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 |
---|---|---|---|---|
font.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 app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use platform::font::{FontHandle, FontTable};
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use smallvec::SmallVec;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::RefCell;
use std::rc::Rc;
use std::str;
use std::sync::Arc;
use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering};
use style::computed_values::{font_stretch, font_variant, font_weight};
use text::Shaper;
use text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore};
use text::shaping::ShaperMethods;
use time;
use unicode_script::Script;
use util::cache::HashCache;
use webrender_traits;
macro_rules! ot_tag {
($t1:expr, $t2:expr, $t3:expr, $t4:expr) => (
(($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32)
);
}
pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S');
pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B');
pub const KERN: u32 = ot_tag!('k', 'e', 'r', 'n');
static TEXT_SHAPING_PERFORMANCE_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
// FontHandle encapsulates access to the platform's font API,
// e.g. quartz, FreeType. It provides access to metrics and tables
// needed by the text shaper as well as access to the underlying font
// resources needed by the graphics layer to draw glyphs.
pub trait FontHandleMethods: Sized {
fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>)
-> Result<Self, ()>;
fn template(&self) -> Arc<FontTemplateData>;
fn family_name(&self) -> String;
fn face_name(&self) -> String;
fn is_italic(&self) -> bool;
fn boldness(&self) -> font_weight::T;
fn stretchiness(&self) -> font_stretch::T;
fn glyph_index(&self, codepoint: char) -> Option<GlyphId>;
fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>;
fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel;
/// Can this font do basic horizontal LTR shaping without Harfbuzz?
fn can_do_fast_shaping(&self) -> bool;
fn metrics(&self) -> FontMetrics;
fn table_for_tag(&self, FontTableTag) -> Option<FontTable>;
}
// Used to abstract over the shaper's choice of fixed int representation.
pub type FractionalPixel = f64;
pub type FontTableTag = u32;
trait FontTableTagConversions {
fn tag_to_str(&self) -> String;
}
impl FontTableTagConversions for FontTableTag {
fn tag_to_str(&self) -> String {
let bytes = [(self >> 24) as u8,
(self >> 16) as u8,
(self >> 8) as u8,
(self >> 0) as u8];
str::from_utf8(&bytes).unwrap().to_owned()
}
}
pub trait FontTableMethods {
fn buffer(&self) -> &[u8];
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FontMetrics {
pub underline_size: Au,
pub underline_offset: Au,
pub strikeout_size: Au,
pub strikeout_offset: Au,
pub leading: Au,
pub x_height: Au,
pub em_size: Au,
pub ascent: Au,
pub descent: Au,
pub max_advance: Au,
pub average_advance: Au,
pub line_gap: Au,
}
#[derive(Debug)]
pub struct Font {
pub handle: FontHandle,
pub metrics: FontMetrics,
pub variant: font_variant::T,
pub descriptor: FontTemplateDescriptor,
pub requested_pt_size: Au,
pub actual_pt_size: Au,
shaper: Option<Shaper>,
shape_cache: RefCell<HashCache<ShapeCacheEntry, Arc<GlyphStore>>>,
glyph_advance_cache: RefCell<HashCache<u32, FractionalPixel>>,
pub font_key: Option<webrender_traits::FontKey>,
}
impl Font {
pub fn new(handle: FontHandle,
variant: font_variant::T,
descriptor: FontTemplateDescriptor,
requested_pt_size: Au,
actual_pt_size: Au,
font_key: Option<webrender_traits::FontKey>) -> Font {
let metrics = handle.metrics();
Font {
handle: handle,
shaper: None,
variant: variant,
descriptor: descriptor,
requested_pt_size: requested_pt_size,
actual_pt_size: actual_pt_size,
metrics: metrics,
shape_cache: RefCell::new(HashCache::new()),
glyph_advance_cache: RefCell::new(HashCache::new()),
font_key: font_key,
}
}
}
bitflags! {
pub flags ShapingFlags: u8 {
#[doc = "Set if the text is entirely whitespace."]
const IS_WHITESPACE_SHAPING_FLAG = 0x01,
#[doc = "Set if we are to ignore ligatures."]
const IGNORE_LIGATURES_SHAPING_FLAG = 0x02,
#[doc = "Set if we are to disable kerning."]
const DISABLE_KERNING_SHAPING_FLAG = 0x04,
#[doc = "Text direction is right-to-left."]
const RTL_FLAG = 0x08,
}
}
/// Various options that control text shaping.
#[derive(Clone, Eq, PartialEq, Hash, Copy, Debug)]
pub struct ShapingOptions {
/// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property.
/// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null.
pub letter_spacing: Option<Au>,
/// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property.
pub word_spacing: Au,
/// The Unicode script property of the characters in this run.
pub script: Script,
/// Various flags.
pub flags: ShapingFlags,
}
/// An entry in the shape cache.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
struct ShapeCacheEntry {
text: String,
options: ShapingOptions,
}
impl Font {
pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> {
let this = self as *const Font;
let mut shaper = self.shaper.take();
let lookup_key = ShapeCacheEntry {
text: text.to_owned(),
options: *options, | options.flags.contains(IS_WHITESPACE_SHAPING_FLAG),
options.flags.contains(RTL_FLAG));
if self.can_do_fast_shaping(text, options) {
debug!("shape_text: Using ASCII fast path.");
self.shape_text_fast(text, options, &mut glyphs);
} else {
debug!("shape_text: Using Harfbuzz.");
if shaper.is_none() {
shaper = Some(Shaper::new(this));
}
shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs);
}
let end_time = time::precise_time_ns();
TEXT_SHAPING_PERFORMANCE_COUNTER.fetch_add((end_time - start_time) as usize,
Ordering::Relaxed);
Arc::new(glyphs)
});
self.shaper = shaper;
result
}
fn can_do_fast_shaping(&self, text: &str, options: &ShapingOptions) -> bool {
options.script == Script::Latin &&
!options.flags.contains(RTL_FLAG) &&
self.handle.can_do_fast_shaping() &&
text.is_ascii()
}
/// Fast path for ASCII text that only needs simple horizontal LTR kerning.
fn shape_text_fast(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
let mut prev_glyph_id = None;
for (i, byte) in text.bytes().enumerate() {
let character = byte as char;
let glyph_id = match self.glyph_index(character) {
Some(id) => id,
None => continue,
};
let mut advance = Au::from_f64_px(self.glyph_h_advance(glyph_id));
if character =='' {
advance += options.word_spacing;
}
if let Some(letter_spacing) = options.letter_spacing {
advance += letter_spacing;
}
let offset = prev_glyph_id.map(|prev| {
let h_kerning = Au::from_f64_px(self.glyph_h_kerning(prev, glyph_id));
advance += h_kerning;
Point2D::new(h_kerning, Au(0))
});
let glyph = GlyphData::new(glyph_id, advance, offset, true, true);
glyphs.add_glyph_for_byte_index(ByteIndex(i as isize), character, &glyph);
prev_glyph_id = Some(glyph_id);
}
glyphs.finalize_changes();
}
pub fn table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> {
let result = self.handle.table_for_tag(tag);
let status = if result.is_some() { "Found" } else { "Didn't find" };
debug!("{} font table[{}] with family={}, face={}",
status, tag.tag_to_str(),
self.handle.family_name(), self.handle.face_name());
result
}
#[inline]
pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> {
let codepoint = match self.variant {
font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938
font_variant::T::normal => codepoint,
};
self.handle.glyph_index(codepoint)
}
pub fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId)
-> FractionalPixel {
self.handle.glyph_h_kerning(first_glyph, second_glyph)
}
pub fn glyph_h_advance(&self, glyph: GlyphId) -> FractionalPixel {
self.glyph_advance_cache.borrow_mut().find_or_create(glyph, || {
match self.handle.glyph_h_advance(glyph) {
Some(adv) => adv,
None => 10f64 as FractionalPixel // FIXME: Need fallback strategy
}
})
}
}
#[derive(Debug)]
pub struct FontGroup {
pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>,
}
impl FontGroup {
pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup {
FontGroup {
fonts: fonts,
}
}
}
pub struct RunMetrics {
// may be negative due to negative width (i.e., kerning of '.' in 'P.T.')
pub advance_width: Au,
pub ascent: Au, // nonzero
pub descent: Au, // nonzero
// this bounding box is relative to the left origin baseline.
// so, bounding_box.position.y = -ascent
pub bounding_box: Rect<Au>
}
impl RunMetrics {
pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics {
let bounds = Rect::new(Point2D::new(Au(0), -ascent),
Size2D::new(advance, ascent + descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent+descent and advance is sometimes too generous and
// looking at actual glyph extents can yield a tighter box.
RunMetrics {
advance_width: advance,
bounding_box: bounds,
ascent: ascent,
descent: descent,
}
}
}
pub fn get_and_reset_text_shaping_performance_counter() -> usize {
let value = TEXT_SHAPING_PERFORMANCE_COUNTER.load(Ordering::SeqCst);
TEXT_SHAPING_PERFORMANCE_COUNTER.store(0, Ordering::SeqCst);
value
} | };
let result = self.shape_cache.borrow_mut().find_or_create(lookup_key, || {
let start_time = time::precise_time_ns();
let mut glyphs = GlyphStore::new(text.len(), | random_line_split |
font.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 app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use platform::font::{FontHandle, FontTable};
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use smallvec::SmallVec;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::RefCell;
use std::rc::Rc;
use std::str;
use std::sync::Arc;
use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering};
use style::computed_values::{font_stretch, font_variant, font_weight};
use text::Shaper;
use text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore};
use text::shaping::ShaperMethods;
use time;
use unicode_script::Script;
use util::cache::HashCache;
use webrender_traits;
macro_rules! ot_tag {
($t1:expr, $t2:expr, $t3:expr, $t4:expr) => (
(($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32)
);
}
pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S');
pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B');
pub const KERN: u32 = ot_tag!('k', 'e', 'r', 'n');
static TEXT_SHAPING_PERFORMANCE_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
// FontHandle encapsulates access to the platform's font API,
// e.g. quartz, FreeType. It provides access to metrics and tables
// needed by the text shaper as well as access to the underlying font
// resources needed by the graphics layer to draw glyphs.
pub trait FontHandleMethods: Sized {
fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>)
-> Result<Self, ()>;
fn template(&self) -> Arc<FontTemplateData>;
fn family_name(&self) -> String;
fn face_name(&self) -> String;
fn is_italic(&self) -> bool;
fn boldness(&self) -> font_weight::T;
fn stretchiness(&self) -> font_stretch::T;
fn glyph_index(&self, codepoint: char) -> Option<GlyphId>;
fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>;
fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel;
/// Can this font do basic horizontal LTR shaping without Harfbuzz?
fn can_do_fast_shaping(&self) -> bool;
fn metrics(&self) -> FontMetrics;
fn table_for_tag(&self, FontTableTag) -> Option<FontTable>;
}
// Used to abstract over the shaper's choice of fixed int representation.
pub type FractionalPixel = f64;
pub type FontTableTag = u32;
trait FontTableTagConversions {
fn tag_to_str(&self) -> String;
}
impl FontTableTagConversions for FontTableTag {
fn tag_to_str(&self) -> String {
let bytes = [(self >> 24) as u8,
(self >> 16) as u8,
(self >> 8) as u8,
(self >> 0) as u8];
str::from_utf8(&bytes).unwrap().to_owned()
}
}
pub trait FontTableMethods {
fn buffer(&self) -> &[u8];
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FontMetrics {
pub underline_size: Au,
pub underline_offset: Au,
pub strikeout_size: Au,
pub strikeout_offset: Au,
pub leading: Au,
pub x_height: Au,
pub em_size: Au,
pub ascent: Au,
pub descent: Au,
pub max_advance: Au,
pub average_advance: Au,
pub line_gap: Au,
}
#[derive(Debug)]
pub struct Font {
pub handle: FontHandle,
pub metrics: FontMetrics,
pub variant: font_variant::T,
pub descriptor: FontTemplateDescriptor,
pub requested_pt_size: Au,
pub actual_pt_size: Au,
shaper: Option<Shaper>,
shape_cache: RefCell<HashCache<ShapeCacheEntry, Arc<GlyphStore>>>,
glyph_advance_cache: RefCell<HashCache<u32, FractionalPixel>>,
pub font_key: Option<webrender_traits::FontKey>,
}
impl Font {
pub fn new(handle: FontHandle,
variant: font_variant::T,
descriptor: FontTemplateDescriptor,
requested_pt_size: Au,
actual_pt_size: Au,
font_key: Option<webrender_traits::FontKey>) -> Font {
let metrics = handle.metrics();
Font {
handle: handle,
shaper: None,
variant: variant,
descriptor: descriptor,
requested_pt_size: requested_pt_size,
actual_pt_size: actual_pt_size,
metrics: metrics,
shape_cache: RefCell::new(HashCache::new()),
glyph_advance_cache: RefCell::new(HashCache::new()),
font_key: font_key,
}
}
}
bitflags! {
pub flags ShapingFlags: u8 {
#[doc = "Set if the text is entirely whitespace."]
const IS_WHITESPACE_SHAPING_FLAG = 0x01,
#[doc = "Set if we are to ignore ligatures."]
const IGNORE_LIGATURES_SHAPING_FLAG = 0x02,
#[doc = "Set if we are to disable kerning."]
const DISABLE_KERNING_SHAPING_FLAG = 0x04,
#[doc = "Text direction is right-to-left."]
const RTL_FLAG = 0x08,
}
}
/// Various options that control text shaping.
#[derive(Clone, Eq, PartialEq, Hash, Copy, Debug)]
pub struct ShapingOptions {
/// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property.
/// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null.
pub letter_spacing: Option<Au>,
/// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property.
pub word_spacing: Au,
/// The Unicode script property of the characters in this run.
pub script: Script,
/// Various flags.
pub flags: ShapingFlags,
}
/// An entry in the shape cache.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
struct ShapeCacheEntry {
text: String,
options: ShapingOptions,
}
impl Font {
pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> {
let this = self as *const Font;
let mut shaper = self.shaper.take();
let lookup_key = ShapeCacheEntry {
text: text.to_owned(),
options: *options,
};
let result = self.shape_cache.borrow_mut().find_or_create(lookup_key, || {
let start_time = time::precise_time_ns();
let mut glyphs = GlyphStore::new(text.len(),
options.flags.contains(IS_WHITESPACE_SHAPING_FLAG),
options.flags.contains(RTL_FLAG));
if self.can_do_fast_shaping(text, options) {
debug!("shape_text: Using ASCII fast path.");
self.shape_text_fast(text, options, &mut glyphs);
} else {
debug!("shape_text: Using Harfbuzz.");
if shaper.is_none() {
shaper = Some(Shaper::new(this));
}
shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs);
}
let end_time = time::precise_time_ns();
TEXT_SHAPING_PERFORMANCE_COUNTER.fetch_add((end_time - start_time) as usize,
Ordering::Relaxed);
Arc::new(glyphs)
});
self.shaper = shaper;
result
}
fn can_do_fast_shaping(&self, text: &str, options: &ShapingOptions) -> bool {
options.script == Script::Latin &&
!options.flags.contains(RTL_FLAG) &&
self.handle.can_do_fast_shaping() &&
text.is_ascii()
}
/// Fast path for ASCII text that only needs simple horizontal LTR kerning.
fn | (&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
let mut prev_glyph_id = None;
for (i, byte) in text.bytes().enumerate() {
let character = byte as char;
let glyph_id = match self.glyph_index(character) {
Some(id) => id,
None => continue,
};
let mut advance = Au::from_f64_px(self.glyph_h_advance(glyph_id));
if character =='' {
advance += options.word_spacing;
}
if let Some(letter_spacing) = options.letter_spacing {
advance += letter_spacing;
}
let offset = prev_glyph_id.map(|prev| {
let h_kerning = Au::from_f64_px(self.glyph_h_kerning(prev, glyph_id));
advance += h_kerning;
Point2D::new(h_kerning, Au(0))
});
let glyph = GlyphData::new(glyph_id, advance, offset, true, true);
glyphs.add_glyph_for_byte_index(ByteIndex(i as isize), character, &glyph);
prev_glyph_id = Some(glyph_id);
}
glyphs.finalize_changes();
}
pub fn table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> {
let result = self.handle.table_for_tag(tag);
let status = if result.is_some() { "Found" } else { "Didn't find" };
debug!("{} font table[{}] with family={}, face={}",
status, tag.tag_to_str(),
self.handle.family_name(), self.handle.face_name());
result
}
#[inline]
pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> {
let codepoint = match self.variant {
font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938
font_variant::T::normal => codepoint,
};
self.handle.glyph_index(codepoint)
}
pub fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId)
-> FractionalPixel {
self.handle.glyph_h_kerning(first_glyph, second_glyph)
}
pub fn glyph_h_advance(&self, glyph: GlyphId) -> FractionalPixel {
self.glyph_advance_cache.borrow_mut().find_or_create(glyph, || {
match self.handle.glyph_h_advance(glyph) {
Some(adv) => adv,
None => 10f64 as FractionalPixel // FIXME: Need fallback strategy
}
})
}
}
#[derive(Debug)]
pub struct FontGroup {
pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>,
}
impl FontGroup {
pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup {
FontGroup {
fonts: fonts,
}
}
}
pub struct RunMetrics {
// may be negative due to negative width (i.e., kerning of '.' in 'P.T.')
pub advance_width: Au,
pub ascent: Au, // nonzero
pub descent: Au, // nonzero
// this bounding box is relative to the left origin baseline.
// so, bounding_box.position.y = -ascent
pub bounding_box: Rect<Au>
}
impl RunMetrics {
pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics {
let bounds = Rect::new(Point2D::new(Au(0), -ascent),
Size2D::new(advance, ascent + descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent+descent and advance is sometimes too generous and
// looking at actual glyph extents can yield a tighter box.
RunMetrics {
advance_width: advance,
bounding_box: bounds,
ascent: ascent,
descent: descent,
}
}
}
pub fn get_and_reset_text_shaping_performance_counter() -> usize {
let value = TEXT_SHAPING_PERFORMANCE_COUNTER.load(Ordering::SeqCst);
TEXT_SHAPING_PERFORMANCE_COUNTER.store(0, Ordering::SeqCst);
value
}
| shape_text_fast | identifier_name |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *};
use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task;
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
scheduler: Scheduler<Task>,
}
impl Service {
/// Create a new backup service.
pub fn new(scheduler: Scheduler<Task>) -> Service {
Service { scheduler }
}
}
impl Backup for Service {
fn backup(
&mut self,
ctx: RpcContext,
req: BackupRequest,
mut sink: ServerStreamingSink<BackupResponse>,
) {
let mut cancel = None;
// TODO: make it a bounded channel.
let (tx, rx) = mpsc::unbounded();
if let Err(status) = match Task::new(req, tx) {
Ok((task, c)) => {
cancel = Some(c);
self.scheduler.schedule(task).map_err(|e| {
RpcStatus::new(RpcStatusCode::INVALID_ARGUMENT, Some(format!("{:?}", e)))
})
}
Err(e) => Err(RpcStatus::new(
RpcStatusCode::UNKNOWN,
Some(format!("{:?}", e)),
)),
} {
error!("backup task initiate failed"; "error" =>?status);
ctx.spawn(
sink.fail(status)
.unwrap_or_else(|e| error!("backup failed to send error"; "error" =>?e)),
);
return;
};
let send_task = async move {
let mut s = rx.map(|resp| Ok((resp, WriteFlags::default())));
sink.send_all(&mut s).await?;
sink.close().await?;
Ok(())
}
.map(|res: Result<()>| {
match res {
Ok(_) => {
info!("backup closed");
}
Err(e) => {
if let Some(c) = cancel {
// Cancel the running task.
c.store(true, Ordering::SeqCst);
}
error!("backup canceled"; "error" =>?e);
}
}
});
ctx.spawn(send_task);
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use super::*;
use crate::endpoint::tests::*;
use external_storage::make_local_backend;
use tikv::storage::txn::tests::{must_commit, must_prewrite_put};
use tikv_util::worker::{dummy_scheduler, ReceiverWrapper};
use txn_types::TimeStamp;
fn new_rpc_suite() -> (Server, BackupClient, ReceiverWrapper<Task>) {
let env = Arc::new(EnvBuilder::new().build());
let (scheduler, rx) = dummy_scheduler();
let backup_service = super::Service::new(scheduler);
let builder =
ServerBuilder::new(env.clone()).register_service(create_backup(backup_service));
let mut server = builder.bind("127.0.0.1", 0).build().unwrap();
server.start();
let (_, port) = server.bind_addrs().next().unwrap();
let addr = format!("127.0.0.1:{}", port);
let channel = ChannelBuilder::new(env).connect(&addr);
let client = BackupClient::new(channel);
(server, client, rx)
}
#[test]
fn | () {
let (_server, client, mut rx) = new_rpc_suite();
let (tmp, endpoint) = new_endpoint();
let engine = endpoint.engine.clone();
endpoint.region_info.set_regions(vec![
(b"".to_vec(), b"2".to_vec(), 1),
(b"2".to_vec(), b"5".to_vec(), 2),
]);
let mut ts: TimeStamp = 1.into();
let mut alloc_ts = || *ts.incr();
for i in 0..5 {
let start = alloc_ts();
let key = format!("{}", i);
must_prewrite_put(
&engine,
key.as_bytes(),
key.as_bytes(),
key.as_bytes(),
start,
);
let commit = alloc_ts();
must_commit(&engine, key.as_bytes(), start, commit);
}
let now = alloc_ts();
let mut req = BackupRequest::default();
req.set_start_key(vec![]);
req.set_end_key(vec![b'5']);
req.set_start_version(now.into_inner());
req.set_end_version(now.into_inner());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(now.to_string())));
let stream = client.backup(&req).unwrap();
let task = rx.recv_timeout(Duration::from_secs(5)).unwrap();
// Drop stream without start receiving will cause cancel error.
drop(stream);
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task.unwrap());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(alloc_ts().to_string())));
let mut stream = client.backup(&req).unwrap();
// Drop steam once it received something.
client.spawn(async move {
let _ = stream.next().await;
});
let task = rx.recv_timeout(Duration::from_secs(5)).unwrap();
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task.unwrap());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(alloc_ts().to_string())));
let stream = client.backup(&req).unwrap();
let task = rx.recv().unwrap();
// Drop stream without start receiving will cause cancel error.
drop(stream);
// Wait util the task is canceled in map_err.
loop {
std::thread::sleep(Duration::from_millis(100));
if task.resp.unbounded_send(Default::default()).is_err() {
break;
}
}
// The task should be canceled.
assert!(task.has_canceled());
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task);
}
}
| test_client_stop | identifier_name |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *}; |
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
scheduler: Scheduler<Task>,
}
impl Service {
/// Create a new backup service.
pub fn new(scheduler: Scheduler<Task>) -> Service {
Service { scheduler }
}
}
impl Backup for Service {
fn backup(
&mut self,
ctx: RpcContext,
req: BackupRequest,
mut sink: ServerStreamingSink<BackupResponse>,
) {
let mut cancel = None;
// TODO: make it a bounded channel.
let (tx, rx) = mpsc::unbounded();
if let Err(status) = match Task::new(req, tx) {
Ok((task, c)) => {
cancel = Some(c);
self.scheduler.schedule(task).map_err(|e| {
RpcStatus::new(RpcStatusCode::INVALID_ARGUMENT, Some(format!("{:?}", e)))
})
}
Err(e) => Err(RpcStatus::new(
RpcStatusCode::UNKNOWN,
Some(format!("{:?}", e)),
)),
} {
error!("backup task initiate failed"; "error" =>?status);
ctx.spawn(
sink.fail(status)
.unwrap_or_else(|e| error!("backup failed to send error"; "error" =>?e)),
);
return;
};
let send_task = async move {
let mut s = rx.map(|resp| Ok((resp, WriteFlags::default())));
sink.send_all(&mut s).await?;
sink.close().await?;
Ok(())
}
.map(|res: Result<()>| {
match res {
Ok(_) => {
info!("backup closed");
}
Err(e) => {
if let Some(c) = cancel {
// Cancel the running task.
c.store(true, Ordering::SeqCst);
}
error!("backup canceled"; "error" =>?e);
}
}
});
ctx.spawn(send_task);
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use super::*;
use crate::endpoint::tests::*;
use external_storage::make_local_backend;
use tikv::storage::txn::tests::{must_commit, must_prewrite_put};
use tikv_util::worker::{dummy_scheduler, ReceiverWrapper};
use txn_types::TimeStamp;
fn new_rpc_suite() -> (Server, BackupClient, ReceiverWrapper<Task>) {
let env = Arc::new(EnvBuilder::new().build());
let (scheduler, rx) = dummy_scheduler();
let backup_service = super::Service::new(scheduler);
let builder =
ServerBuilder::new(env.clone()).register_service(create_backup(backup_service));
let mut server = builder.bind("127.0.0.1", 0).build().unwrap();
server.start();
let (_, port) = server.bind_addrs().next().unwrap();
let addr = format!("127.0.0.1:{}", port);
let channel = ChannelBuilder::new(env).connect(&addr);
let client = BackupClient::new(channel);
(server, client, rx)
}
#[test]
fn test_client_stop() {
let (_server, client, mut rx) = new_rpc_suite();
let (tmp, endpoint) = new_endpoint();
let engine = endpoint.engine.clone();
endpoint.region_info.set_regions(vec![
(b"".to_vec(), b"2".to_vec(), 1),
(b"2".to_vec(), b"5".to_vec(), 2),
]);
let mut ts: TimeStamp = 1.into();
let mut alloc_ts = || *ts.incr();
for i in 0..5 {
let start = alloc_ts();
let key = format!("{}", i);
must_prewrite_put(
&engine,
key.as_bytes(),
key.as_bytes(),
key.as_bytes(),
start,
);
let commit = alloc_ts();
must_commit(&engine, key.as_bytes(), start, commit);
}
let now = alloc_ts();
let mut req = BackupRequest::default();
req.set_start_key(vec![]);
req.set_end_key(vec![b'5']);
req.set_start_version(now.into_inner());
req.set_end_version(now.into_inner());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(now.to_string())));
let stream = client.backup(&req).unwrap();
let task = rx.recv_timeout(Duration::from_secs(5)).unwrap();
// Drop stream without start receiving will cause cancel error.
drop(stream);
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task.unwrap());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(alloc_ts().to_string())));
let mut stream = client.backup(&req).unwrap();
// Drop steam once it received something.
client.spawn(async move {
let _ = stream.next().await;
});
let task = rx.recv_timeout(Duration::from_secs(5)).unwrap();
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task.unwrap());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(alloc_ts().to_string())));
let stream = client.backup(&req).unwrap();
let task = rx.recv().unwrap();
// Drop stream without start receiving will cause cancel error.
drop(stream);
// Wait util the task is canceled in map_err.
loop {
std::thread::sleep(Duration::from_millis(100));
if task.resp.unbounded_send(Default::default()).is_err() {
break;
}
}
// The task should be canceled.
assert!(task.has_canceled());
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task);
}
} | use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task; | random_line_split |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *};
use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task;
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
scheduler: Scheduler<Task>,
}
impl Service {
/// Create a new backup service.
pub fn new(scheduler: Scheduler<Task>) -> Service {
Service { scheduler }
}
}
impl Backup for Service {
fn backup(
&mut self,
ctx: RpcContext,
req: BackupRequest,
mut sink: ServerStreamingSink<BackupResponse>,
) {
let mut cancel = None;
// TODO: make it a bounded channel.
let (tx, rx) = mpsc::unbounded();
if let Err(status) = match Task::new(req, tx) {
Ok((task, c)) => {
cancel = Some(c);
self.scheduler.schedule(task).map_err(|e| {
RpcStatus::new(RpcStatusCode::INVALID_ARGUMENT, Some(format!("{:?}", e)))
})
}
Err(e) => Err(RpcStatus::new(
RpcStatusCode::UNKNOWN,
Some(format!("{:?}", e)),
)),
} {
error!("backup task initiate failed"; "error" =>?status);
ctx.spawn(
sink.fail(status)
.unwrap_or_else(|e| error!("backup failed to send error"; "error" =>?e)),
);
return;
};
let send_task = async move {
let mut s = rx.map(|resp| Ok((resp, WriteFlags::default())));
sink.send_all(&mut s).await?;
sink.close().await?;
Ok(())
}
.map(|res: Result<()>| {
match res {
Ok(_) => {
info!("backup closed");
}
Err(e) => {
if let Some(c) = cancel {
// Cancel the running task.
c.store(true, Ordering::SeqCst);
}
error!("backup canceled"; "error" =>?e);
}
}
});
ctx.spawn(send_task);
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use super::*;
use crate::endpoint::tests::*;
use external_storage::make_local_backend;
use tikv::storage::txn::tests::{must_commit, must_prewrite_put};
use tikv_util::worker::{dummy_scheduler, ReceiverWrapper};
use txn_types::TimeStamp;
fn new_rpc_suite() -> (Server, BackupClient, ReceiverWrapper<Task>) |
#[test]
fn test_client_stop() {
let (_server, client, mut rx) = new_rpc_suite();
let (tmp, endpoint) = new_endpoint();
let engine = endpoint.engine.clone();
endpoint.region_info.set_regions(vec![
(b"".to_vec(), b"2".to_vec(), 1),
(b"2".to_vec(), b"5".to_vec(), 2),
]);
let mut ts: TimeStamp = 1.into();
let mut alloc_ts = || *ts.incr();
for i in 0..5 {
let start = alloc_ts();
let key = format!("{}", i);
must_prewrite_put(
&engine,
key.as_bytes(),
key.as_bytes(),
key.as_bytes(),
start,
);
let commit = alloc_ts();
must_commit(&engine, key.as_bytes(), start, commit);
}
let now = alloc_ts();
let mut req = BackupRequest::default();
req.set_start_key(vec![]);
req.set_end_key(vec![b'5']);
req.set_start_version(now.into_inner());
req.set_end_version(now.into_inner());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(now.to_string())));
let stream = client.backup(&req).unwrap();
let task = rx.recv_timeout(Duration::from_secs(5)).unwrap();
// Drop stream without start receiving will cause cancel error.
drop(stream);
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task.unwrap());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(alloc_ts().to_string())));
let mut stream = client.backup(&req).unwrap();
// Drop steam once it received something.
client.spawn(async move {
let _ = stream.next().await;
});
let task = rx.recv_timeout(Duration::from_secs(5)).unwrap();
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task.unwrap());
// Set an unique path to avoid AlreadyExists error.
req.set_storage_backend(make_local_backend(&tmp.path().join(alloc_ts().to_string())));
let stream = client.backup(&req).unwrap();
let task = rx.recv().unwrap();
// Drop stream without start receiving will cause cancel error.
drop(stream);
// Wait util the task is canceled in map_err.
loop {
std::thread::sleep(Duration::from_millis(100));
if task.resp.unbounded_send(Default::default()).is_err() {
break;
}
}
// The task should be canceled.
assert!(task.has_canceled());
// A stopped remote must not cause panic.
endpoint.handle_backup_task(task);
}
}
| {
let env = Arc::new(EnvBuilder::new().build());
let (scheduler, rx) = dummy_scheduler();
let backup_service = super::Service::new(scheduler);
let builder =
ServerBuilder::new(env.clone()).register_service(create_backup(backup_service));
let mut server = builder.bind("127.0.0.1", 0).build().unwrap();
server.start();
let (_, port) = server.bind_addrs().next().unwrap();
let addr = format!("127.0.0.1:{}", port);
let channel = ChannelBuilder::new(env).connect(&addr);
let client = BackupClient::new(channel);
(server, client, rx)
} | identifier_body |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn test_success() |
#[test]
fn test_failure() {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, dir.path()).is_err());
assert!(util::ensure_file_content(&file1, b"content1").expect("Could not read file"));
}
| {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
util::create_file_with_content(&file2, b"content2").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, &file2).is_ok());
assert!(util::ensure_file_content(&file1, b"content2").expect("Could not read file"));
assert!(util::ensure_file_content(&file2, b"content1").expect("Could not read file"));
} | identifier_body |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn test_success() {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
util::create_file_with_content(&file2, b"content2").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, &file2).is_ok());
assert!(util::ensure_file_content(&file1, b"content2").expect("Could not read file"));
assert!(util::ensure_file_content(&file2, b"content1").expect("Could not read file"));
}
| let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, dir.path()).is_err());
assert!(util::ensure_file_content(&file1, b"content1").expect("Could not read file"));
} | #[test]
fn test_failure() { | random_line_split |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn | () {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
util::create_file_with_content(&file2, b"content2").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, &file2).is_ok());
assert!(util::ensure_file_content(&file1, b"content2").expect("Could not read file"));
assert!(util::ensure_file_content(&file2, b"content1").expect("Could not read file"));
}
#[test]
fn test_failure() {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, dir.path()).is_err());
assert!(util::ensure_file_content(&file1, b"content1").expect("Could not read file"));
}
| test_success | identifier_name |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Returns the amount of connections from an input with the given id
pub fn get_input_copies(&self, id: usize) -> usize {
self.network.genome.iter().fold(0, |acc, g| {
if let GeneExtras::Input(_) = (*g).variant {
acc + ((g.id == id) as usize)
} else {
acc
}
})
}
// Returns a vector with each element being the length of the shortest path between the
// corresponding neuron and the nearest output
pub fn get_depths(&self, include_connections: bool) -> Vec<usize> {
let mut depths = Vec::new();
let mut stack = Vec::new();
for gene in &self.network.genome {
let depth = stack.len();
if let GeneExtras::Neuron(_, ref inputs) = gene.variant | else {
if include_connections {
depths.push(depth);
}
while let Some(&1) = stack.last() {
stack.pop();
}
if let Some(last) = stack.last_mut() {
*last -= 1;
}
}
}
depths
}
pub fn random_index(&self) -> usize {
let indices = (0..self.next_id).map(|i| {
self.network.get_neuron_index(i).unwrap()
}).collect::<Vec<usize>>();
*thread_rng().choose(&indices).unwrap()
}
pub fn subnetwork_index(&self, index: usize) -> ops::Range<usize> {
let mut i = index;
let mut sum = 0;
while sum!= 1 {
if let GeneExtras::Neuron(_, ref inputs) = self.network.genome[i].variant {
sum += 1 - *inputs as i32;
} else {
sum += 1;
}
i += 1;
}
ops::Range {
start: index,
end: i
}
}
}
// Wrap the Network implementation, to adjust the gene_ages field as well as the genome
impl<T: NNFitnessFunction + Clone> Mutation for Individual<T> {
// Inputs and outputs aren't used; read from field instead
fn add_subnetwork(&mut self, _: usize, output: usize, _: usize) {
self.network.add_subnetwork(self.next_id, output, self.inputs);
if let GeneExtras::Neuron(_, ref inputs) = self.network.genome[output].variant {
for _ in 0..*inputs + 1 {
self.ages.insert(output, 0);
}
}
self.next_id += 1;
}
fn add_forward(&mut self, input: usize, output: usize) {
self.network.add_forward(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_recurrent(&mut self, input: usize, output: usize) {
self.network.add_recurrent(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_bias(&mut self, output: usize) {
self.network.add_bias(output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_input(&mut self, input: usize, output: usize) {
self.network.add_input(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn remove_connection(&mut self, index: usize, output: usize) {
self.network.remove_connection(index, output);
// Remove the age associated with the removed connection
self.ages.remove(index);
}
// does not need to be implemented
fn previous_neuron_index(&self, _: usize) -> Option<usize> {
unimplemented!();
}
}
| {
depths.push(depth);
stack.push(*inputs);
} | conditional_block |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Returns the amount of connections from an input with the given id
pub fn | (&self, id: usize) -> usize {
self.network.genome.iter().fold(0, |acc, g| {
if let GeneExtras::Input(_) = (*g).variant {
acc + ((g.id == id) as usize)
} else {
acc
}
})
}
// Returns a vector with each element being the length of the shortest path between the
// corresponding neuron and the nearest output
pub fn get_depths(&self, include_connections: bool) -> Vec<usize> {
let mut depths = Vec::new();
let mut stack = Vec::new();
for gene in &self.network.genome {
let depth = stack.len();
if let GeneExtras::Neuron(_, ref inputs) = gene.variant {
depths.push(depth);
stack.push(*inputs);
} else {
if include_connections {
depths.push(depth);
}
while let Some(&1) = stack.last() {
stack.pop();
}
if let Some(last) = stack.last_mut() {
*last -= 1;
}
}
}
depths
}
pub fn random_index(&self) -> usize {
let indices = (0..self.next_id).map(|i| {
self.network.get_neuron_index(i).unwrap()
}).collect::<Vec<usize>>();
*thread_rng().choose(&indices).unwrap()
}
pub fn subnetwork_index(&self, index: usize) -> ops::Range<usize> {
let mut i = index;
let mut sum = 0;
while sum!= 1 {
if let GeneExtras::Neuron(_, ref inputs) = self.network.genome[i].variant {
sum += 1 - *inputs as i32;
} else {
sum += 1;
}
i += 1;
}
ops::Range {
start: index,
end: i
}
}
}
// Wrap the Network implementation, to adjust the gene_ages field as well as the genome
impl<T: NNFitnessFunction + Clone> Mutation for Individual<T> {
// Inputs and outputs aren't used; read from field instead
fn add_subnetwork(&mut self, _: usize, output: usize, _: usize) {
self.network.add_subnetwork(self.next_id, output, self.inputs);
if let GeneExtras::Neuron(_, ref inputs) = self.network.genome[output].variant {
for _ in 0..*inputs + 1 {
self.ages.insert(output, 0);
}
}
self.next_id += 1;
}
fn add_forward(&mut self, input: usize, output: usize) {
self.network.add_forward(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_recurrent(&mut self, input: usize, output: usize) {
self.network.add_recurrent(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_bias(&mut self, output: usize) {
self.network.add_bias(output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_input(&mut self, input: usize, output: usize) {
self.network.add_input(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn remove_connection(&mut self, index: usize, output: usize) {
self.network.remove_connection(index, output);
// Remove the age associated with the removed connection
self.ages.remove(index);
}
// does not need to be implemented
fn previous_neuron_index(&self, _: usize) -> Option<usize> {
unimplemented!();
}
}
| get_input_copies | identifier_name |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Returns the amount of connections from an input with the given id
pub fn get_input_copies(&self, id: usize) -> usize {
self.network.genome.iter().fold(0, |acc, g| {
if let GeneExtras::Input(_) = (*g).variant {
acc + ((g.id == id) as usize)
} else {
acc
}
})
}
// Returns a vector with each element being the length of the shortest path between the
// corresponding neuron and the nearest output
pub fn get_depths(&self, include_connections: bool) -> Vec<usize> {
let mut depths = Vec::new();
let mut stack = Vec::new();
for gene in &self.network.genome {
let depth = stack.len();
if let GeneExtras::Neuron(_, ref inputs) = gene.variant {
depths.push(depth);
stack.push(*inputs);
} else {
if include_connections {
depths.push(depth);
}
while let Some(&1) = stack.last() {
stack.pop();
}
if let Some(last) = stack.last_mut() {
*last -= 1;
}
}
}
depths
}
pub fn random_index(&self) -> usize {
let indices = (0..self.next_id).map(|i| {
self.network.get_neuron_index(i).unwrap()
}).collect::<Vec<usize>>();
*thread_rng().choose(&indices).unwrap()
}
pub fn subnetwork_index(&self, index: usize) -> ops::Range<usize> {
let mut i = index;
let mut sum = 0;
while sum!= 1 {
if let GeneExtras::Neuron(_, ref inputs) = self.network.genome[i].variant {
sum += 1 - *inputs as i32;
} else {
sum += 1;
}
i += 1;
}
ops::Range {
start: index,
end: i
}
}
}
// Wrap the Network implementation, to adjust the gene_ages field as well as the genome
impl<T: NNFitnessFunction + Clone> Mutation for Individual<T> {
// Inputs and outputs aren't used; read from field instead
fn add_subnetwork(&mut self, _: usize, output: usize, _: usize) {
self.network.add_subnetwork(self.next_id, output, self.inputs);
if let GeneExtras::Neuron(_, ref inputs) = self.network.genome[output].variant {
for _ in 0..*inputs + 1 {
self.ages.insert(output, 0);
}
}
self.next_id += 1;
}
fn add_forward(&mut self, input: usize, output: usize) {
self.network.add_forward(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_recurrent(&mut self, input: usize, output: usize) {
self.network.add_recurrent(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_bias(&mut self, output: usize) {
self.network.add_bias(output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_input(&mut self, input: usize, output: usize) {
self.network.add_input(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn remove_connection(&mut self, index: usize, output: usize) {
self.network.remove_connection(index, output);
// Remove the age associated with the removed connection
self.ages.remove(index);
}
| // does not need to be implemented
fn previous_neuron_index(&self, _: usize) -> Option<usize> {
unimplemented!();
}
} | random_line_split |
|
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Returns the amount of connections from an input with the given id
pub fn get_input_copies(&self, id: usize) -> usize {
self.network.genome.iter().fold(0, |acc, g| {
if let GeneExtras::Input(_) = (*g).variant {
acc + ((g.id == id) as usize)
} else {
acc
}
})
}
// Returns a vector with each element being the length of the shortest path between the
// corresponding neuron and the nearest output
pub fn get_depths(&self, include_connections: bool) -> Vec<usize> | }
}
depths
}
pub fn random_index(&self) -> usize {
let indices = (0..self.next_id).map(|i| {
self.network.get_neuron_index(i).unwrap()
}).collect::<Vec<usize>>();
*thread_rng().choose(&indices).unwrap()
}
pub fn subnetwork_index(&self, index: usize) -> ops::Range<usize> {
let mut i = index;
let mut sum = 0;
while sum!= 1 {
if let GeneExtras::Neuron(_, ref inputs) = self.network.genome[i].variant {
sum += 1 - *inputs as i32;
} else {
sum += 1;
}
i += 1;
}
ops::Range {
start: index,
end: i
}
}
}
// Wrap the Network implementation, to adjust the gene_ages field as well as the genome
impl<T: NNFitnessFunction + Clone> Mutation for Individual<T> {
// Inputs and outputs aren't used; read from field instead
fn add_subnetwork(&mut self, _: usize, output: usize, _: usize) {
self.network.add_subnetwork(self.next_id, output, self.inputs);
if let GeneExtras::Neuron(_, ref inputs) = self.network.genome[output].variant {
for _ in 0..*inputs + 1 {
self.ages.insert(output, 0);
}
}
self.next_id += 1;
}
fn add_forward(&mut self, input: usize, output: usize) {
self.network.add_forward(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_recurrent(&mut self, input: usize, output: usize) {
self.network.add_recurrent(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_bias(&mut self, output: usize) {
self.network.add_bias(output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn add_input(&mut self, input: usize, output: usize) {
self.network.add_input(input, output);
// Add an age associated with the new connection
self.ages.insert(output, 0);
}
fn remove_connection(&mut self, index: usize, output: usize) {
self.network.remove_connection(index, output);
// Remove the age associated with the removed connection
self.ages.remove(index);
}
// does not need to be implemented
fn previous_neuron_index(&self, _: usize) -> Option<usize> {
unimplemented!();
}
}
| {
let mut depths = Vec::new();
let mut stack = Vec::new();
for gene in &self.network.genome {
let depth = stack.len();
if let GeneExtras::Neuron(_, ref inputs) = gene.variant {
depths.push(depth);
stack.push(*inputs);
} else {
if include_connections {
depths.push(depth);
}
while let Some(&1) = stack.last() {
stack.pop();
}
if let Some(last) = stack.last_mut() {
*last -= 1;
} | identifier_body |
mod.rs | use communication::Message;
pub use self::counter::Counter;
pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must constantly check this. This complicates data exchange, which
/// may conservatively over-flush, if the defensive implementation isn't well done (e.g. now).
/// An alternate design is for a Pullable<T, D> to return a (&T, Session<D>), where Session<D> is a
/// new type implementing Iterator<Item=Message<D>>, or Iterator<Item=D>, or PullableSession<D>, or
/// something like that. Ideally, the Session<D> notice how many records are consumed, and only
/// treats those res
pub trait Pullable<T, D> {
fn pull(&mut self) -> Option<(&T, &mut Message<D>)>;
}
impl<T, D, P:?Sized + Pullable<T, D>> Pullable<T, D> for Box<P> {
fn pull(&mut self) -> Option<(&T, &mut Message<D>)> |
}
| { (**self).pull() } | identifier_body |
mod.rs | use communication::Message;
pub use self::counter::Counter;
pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must constantly check this. This complicates data exchange, which
/// may conservatively over-flush, if the defensive implementation isn't well done (e.g. now).
/// An alternate design is for a Pullable<T, D> to return a (&T, Session<D>), where Session<D> is a
/// new type implementing Iterator<Item=Message<D>>, or Iterator<Item=D>, or PullableSession<D>, or
/// something like that. Ideally, the Session<D> notice how many records are consumed, and only
/// treats those res
pub trait Pullable<T, D> {
fn pull(&mut self) -> Option<(&T, &mut Message<D>)>;
}
impl<T, D, P:?Sized + Pullable<T, D>> Pullable<T, D> for Box<P> {
fn | (&mut self) -> Option<(&T, &mut Message<D>)> { (**self).pull() }
}
| pull | identifier_name |
mod.rs | use communication::Message;
pub use self::counter::Counter;
| /// may conservatively over-flush, if the defensive implementation isn't well done (e.g. now).
/// An alternate design is for a Pullable<T, D> to return a (&T, Session<D>), where Session<D> is a
/// new type implementing Iterator<Item=Message<D>>, or Iterator<Item=D>, or PullableSession<D>, or
/// something like that. Ideally, the Session<D> notice how many records are consumed, and only
/// treats those res
pub trait Pullable<T, D> {
fn pull(&mut self) -> Option<(&T, &mut Message<D>)>;
}
impl<T, D, P:?Sized + Pullable<T, D>> Pullable<T, D> for Box<P> {
fn pull(&mut self) -> Option<(&T, &mut Message<D>)> { (**self).pull() }
} | pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must constantly check this. This complicates data exchange, which | random_line_split |
movemant.rs | extern crate ggez;
extern crate rand;
use rand::Rng;
use ggez::graphics::{Point};
use ::MainState;
#[derive(Clone)]
pub struct Rabbit{
pub x:i32,
pub y:i32,
pub point:Point,
}
pub fn | (tself:&mut MainState){
let mut next_rabbits = Vec::new();
for obj in tself.rabbits_hash.iter(){
let cor_prev = obj.1;
let rab = rabbit_run(cor_prev);
let mut cor_next = rab.0;
cor_next.point = match tself.map_hash.get(&(cor_next.x, cor_next.y)) {
Some(n) => *n,
None => Point{x:150.0,y:150.0},
};
//println!("Rabbit({},{},{}) go {}, prev:{},{}; next:{},{}",(obj.0).0,(obj.0).1,(obj.0).2, rab.1, cor_prev.x, cor_prev.y, cor_next.x, cor_next.y);
//println!("next:{},{}", cor_next.x, cor_next.y);
//println!("next point:{},{}", &next_point.x, &next_point.y);
next_rabbits.push( ( *obj.0, cor_next ) );
};
for rabbit in next_rabbits{
tself.rabbits_hash.remove( &rabbit.0 );
tself.rabbits_hash.insert( ((rabbit.0).0, (rabbit.0).1, (rabbit.0).2), rabbit.1 );
}
}
pub fn rabbit_run (cor_prev:& Rabbit)-> (Rabbit, &str){
let not_run = Rabbit{
x:cor_prev.x,
y:cor_prev.y,
point: cor_prev.point,
};
let left = Rabbit{
x: (cor_prev.x - 1),
y: cor_prev.y,
point: cor_prev.point,
};
let right = Rabbit{
x: (cor_prev.x + 1),
y: cor_prev.y,
point: cor_prev.point,
};
let up_left = Rabbit{
x: (cor_prev.x - 1),
y: (cor_prev.y - 1),
point: cor_prev.point,
};
let down_right = Rabbit{
x: (cor_prev.x + 1),
y: (cor_prev.y + 1),
point: cor_prev.point,
};
let false_random = rand::thread_rng().gen_range(0, 5);
let variants = [
(not_run, "not_run"),
(left, "left"),
(right, "right"),
(up_left, "up_left"),
(down_right, "down_right"),
];
let lets_go = variants[false_random].clone();
/*if (lets_go.0.x > 4) || (lets_go.0.y < -4){
return variants[0].clone();
}*/
return lets_go
} | rabbits_run | identifier_name |
movemant.rs | extern crate ggez;
extern crate rand;
use rand::Rng;
use ggez::graphics::{Point};
use ::MainState;
#[derive(Clone)]
pub struct Rabbit{
pub x:i32,
pub y:i32,
pub point:Point,
}
pub fn rabbits_run (tself:&mut MainState){
let mut next_rabbits = Vec::new();
for obj in tself.rabbits_hash.iter(){
let cor_prev = obj.1;
let rab = rabbit_run(cor_prev);
let mut cor_next = rab.0;
cor_next.point = match tself.map_hash.get(&(cor_next.x, cor_next.y)) {
Some(n) => *n,
None => Point{x:150.0,y:150.0},
};
//println!("Rabbit({},{},{}) go {}, prev:{},{}; next:{},{}",(obj.0).0,(obj.0).1,(obj.0).2, rab.1, cor_prev.x, cor_prev.y, cor_next.x, cor_next.y);
//println!("next:{},{}", cor_next.x, cor_next.y);
//println!("next point:{},{}", &next_point.x, &next_point.y);
next_rabbits.push( ( *obj.0, cor_next ) );
};
for rabbit in next_rabbits{
tself.rabbits_hash.remove( &rabbit.0 );
tself.rabbits_hash.insert( ((rabbit.0).0, (rabbit.0).1, (rabbit.0).2), rabbit.1 );
}
}
pub fn rabbit_run (cor_prev:& Rabbit)-> (Rabbit, &str){
let not_run = Rabbit{
x:cor_prev.x,
y:cor_prev.y,
point: cor_prev.point,
};
let left = Rabbit{
x: (cor_prev.x - 1),
y: cor_prev.y, | point: cor_prev.point,
};
let right = Rabbit{
x: (cor_prev.x + 1),
y: cor_prev.y,
point: cor_prev.point,
};
let up_left = Rabbit{
x: (cor_prev.x - 1),
y: (cor_prev.y - 1),
point: cor_prev.point,
};
let down_right = Rabbit{
x: (cor_prev.x + 1),
y: (cor_prev.y + 1),
point: cor_prev.point,
};
let false_random = rand::thread_rng().gen_range(0, 5);
let variants = [
(not_run, "not_run"),
(left, "left"),
(right, "right"),
(up_left, "up_left"),
(down_right, "down_right"),
];
let lets_go = variants[false_random].clone();
/*if (lets_go.0.x > 4) || (lets_go.0.y < -4){
return variants[0].clone();
}*/
return lets_go
} | random_line_split |
|
perf_context.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PerfLevel {
Uninitialized,
Disable,
EnableCount,
EnableTimeExceptForMutex,
EnableTimeAndCPUTimeExceptForMutex,
EnableTime,
OutOfBounds,
}
/// Extensions for measuring engine performance.
///
/// A PerfContext is created with a specific measurement level,
/// and a 'kind' which represents wich tikv subsystem measurements are being
/// collected for.
///
/// In rocks, `PerfContext` uses global state, and does not require
/// access through an engine. Thus perf data is not per-engine.
/// This doesn't seem like a reasonable assumption for engines generally,
/// so this abstraction follows the existing pattern in this crate and
/// requires `PerfContext` to be accessed through the engine.
pub trait PerfContextExt {
type PerfContext: PerfContext;
fn get_perf_context(&self, level: PerfLevel, kind: PerfContextKind) -> Self::PerfContext;
}
/// The raftstore subsystem the PerfContext is being created for.
///
/// This is a leaky abstraction that supports the encapsulation of metrics
/// reporting by the two raftstore subsystems that use `report_metrics`.
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum | {
RaftstoreApply,
RaftstoreStore,
}
/// Reports metrics to prometheus
///
/// For alternate engines, it is reasonable to make `start_observe`
/// and `report_metrics` no-ops.
pub trait PerfContext: Send {
/// Reinitializes statistics and the perf level
fn start_observe(&mut self);
/// Reports the current collected metrics to prometheus
fn report_metrics(&mut self);
}
| PerfContextKind | identifier_name |
perf_context.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PerfLevel {
Uninitialized,
Disable,
EnableCount,
EnableTimeExceptForMutex,
EnableTimeAndCPUTimeExceptForMutex,
EnableTime,
OutOfBounds,
}
/// Extensions for measuring engine performance.
///
/// A PerfContext is created with a specific measurement level,
/// and a 'kind' which represents wich tikv subsystem measurements are being
/// collected for.
///
/// In rocks, `PerfContext` uses global state, and does not require
/// access through an engine. Thus perf data is not per-engine.
/// This doesn't seem like a reasonable assumption for engines generally,
/// so this abstraction follows the existing pattern in this crate and
/// requires `PerfContext` to be accessed through the engine.
pub trait PerfContextExt {
type PerfContext: PerfContext;
| }
/// The raftstore subsystem the PerfContext is being created for.
///
/// This is a leaky abstraction that supports the encapsulation of metrics
/// reporting by the two raftstore subsystems that use `report_metrics`.
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum PerfContextKind {
RaftstoreApply,
RaftstoreStore,
}
/// Reports metrics to prometheus
///
/// For alternate engines, it is reasonable to make `start_observe`
/// and `report_metrics` no-ops.
pub trait PerfContext: Send {
/// Reinitializes statistics and the perf level
fn start_observe(&mut self);
/// Reports the current collected metrics to prometheus
fn report_metrics(&mut self);
} | fn get_perf_context(&self, level: PerfLevel, kind: PerfContextKind) -> Self::PerfContext; | random_line_split |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num=".to_string()+&self.num.to_string();
let str_index_x = "index_x=".to_string() + &self.index_x.to_string();
let str_index_y = "index_y=".to_string() + &self.index_y.to_string();
let str_w = "w=".to_string() + &self.width.to_string();
let str_h = "h=".to_string() + &self.height.to_string();
let parsed = str_num + " " + str_index_x.as_str() + " " + str_index_y.as_str() + " " + str_w.as_str() + " " + str_h.as_str();
fmt.write_str(parsed.as_str())?;
Ok(())
}
}
fn paint_matrix(matrix: &mut [[i32; 10]; 10]) {
for (i, row) in matrix.iter_mut().enumerate() {
for (y, col) in row.iter_mut().enumerate() {
if *col == 0 as i32 {
print!(".");
} else if *col == -1 as i32 {
print!("X");
} else {
print!("{}", col);
}
}
println!();
}
} | if current_value == DEFAULT {
matrix[x as usize][y as usize] = entry.num;
//matrix[x as usize][y as usize] = "1";
} else {
if current_value!= MULTIPLE {
matrix[x as usize][y as usize] = MULTIPLE;
}
}
}
}
}
fn code3() {
use regex::Regex;
let re = Regex::new(r"^#(\d) @ (\d),(\d): (\d)x(\d)").unwrap();
let mut vec: Vec<String> = Vec::new();
let stdin = io::stdin();
for line in stdin.lock().lines() {
let str_line = line.unwrap().trim().to_string();
if str_line == "0" {
println!("exit!");
break;
}
vec.push(str_line);
}
// check input
let mut entries: Vec<Entry> = Vec::new();
for line in vec {
println!("{:?}", re.is_match(line.as_str()));
for cap in re.captures_iter(line.as_str()) {
let num: i32 = cap[1].parse::<i32>().unwrap();
let index_x: i32 = cap[2].parse::<i32>().unwrap();
let index_y: i32 = cap[3].parse::<i32>().unwrap();
let width: i32 = cap[4].parse::<i32>().unwrap();
let height: i32 = cap[5].parse::<i32>().unwrap();
let entry = Entry{num, index_x, index_y, width, height};
entries.push(entry);
}
}
let mut matrix = [[DEFAULT; 10];10];
for mut ent in entries {
println!("{}",ent);
fill_matrix(&mut matrix, &mut ent);
}
paint_matrix(&mut matrix);
} |
fn fill_matrix(matrix: &mut [[i32; 10]; 10], entry: &mut Entry) {
for x in entry.index_x..entry.width{
for y in entry.index_y..entry.height {
let current_value = matrix[x as usize][y as usize]; | random_line_split |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct | {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num=".to_string()+&self.num.to_string();
let str_index_x = "index_x=".to_string() + &self.index_x.to_string();
let str_index_y = "index_y=".to_string() + &self.index_y.to_string();
let str_w = "w=".to_string() + &self.width.to_string();
let str_h = "h=".to_string() + &self.height.to_string();
let parsed = str_num + " " + str_index_x.as_str() + " " + str_index_y.as_str() + " " + str_w.as_str() + " " + str_h.as_str();
fmt.write_str(parsed.as_str())?;
Ok(())
}
}
fn paint_matrix(matrix: &mut [[i32; 10]; 10]) {
for (i, row) in matrix.iter_mut().enumerate() {
for (y, col) in row.iter_mut().enumerate() {
if *col == 0 as i32 {
print!(".");
} else if *col == -1 as i32 {
print!("X");
} else {
print!("{}", col);
}
}
println!();
}
}
fn fill_matrix(matrix: &mut [[i32; 10]; 10], entry: &mut Entry) {
for x in entry.index_x..entry.width{
for y in entry.index_y..entry.height {
let current_value = matrix[x as usize][y as usize];
if current_value == DEFAULT {
matrix[x as usize][y as usize] = entry.num;
//matrix[x as usize][y as usize] = "1";
} else {
if current_value!= MULTIPLE {
matrix[x as usize][y as usize] = MULTIPLE;
}
}
}
}
}
fn code3() {
use regex::Regex;
let re = Regex::new(r"^#(\d) @ (\d),(\d): (\d)x(\d)").unwrap();
let mut vec: Vec<String> = Vec::new();
let stdin = io::stdin();
for line in stdin.lock().lines() {
let str_line = line.unwrap().trim().to_string();
if str_line == "0" {
println!("exit!");
break;
}
vec.push(str_line);
}
// check input
let mut entries: Vec<Entry> = Vec::new();
for line in vec {
println!("{:?}", re.is_match(line.as_str()));
for cap in re.captures_iter(line.as_str()) {
let num: i32 = cap[1].parse::<i32>().unwrap();
let index_x: i32 = cap[2].parse::<i32>().unwrap();
let index_y: i32 = cap[3].parse::<i32>().unwrap();
let width: i32 = cap[4].parse::<i32>().unwrap();
let height: i32 = cap[5].parse::<i32>().unwrap();
let entry = Entry{num, index_x, index_y, width, height};
entries.push(entry);
}
}
let mut matrix = [[DEFAULT; 10];10];
for mut ent in entries {
println!("{}",ent);
fill_matrix(&mut matrix, &mut ent);
}
paint_matrix(&mut matrix);
}
| Entry | identifier_name |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num=".to_string()+&self.num.to_string();
let str_index_x = "index_x=".to_string() + &self.index_x.to_string();
let str_index_y = "index_y=".to_string() + &self.index_y.to_string();
let str_w = "w=".to_string() + &self.width.to_string();
let str_h = "h=".to_string() + &self.height.to_string();
let parsed = str_num + " " + str_index_x.as_str() + " " + str_index_y.as_str() + " " + str_w.as_str() + " " + str_h.as_str();
fmt.write_str(parsed.as_str())?;
Ok(())
}
}
fn paint_matrix(matrix: &mut [[i32; 10]; 10]) {
for (i, row) in matrix.iter_mut().enumerate() {
for (y, col) in row.iter_mut().enumerate() {
if *col == 0 as i32 | else if *col == -1 as i32 {
print!("X");
} else {
print!("{}", col);
}
}
println!();
}
}
fn fill_matrix(matrix: &mut [[i32; 10]; 10], entry: &mut Entry) {
for x in entry.index_x..entry.width{
for y in entry.index_y..entry.height {
let current_value = matrix[x as usize][y as usize];
if current_value == DEFAULT {
matrix[x as usize][y as usize] = entry.num;
//matrix[x as usize][y as usize] = "1";
} else {
if current_value!= MULTIPLE {
matrix[x as usize][y as usize] = MULTIPLE;
}
}
}
}
}
fn code3() {
use regex::Regex;
let re = Regex::new(r"^#(\d) @ (\d),(\d): (\d)x(\d)").unwrap();
let mut vec: Vec<String> = Vec::new();
let stdin = io::stdin();
for line in stdin.lock().lines() {
let str_line = line.unwrap().trim().to_string();
if str_line == "0" {
println!("exit!");
break;
}
vec.push(str_line);
}
// check input
let mut entries: Vec<Entry> = Vec::new();
for line in vec {
println!("{:?}", re.is_match(line.as_str()));
for cap in re.captures_iter(line.as_str()) {
let num: i32 = cap[1].parse::<i32>().unwrap();
let index_x: i32 = cap[2].parse::<i32>().unwrap();
let index_y: i32 = cap[3].parse::<i32>().unwrap();
let width: i32 = cap[4].parse::<i32>().unwrap();
let height: i32 = cap[5].parse::<i32>().unwrap();
let entry = Entry{num, index_x, index_y, width, height};
entries.push(entry);
}
}
let mut matrix = [[DEFAULT; 10];10];
for mut ent in entries {
println!("{}",ent);
fill_matrix(&mut matrix, &mut ent);
}
paint_matrix(&mut matrix);
}
| {
print!(".");
} | conditional_block |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result |
}
fn paint_matrix(matrix: &mut [[i32; 10]; 10]) {
for (i, row) in matrix.iter_mut().enumerate() {
for (y, col) in row.iter_mut().enumerate() {
if *col == 0 as i32 {
print!(".");
} else if *col == -1 as i32 {
print!("X");
} else {
print!("{}", col);
}
}
println!();
}
}
fn fill_matrix(matrix: &mut [[i32; 10]; 10], entry: &mut Entry) {
for x in entry.index_x..entry.width{
for y in entry.index_y..entry.height {
let current_value = matrix[x as usize][y as usize];
if current_value == DEFAULT {
matrix[x as usize][y as usize] = entry.num;
//matrix[x as usize][y as usize] = "1";
} else {
if current_value!= MULTIPLE {
matrix[x as usize][y as usize] = MULTIPLE;
}
}
}
}
}
fn code3() {
use regex::Regex;
let re = Regex::new(r"^#(\d) @ (\d),(\d): (\d)x(\d)").unwrap();
let mut vec: Vec<String> = Vec::new();
let stdin = io::stdin();
for line in stdin.lock().lines() {
let str_line = line.unwrap().trim().to_string();
if str_line == "0" {
println!("exit!");
break;
}
vec.push(str_line);
}
// check input
let mut entries: Vec<Entry> = Vec::new();
for line in vec {
println!("{:?}", re.is_match(line.as_str()));
for cap in re.captures_iter(line.as_str()) {
let num: i32 = cap[1].parse::<i32>().unwrap();
let index_x: i32 = cap[2].parse::<i32>().unwrap();
let index_y: i32 = cap[3].parse::<i32>().unwrap();
let width: i32 = cap[4].parse::<i32>().unwrap();
let height: i32 = cap[5].parse::<i32>().unwrap();
let entry = Entry{num, index_x, index_y, width, height};
entries.push(entry);
}
}
let mut matrix = [[DEFAULT; 10];10];
for mut ent in entries {
println!("{}",ent);
fill_matrix(&mut matrix, &mut ent);
}
paint_matrix(&mut matrix);
}
| {
let str_num = "num=".to_string()+&self.num.to_string();
let str_index_x = "index_x=".to_string() + &self.index_x.to_string();
let str_index_y = "index_y=".to_string() + &self.index_y.to_string();
let str_w = "w=".to_string() + &self.width.to_string();
let str_h = "h=".to_string() + &self.height.to_string();
let parsed = str_num + " " + str_index_x.as_str() + " " + str_index_y.as_str() + " " + str_w.as_str() + " " + str_h.as_str();
fmt.write_str(parsed.as_str())?;
Ok(())
} | identifier_body |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
const O_RDONLY = 0o00000000,
const O_WRONLY = 0o00000001,
const O_RDWR = 0o00000002,
const O_CREAT = 0o00000100,
const O_EXCL = 0o00000200,
const O_NONBLOCK = 0o00004000,
const O_CLOEXEC = 0o02000000,
}
);
bitflags!(
flags FdFlag: c_int {
const FD_CLOEXEC = 1
}
);
}
mod ffi {
use libc::{c_char, size_t, ssize_t, c_uint, c_int};
use super::MQd;
use super::MqAttr;
extern "C" {
pub fn mq_open(name: *const c_char, oflag: c_int,...) -> MQd;
pub fn mq_close (mqd: MQd) -> c_int;
pub fn mq_receive (mqd: MQd, msg_ptr: *const c_char, msg_len: size_t, msq_prio: *const c_uint) -> ssize_t;
pub fn mq_send (mqd: MQd, msg_ptr: *const c_char, msg_len: size_t, msq_prio: c_uint) -> c_int;
pub fn mq_getattr(mqd: MQd, attr: *mut MqAttr) -> c_int;
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MqAttr {
pub mq_flags: c_long,
pub mq_maxmsg: c_long,
pub mq_msgsize: c_long,
pub mq_curmsgs: c_long,
pad: [c_long; 4]
}
impl MqAttr {
pub fn new(mq_flags: c_long, mq_maxmsg: c_long, mq_msgsize: c_long, mq_curmsgs: c_long) -> MqAttr {
MqAttr { mq_flags: mq_flags, mq_maxmsg: mq_maxmsg, mq_msgsize: mq_msgsize, mq_curmsgs: mq_curmsgs, pad: [0; 4] }
}
}
#[inline]
pub fn mq_open(name: &CString, oflag: MQ_OFlag, mode: Mode, attr: &MqAttr) -> Result<MQd> {
let res = unsafe { ffi::mq_open(name.as_ptr(), oflag.bits(), mode.bits() as mode_t, attr as *const MqAttr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res)
}
pub fn mq_close(mqdes: MQd) -> Result<()> {
let res = unsafe { ffi::mq_close(mqdes) };
from_ffi(res)
}
pub fn mq_receive(mqdes: MQd, message: &mut [u8], msq_prio: u32) -> Result<usize> {
let len = message.len() as size_t;
let res = unsafe { ffi::mq_receive(mqdes, message.as_mut_ptr() as *mut c_char, len, &msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
}
pub fn mq_send(mqdes: MQd, message: &CString, msq_prio: u32) -> Result<usize> |
pub fn mq_getattr(mqd: MQd) -> Result<MqAttr> {
let mut attr = MqAttr::new(0, 0, 0, 0);
let res = unsafe { ffi::mq_getattr(mqd, &mut attr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(attr)
}
| {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
} | identifier_body |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
const O_RDONLY = 0o00000000,
const O_WRONLY = 0o00000001,
const O_RDWR = 0o00000002,
const O_CREAT = 0o00000100,
const O_EXCL = 0o00000200,
const O_NONBLOCK = 0o00004000,
const O_CLOEXEC = 0o02000000,
}
);
bitflags!(
flags FdFlag: c_int {
const FD_CLOEXEC = 1
}
);
}
mod ffi {
use libc::{c_char, size_t, ssize_t, c_uint, c_int};
use super::MQd;
use super::MqAttr;
extern "C" {
pub fn mq_open(name: *const c_char, oflag: c_int,...) -> MQd;
pub fn mq_close (mqd: MQd) -> c_int;
pub fn mq_receive (mqd: MQd, msg_ptr: *const c_char, msg_len: size_t, msq_prio: *const c_uint) -> ssize_t;
pub fn mq_send (mqd: MQd, msg_ptr: *const c_char, msg_len: size_t, msq_prio: c_uint) -> c_int;
pub fn mq_getattr(mqd: MQd, attr: *mut MqAttr) -> c_int;
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MqAttr {
pub mq_flags: c_long,
pub mq_maxmsg: c_long,
pub mq_msgsize: c_long,
pub mq_curmsgs: c_long,
pad: [c_long; 4]
}
impl MqAttr {
pub fn new(mq_flags: c_long, mq_maxmsg: c_long, mq_msgsize: c_long, mq_curmsgs: c_long) -> MqAttr {
MqAttr { mq_flags: mq_flags, mq_maxmsg: mq_maxmsg, mq_msgsize: mq_msgsize, mq_curmsgs: mq_curmsgs, pad: [0; 4] }
}
}
#[inline]
pub fn mq_open(name: &CString, oflag: MQ_OFlag, mode: Mode, attr: &MqAttr) -> Result<MQd> {
let res = unsafe { ffi::mq_open(name.as_ptr(), oflag.bits(), mode.bits() as mode_t, attr as *const MqAttr) };
if res < 0 { | }
Ok(res)
}
pub fn mq_close(mqdes: MQd) -> Result<()> {
let res = unsafe { ffi::mq_close(mqdes) };
from_ffi(res)
}
pub fn mq_receive(mqdes: MQd, message: &mut [u8], msq_prio: u32) -> Result<usize> {
let len = message.len() as size_t;
let res = unsafe { ffi::mq_receive(mqdes, message.as_mut_ptr() as *mut c_char, len, &msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
}
pub fn mq_send(mqdes: MQd, message: &CString, msq_prio: u32) -> Result<usize> {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
}
pub fn mq_getattr(mqd: MQd) -> Result<MqAttr> {
let mut attr = MqAttr::new(0, 0, 0, 0);
let res = unsafe { ffi::mq_getattr(mqd, &mut attr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(attr)
} | return Err(Error::Sys(Errno::last())); | random_line_split |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
const O_RDONLY = 0o00000000,
const O_WRONLY = 0o00000001,
const O_RDWR = 0o00000002,
const O_CREAT = 0o00000100,
const O_EXCL = 0o00000200,
const O_NONBLOCK = 0o00004000,
const O_CLOEXEC = 0o02000000,
}
);
bitflags!(
flags FdFlag: c_int {
const FD_CLOEXEC = 1
}
);
}
mod ffi {
use libc::{c_char, size_t, ssize_t, c_uint, c_int};
use super::MQd;
use super::MqAttr;
extern "C" {
pub fn mq_open(name: *const c_char, oflag: c_int,...) -> MQd;
pub fn mq_close (mqd: MQd) -> c_int;
pub fn mq_receive (mqd: MQd, msg_ptr: *const c_char, msg_len: size_t, msq_prio: *const c_uint) -> ssize_t;
pub fn mq_send (mqd: MQd, msg_ptr: *const c_char, msg_len: size_t, msq_prio: c_uint) -> c_int;
pub fn mq_getattr(mqd: MQd, attr: *mut MqAttr) -> c_int;
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MqAttr {
pub mq_flags: c_long,
pub mq_maxmsg: c_long,
pub mq_msgsize: c_long,
pub mq_curmsgs: c_long,
pad: [c_long; 4]
}
impl MqAttr {
pub fn new(mq_flags: c_long, mq_maxmsg: c_long, mq_msgsize: c_long, mq_curmsgs: c_long) -> MqAttr {
MqAttr { mq_flags: mq_flags, mq_maxmsg: mq_maxmsg, mq_msgsize: mq_msgsize, mq_curmsgs: mq_curmsgs, pad: [0; 4] }
}
}
#[inline]
pub fn mq_open(name: &CString, oflag: MQ_OFlag, mode: Mode, attr: &MqAttr) -> Result<MQd> {
let res = unsafe { ffi::mq_open(name.as_ptr(), oflag.bits(), mode.bits() as mode_t, attr as *const MqAttr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res)
}
pub fn mq_close(mqdes: MQd) -> Result<()> {
let res = unsafe { ffi::mq_close(mqdes) };
from_ffi(res)
}
pub fn mq_receive(mqdes: MQd, message: &mut [u8], msq_prio: u32) -> Result<usize> {
let len = message.len() as size_t;
let res = unsafe { ffi::mq_receive(mqdes, message.as_mut_ptr() as *mut c_char, len, &msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
}
pub fn | (mqdes: MQd, message: &CString, msq_prio: u32) -> Result<usize> {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
}
pub fn mq_getattr(mqd: MQd) -> Result<MqAttr> {
let mut attr = MqAttr::new(0, 0, 0, 0);
let res = unsafe { ffi::mq_getattr(mqd, &mut attr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(attr)
}
| mq_send | identifier_name |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
const O_RDONLY = 0o00000000,
const O_WRONLY = 0o00000001,
const O_RDWR = 0o00000002,
const O_CREAT = 0o00000100,
const O_EXCL = 0o00000200,
const O_NONBLOCK = 0o00004000,
const O_CLOEXEC = 0o02000000,
}
);
bitflags!(
flags FdFlag: c_int {
const FD_CLOEXEC = 1
}
);
}
mod ffi {
use libc::{c_char, size_t, ssize_t, c_uint, c_int};
use super::MQd;
use super::MqAttr;
extern "C" {
pub fn mq_open(name: *const c_char, oflag: c_int,...) -> MQd;
pub fn mq_close (mqd: MQd) -> c_int;
pub fn mq_receive (mqd: MQd, msg_ptr: *const c_char, msg_len: size_t, msq_prio: *const c_uint) -> ssize_t;
pub fn mq_send (mqd: MQd, msg_ptr: *const c_char, msg_len: size_t, msq_prio: c_uint) -> c_int;
pub fn mq_getattr(mqd: MQd, attr: *mut MqAttr) -> c_int;
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MqAttr {
pub mq_flags: c_long,
pub mq_maxmsg: c_long,
pub mq_msgsize: c_long,
pub mq_curmsgs: c_long,
pad: [c_long; 4]
}
impl MqAttr {
pub fn new(mq_flags: c_long, mq_maxmsg: c_long, mq_msgsize: c_long, mq_curmsgs: c_long) -> MqAttr {
MqAttr { mq_flags: mq_flags, mq_maxmsg: mq_maxmsg, mq_msgsize: mq_msgsize, mq_curmsgs: mq_curmsgs, pad: [0; 4] }
}
}
#[inline]
pub fn mq_open(name: &CString, oflag: MQ_OFlag, mode: Mode, attr: &MqAttr) -> Result<MQd> {
let res = unsafe { ffi::mq_open(name.as_ptr(), oflag.bits(), mode.bits() as mode_t, attr as *const MqAttr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res)
}
pub fn mq_close(mqdes: MQd) -> Result<()> {
let res = unsafe { ffi::mq_close(mqdes) };
from_ffi(res)
}
pub fn mq_receive(mqdes: MQd, message: &mut [u8], msq_prio: u32) -> Result<usize> {
let len = message.len() as size_t;
let res = unsafe { ffi::mq_receive(mqdes, message.as_mut_ptr() as *mut c_char, len, &msq_prio) };
if res < 0 |
Ok(res as usize)
}
pub fn mq_send(mqdes: MQd, message: &CString, msq_prio: u32) -> Result<usize> {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
}
pub fn mq_getattr(mqd: MQd) -> Result<MqAttr> {
let mut attr = MqAttr::new(0, 0, 0, 0);
let res = unsafe { ffi::mq_getattr(mqd, &mut attr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(attr)
}
| {
return Err(Error::Sys(Errno::last()));
} | conditional_block |
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. | // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Log entry type definition.
use std::ops::Deref;
use util::{H256, Address, Bytes, HeapSizeOf, Hashable};
use util::bloom::Bloomable;
use rlp::*;
use basic_types::LogBloom;
use header::BlockNumber;
use ethjson;
/// A record of execution for a `LOG` operation.
#[derive(Default, Debug, Clone, PartialEq, Eq, Binary)]
pub struct LogEntry {
/// The address of the contract executing at the point of the `LOG` operation.
pub address: Address,
/// The topics associated with the `LOG` operation.
pub topics: Vec<H256>,
/// The data associated with the `LOG` operation.
pub data: Bytes,
}
impl Encodable for LogEntry {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(3);
s.append(&self.address);
s.append(&self.topics);
s.append(&self.data);
}
}
impl Decodable for LogEntry {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp();
let entry = LogEntry {
address: try!(d.val_at(0)),
topics: try!(d.val_at(1)),
data: try!(d.val_at(2)),
};
Ok(entry)
}
}
impl HeapSizeOf for LogEntry {
fn heap_size_of_children(&self) -> usize {
self.topics.heap_size_of_children() + self.data.heap_size_of_children()
}
}
impl LogEntry {
/// Calculates the bloom of this log entry.
pub fn bloom(&self) -> LogBloom {
self.topics.iter().fold(LogBloom::from_bloomed(&self.address.sha3()), |b, t| b.with_bloomed(&t.sha3()))
}
}
impl From<ethjson::state::Log> for LogEntry {
fn from(l: ethjson::state::Log) -> Self {
LogEntry {
address: l.address.into(),
topics: l.topics.into_iter().map(Into::into).collect(),
data: l.data.into(),
}
}
}
/// Log localized in a blockchain.
#[derive(Default, Debug, PartialEq, Clone, Binary)]
pub struct LocalizedLogEntry {
/// Plain log entry.
pub entry: LogEntry,
/// Block in which this log was created.
pub block_hash: H256,
/// Block number.
pub block_number: BlockNumber,
/// Hash of transaction in which this log was created.
pub transaction_hash: H256,
/// Index of transaction within block.
pub transaction_index: usize,
/// Log position in the block.
pub log_index: usize,
}
impl Deref for LocalizedLogEntry {
type Target = LogEntry;
fn deref(&self) -> &Self::Target {
&self.entry
}
}
#[cfg(test)]
mod tests {
use util::*;
use super::LogEntry;
#[test]
fn test_empty_log_bloom() {
let bloom = H2048::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let log = LogEntry {
address: address,
topics: vec![],
data: vec![]
};
assert_eq!(log.bloom(), bloom);
}
} | random_line_split |
|
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Log entry type definition.
use std::ops::Deref;
use util::{H256, Address, Bytes, HeapSizeOf, Hashable};
use util::bloom::Bloomable;
use rlp::*;
use basic_types::LogBloom;
use header::BlockNumber;
use ethjson;
/// A record of execution for a `LOG` operation.
#[derive(Default, Debug, Clone, PartialEq, Eq, Binary)]
pub struct LogEntry {
/// The address of the contract executing at the point of the `LOG` operation.
pub address: Address,
/// The topics associated with the `LOG` operation.
pub topics: Vec<H256>,
/// The data associated with the `LOG` operation.
pub data: Bytes,
}
impl Encodable for LogEntry {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(3);
s.append(&self.address);
s.append(&self.topics);
s.append(&self.data);
}
}
impl Decodable for LogEntry {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp();
let entry = LogEntry {
address: try!(d.val_at(0)),
topics: try!(d.val_at(1)),
data: try!(d.val_at(2)),
};
Ok(entry)
}
}
impl HeapSizeOf for LogEntry {
fn heap_size_of_children(&self) -> usize {
self.topics.heap_size_of_children() + self.data.heap_size_of_children()
}
}
impl LogEntry {
/// Calculates the bloom of this log entry.
pub fn bloom(&self) -> LogBloom {
self.topics.iter().fold(LogBloom::from_bloomed(&self.address.sha3()), |b, t| b.with_bloomed(&t.sha3()))
}
}
impl From<ethjson::state::Log> for LogEntry {
fn from(l: ethjson::state::Log) -> Self {
LogEntry {
address: l.address.into(),
topics: l.topics.into_iter().map(Into::into).collect(),
data: l.data.into(),
}
}
}
/// Log localized in a blockchain.
#[derive(Default, Debug, PartialEq, Clone, Binary)]
pub struct LocalizedLogEntry {
/// Plain log entry.
pub entry: LogEntry,
/// Block in which this log was created.
pub block_hash: H256,
/// Block number.
pub block_number: BlockNumber,
/// Hash of transaction in which this log was created.
pub transaction_hash: H256,
/// Index of transaction within block.
pub transaction_index: usize,
/// Log position in the block.
pub log_index: usize,
}
impl Deref for LocalizedLogEntry {
type Target = LogEntry;
fn deref(&self) -> &Self::Target {
&self.entry
}
}
#[cfg(test)]
mod tests {
use util::*;
use super::LogEntry;
#[test]
fn | () {
let bloom = H2048::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let log = LogEntry {
address: address,
topics: vec![],
data: vec![]
};
assert_eq!(log.bloom(), bloom);
}
}
| test_empty_log_bloom | identifier_name |
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Log entry type definition.
use std::ops::Deref;
use util::{H256, Address, Bytes, HeapSizeOf, Hashable};
use util::bloom::Bloomable;
use rlp::*;
use basic_types::LogBloom;
use header::BlockNumber;
use ethjson;
/// A record of execution for a `LOG` operation.
#[derive(Default, Debug, Clone, PartialEq, Eq, Binary)]
pub struct LogEntry {
/// The address of the contract executing at the point of the `LOG` operation.
pub address: Address,
/// The topics associated with the `LOG` operation.
pub topics: Vec<H256>,
/// The data associated with the `LOG` operation.
pub data: Bytes,
}
impl Encodable for LogEntry {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(3);
s.append(&self.address);
s.append(&self.topics);
s.append(&self.data);
}
}
impl Decodable for LogEntry {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp();
let entry = LogEntry {
address: try!(d.val_at(0)),
topics: try!(d.val_at(1)),
data: try!(d.val_at(2)),
};
Ok(entry)
}
}
impl HeapSizeOf for LogEntry {
fn heap_size_of_children(&self) -> usize {
self.topics.heap_size_of_children() + self.data.heap_size_of_children()
}
}
impl LogEntry {
/// Calculates the bloom of this log entry.
pub fn bloom(&self) -> LogBloom {
self.topics.iter().fold(LogBloom::from_bloomed(&self.address.sha3()), |b, t| b.with_bloomed(&t.sha3()))
}
}
impl From<ethjson::state::Log> for LogEntry {
fn from(l: ethjson::state::Log) -> Self {
LogEntry {
address: l.address.into(),
topics: l.topics.into_iter().map(Into::into).collect(),
data: l.data.into(),
}
}
}
/// Log localized in a blockchain.
#[derive(Default, Debug, PartialEq, Clone, Binary)]
pub struct LocalizedLogEntry {
/// Plain log entry.
pub entry: LogEntry,
/// Block in which this log was created.
pub block_hash: H256,
/// Block number.
pub block_number: BlockNumber,
/// Hash of transaction in which this log was created.
pub transaction_hash: H256,
/// Index of transaction within block.
pub transaction_index: usize,
/// Log position in the block.
pub log_index: usize,
}
impl Deref for LocalizedLogEntry {
type Target = LogEntry;
fn deref(&self) -> &Self::Target {
&self.entry
}
}
#[cfg(test)]
mod tests {
use util::*;
use super::LogEntry;
#[test]
fn test_empty_log_bloom() |
}
| {
let bloom = H2048::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let log = LogEntry {
address: address,
topics: vec![],
data: vec![]
};
assert_eq!(log.bloom(), bloom);
} | identifier_body |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct Philosopher {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left_index: left_index,
right_index: right_index
}
}
fn eat(&self, table: &Table) |
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(())
]
});
let philosophers = vec![
Philosopher::new("Philosopher 1", 0, 1),
Philosopher::new("Philosopher 2", 1, 2),
Philosopher::new("Philosopher 3", 2, 3),
Philosopher::new("Philosopher 4", 3, 4),
Philosopher::new("Philosopher 5", 0, 4)
];
let thread_handles: Vec<_> = philosophers.into_iter().map(|p| {
let table = table.clone();
thread::spawn(move || {
p.eat(&table);
})
}).collect();
for handle in thread_handles {
handle.join().unwrap();
}
} | {
let _left = table.forks[self.left_index].lock().unwrap();
let _right = table.forks[self.right_index].lock().unwrap();
println!("{} started eating", self.name);
thread::sleep_ms(1000);
println!("{} is done eating.", self.name);
} | identifier_body |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct | {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left_index: left_index,
right_index: right_index
}
}
fn eat(&self, table: &Table) {
let _left = table.forks[self.left_index].lock().unwrap();
let _right = table.forks[self.right_index].lock().unwrap();
println!("{} started eating", self.name);
thread::sleep_ms(1000);
println!("{} is done eating.", self.name);
}
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(())
]
});
let philosophers = vec![
Philosopher::new("Philosopher 1", 0, 1),
Philosopher::new("Philosopher 2", 1, 2),
Philosopher::new("Philosopher 3", 2, 3),
Philosopher::new("Philosopher 4", 3, 4),
Philosopher::new("Philosopher 5", 0, 4)
];
let thread_handles: Vec<_> = philosophers.into_iter().map(|p| {
let table = table.clone();
thread::spawn(move || {
p.eat(&table);
})
}).collect();
for handle in thread_handles {
handle.join().unwrap();
}
} | Philosopher | identifier_name |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct Philosopher {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left_index: left_index,
right_index: right_index
}
}
fn eat(&self, table: &Table) {
let _left = table.forks[self.left_index].lock().unwrap();
let _right = table.forks[self.right_index].lock().unwrap();
println!("{} started eating", self.name);
thread::sleep_ms(1000);
println!("{} is done eating.", self.name);
} | fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(())
]
});
let philosophers = vec![
Philosopher::new("Philosopher 1", 0, 1),
Philosopher::new("Philosopher 2", 1, 2),
Philosopher::new("Philosopher 3", 2, 3),
Philosopher::new("Philosopher 4", 3, 4),
Philosopher::new("Philosopher 5", 0, 4)
];
let thread_handles: Vec<_> = philosophers.into_iter().map(|p| {
let table = table.clone();
thread::spawn(move || {
p.eat(&table);
})
}).collect();
for handle in thread_handles {
handle.join().unwrap();
}
} | }
| random_line_split |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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.
//! Promote a package to a specified channel.
//!
//! # Examples
//!
//! ```bash
//! $ hab pkg promote acme/redis/2.0.7/2112010203120101 stable
//! ```
//!//! This will promote the acme package specified to the stable channel.
//!
//! Notes:
//! The package should already have been uploaded to Builder.
//! If the specified channel does not exist, it will be created.
//!
use common::ui::{Status, UIWriter, UI};
use depot_client::{self, Client};
use hcore::package::PackageIdent;
use hyper::status::StatusCode;
use {PRODUCT, VERSION};
use error::{Error, Result};
/// Promote a package to the specified channel.
///
/// # Failures
///
/// * Fails if it cannot find the specified package in Builder
pub fn start(
ui: &mut UI,
url: &str,
ident: &PackageIdent,
channel: &str,
token: &str,
) -> Result<()> | return Err(Error::from(e));
}
}
ui.status(Status::Promoted, ident)?;
Ok(())
}
| {
let depot_client = Client::new(url, PRODUCT, VERSION, None)?;
ui.begin(format!("Promoting {} to channel '{}'", ident, channel))?;
if channel != "stable" && channel != "unstable" {
match depot_client.create_channel(&ident.origin, channel, token) {
Ok(_) => (),
Err(depot_client::Error::APIError(StatusCode::Conflict, _)) => (),
Err(e) => {
println!("Failed to create '{}' channel: {:?}", channel, e);
return Err(Error::from(e));
}
};
}
match depot_client.promote_package(ident, channel, token) {
Ok(_) => (),
Err(e) => {
println!("Failed to promote '{}': {:?}", ident, e); | identifier_body |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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.
//! Promote a package to a specified channel.
//!
//! # Examples
//!
//! ```bash
//! $ hab pkg promote acme/redis/2.0.7/2112010203120101 stable
//! ```
//!//! This will promote the acme package specified to the stable channel.
//!
//! Notes:
//! The package should already have been uploaded to Builder.
//! If the specified channel does not exist, it will be created.
//!
use common::ui::{Status, UIWriter, UI};
use depot_client::{self, Client};
use hcore::package::PackageIdent;
use hyper::status::StatusCode;
use {PRODUCT, VERSION};
use error::{Error, Result};
/// Promote a package to the specified channel.
///
/// # Failures
///
/// * Fails if it cannot find the specified package in Builder
pub fn | (
ui: &mut UI,
url: &str,
ident: &PackageIdent,
channel: &str,
token: &str,
) -> Result<()> {
let depot_client = Client::new(url, PRODUCT, VERSION, None)?;
ui.begin(format!("Promoting {} to channel '{}'", ident, channel))?;
if channel!= "stable" && channel!= "unstable" {
match depot_client.create_channel(&ident.origin, channel, token) {
Ok(_) => (),
Err(depot_client::Error::APIError(StatusCode::Conflict, _)) => (),
Err(e) => {
println!("Failed to create '{}' channel: {:?}", channel, e);
return Err(Error::from(e));
}
};
}
match depot_client.promote_package(ident, channel, token) {
Ok(_) => (),
Err(e) => {
println!("Failed to promote '{}': {:?}", ident, e);
return Err(Error::from(e));
}
}
ui.status(Status::Promoted, ident)?;
Ok(())
}
| start | identifier_name |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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.
//! Promote a package to a specified channel.
//!
//! # Examples | //! ```
//!//! This will promote the acme package specified to the stable channel.
//!
//! Notes:
//! The package should already have been uploaded to Builder.
//! If the specified channel does not exist, it will be created.
//!
use common::ui::{Status, UIWriter, UI};
use depot_client::{self, Client};
use hcore::package::PackageIdent;
use hyper::status::StatusCode;
use {PRODUCT, VERSION};
use error::{Error, Result};
/// Promote a package to the specified channel.
///
/// # Failures
///
/// * Fails if it cannot find the specified package in Builder
pub fn start(
ui: &mut UI,
url: &str,
ident: &PackageIdent,
channel: &str,
token: &str,
) -> Result<()> {
let depot_client = Client::new(url, PRODUCT, VERSION, None)?;
ui.begin(format!("Promoting {} to channel '{}'", ident, channel))?;
if channel!= "stable" && channel!= "unstable" {
match depot_client.create_channel(&ident.origin, channel, token) {
Ok(_) => (),
Err(depot_client::Error::APIError(StatusCode::Conflict, _)) => (),
Err(e) => {
println!("Failed to create '{}' channel: {:?}", channel, e);
return Err(Error::from(e));
}
};
}
match depot_client.promote_package(ident, channel, token) {
Ok(_) => (),
Err(e) => {
println!("Failed to promote '{}': {:?}", ident, e);
return Err(Error::from(e));
}
}
ui.status(Status::Promoted, ident)?;
Ok(())
} | //!
//! ```bash
//! $ hab pkg promote acme/redis/2.0.7/2112010203120101 stable | random_line_split |
explicit-self.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
static tau: f64 = 2.0*3.14159265358979323;
struct Point {x: f64, y: f64}
struct Size {w: f64, h: f64}
enum shape {
circle(Point, f64),
rectangle(Point, Size)
}
fn compute_area(shape: &shape) -> f64 {
match *shape {
circle(_, radius) => 0.5 * tau * radius * radius,
rectangle(_, ref size) => size.w * size.h
}
}
impl shape {
// self is in the implicit self region
pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T)
-> &'r T {
if compute_area(self) > threshold {a} else {b}
}
}
fn select_based_on_unit_circle<'r, T>(
threshold: f64, a: &'r T, b: &'r T) -> &'r T {
let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0);
shape.select(threshold, a, b)
}
#[deriving(Clone)]
struct thing {
x: A
}
#[deriving(Clone)]
struct A {
a: @int
}
fn thing(x: A) -> thing {
thing {
x: x
}
}
impl thing { | pub fn quux(&self) -> int { *self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
pub fn spam(self) -> int { *self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
let x = @thing(A {a: @10});
assert_eq!(x.foo(), 10);
assert_eq!(x.quux(), 10);
let y = ~thing(A {a: @10});
assert_eq!(y.clone().bar(), 10);
assert_eq!(y.quux(), 10);
let z = thing(A {a: @11});
assert_eq!(z.spam(), 11);
} | pub fn foo(@self) -> int { *self.x.a }
pub fn bar(~self) -> int { *self.x.a } | random_line_split |
explicit-self.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
static tau: f64 = 2.0*3.14159265358979323;
struct Point {x: f64, y: f64}
struct Size {w: f64, h: f64}
enum shape {
circle(Point, f64),
rectangle(Point, Size)
}
fn | (shape: &shape) -> f64 {
match *shape {
circle(_, radius) => 0.5 * tau * radius * radius,
rectangle(_, ref size) => size.w * size.h
}
}
impl shape {
// self is in the implicit self region
pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T)
-> &'r T {
if compute_area(self) > threshold {a} else {b}
}
}
fn select_based_on_unit_circle<'r, T>(
threshold: f64, a: &'r T, b: &'r T) -> &'r T {
let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0);
shape.select(threshold, a, b)
}
#[deriving(Clone)]
struct thing {
x: A
}
#[deriving(Clone)]
struct A {
a: @int
}
fn thing(x: A) -> thing {
thing {
x: x
}
}
impl thing {
pub fn foo(@self) -> int { *self.x.a }
pub fn bar(~self) -> int { *self.x.a }
pub fn quux(&self) -> int { *self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
pub fn spam(self) -> int { *self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
let x = @thing(A {a: @10});
assert_eq!(x.foo(), 10);
assert_eq!(x.quux(), 10);
let y = ~thing(A {a: @10});
assert_eq!(y.clone().bar(), 10);
assert_eq!(y.quux(), 10);
let z = thing(A {a: @11});
assert_eq!(z.spam(), 11);
}
| compute_area | identifier_name |
explicit-self.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
static tau: f64 = 2.0*3.14159265358979323;
struct Point {x: f64, y: f64}
struct Size {w: f64, h: f64}
enum shape {
circle(Point, f64),
rectangle(Point, Size)
}
fn compute_area(shape: &shape) -> f64 {
match *shape {
circle(_, radius) => 0.5 * tau * radius * radius,
rectangle(_, ref size) => size.w * size.h
}
}
impl shape {
// self is in the implicit self region
pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T)
-> &'r T {
if compute_area(self) > threshold {a} else {b}
}
}
fn select_based_on_unit_circle<'r, T>(
threshold: f64, a: &'r T, b: &'r T) -> &'r T {
let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0);
shape.select(threshold, a, b)
}
#[deriving(Clone)]
struct thing {
x: A
}
#[deriving(Clone)]
struct A {
a: @int
}
fn thing(x: A) -> thing {
thing {
x: x
}
}
impl thing {
pub fn foo(@self) -> int |
pub fn bar(~self) -> int { *self.x.a }
pub fn quux(&self) -> int { *self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
pub fn spam(self) -> int { *self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
let x = @thing(A {a: @10});
assert_eq!(x.foo(), 10);
assert_eq!(x.quux(), 10);
let y = ~thing(A {a: @10});
assert_eq!(y.clone().bar(), 10);
assert_eq!(y.quux(), 10);
let z = thing(A {a: @11});
assert_eq!(z.spam(), 11);
}
| { *self.x.a } | identifier_body |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespot::util::version::version_string;
use librespot::player::Player;
use librespot::spirc::SpircManager;
fn usage(program: &str, opts: &Options) -> String {
let brief = format!("Usage: {} [options]", program);
format!("{}", opts.usage(&brief))
}
fn | () {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY");
opts.reqopt("u", "username", "Username to sign in with", "USERNAME");
opts.optopt("p", "password", "Password (optional)", "PASSWORD");
opts.reqopt("c", "cache", "Path to a directory where files will be cached.", "CACHE");
opts.reqopt("n", "name", "Device name", "NAME");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m },
Err(f) => {
print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts));
return;
}
};
let mut appkey_file = File::open(
Path::new(&*matches.opt_str("a").unwrap())
).expect("Could not open app key.");
let username = matches.opt_str("u").unwrap();
let cache_location = matches.opt_str("c").unwrap();
let name = matches.opt_str("n").unwrap();
let password = matches.opt_str("p").unwrap_or_else(|| {
print!("Password: ");
stdout().flush().unwrap();
read_password().unwrap()
});
let mut appkey = Vec::new();
appkey_file.read_to_end(&mut appkey).unwrap();
let config = Config {
application_key: appkey,
user_agent: version_string(),
device_id: name.clone(),
cache_location: PathBuf::from(cache_location)
};
let session = Session::new(config);
session.login(username.clone(), password);
session.poll();
let _session = session.clone();
thread::spawn(move || {
loop {
_session.poll();
}
});
let player = Player::new(&session);
let mut spirc_manager = SpircManager::new(&session, player, name);
spirc_manager.run();
}
| main | identifier_name |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespot::util::version::version_string;
use librespot::player::Player;
use librespot::spirc::SpircManager;
fn usage(program: &str, opts: &Options) -> String {
let brief = format!("Usage: {} [options]", program);
format!("{}", opts.usage(&brief))
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY");
opts.reqopt("u", "username", "Username to sign in with", "USERNAME");
opts.optopt("p", "password", "Password (optional)", "PASSWORD");
opts.reqopt("c", "cache", "Path to a directory where files will be cached.", "CACHE");
opts.reqopt("n", "name", "Device name", "NAME");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m },
Err(f) => |
};
let mut appkey_file = File::open(
Path::new(&*matches.opt_str("a").unwrap())
).expect("Could not open app key.");
let username = matches.opt_str("u").unwrap();
let cache_location = matches.opt_str("c").unwrap();
let name = matches.opt_str("n").unwrap();
let password = matches.opt_str("p").unwrap_or_else(|| {
print!("Password: ");
stdout().flush().unwrap();
read_password().unwrap()
});
let mut appkey = Vec::new();
appkey_file.read_to_end(&mut appkey).unwrap();
let config = Config {
application_key: appkey,
user_agent: version_string(),
device_id: name.clone(),
cache_location: PathBuf::from(cache_location)
};
let session = Session::new(config);
session.login(username.clone(), password);
session.poll();
let _session = session.clone();
thread::spawn(move || {
loop {
_session.poll();
}
});
let player = Player::new(&session);
let mut spirc_manager = SpircManager::new(&session, player, name);
spirc_manager.run();
}
| {
print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts));
return;
} | conditional_block |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespot::util::version::version_string;
use librespot::player::Player;
use librespot::spirc::SpircManager;
fn usage(program: &str, opts: &Options) -> String {
let brief = format!("Usage: {} [options]", program);
format!("{}", opts.usage(&brief))
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY");
opts.reqopt("u", "username", "Username to sign in with", "USERNAME");
opts.optopt("p", "password", "Password (optional)", "PASSWORD");
opts.reqopt("c", "cache", "Path to a directory where files will be cached.", "CACHE");
opts.reqopt("n", "name", "Device name", "NAME");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m },
Err(f) => {
print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts));
return;
}
};
let mut appkey_file = File::open(
Path::new(&*matches.opt_str("a").unwrap())
).expect("Could not open app key.");
let username = matches.opt_str("u").unwrap();
let cache_location = matches.opt_str("c").unwrap();
let name = matches.opt_str("n").unwrap();
let password = matches.opt_str("p").unwrap_or_else(|| {
print!("Password: ");
stdout().flush().unwrap();
read_password().unwrap()
});
let mut appkey = Vec::new();
appkey_file.read_to_end(&mut appkey).unwrap();
let config = Config {
application_key: appkey,
user_agent: version_string(),
device_id: name.clone(),
cache_location: PathBuf::from(cache_location)
};
let session = Session::new(config);
session.login(username.clone(), password);
session.poll();
let _session = session.clone();
thread::spawn(move || {
loop {
_session.poll();
} |
let mut spirc_manager = SpircManager::new(&session, player, name);
spirc_manager.run();
} | });
let player = Player::new(&session); | random_line_split |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespot::util::version::version_string;
use librespot::player::Player;
use librespot::spirc::SpircManager;
fn usage(program: &str, opts: &Options) -> String |
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY");
opts.reqopt("u", "username", "Username to sign in with", "USERNAME");
opts.optopt("p", "password", "Password (optional)", "PASSWORD");
opts.reqopt("c", "cache", "Path to a directory where files will be cached.", "CACHE");
opts.reqopt("n", "name", "Device name", "NAME");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m },
Err(f) => {
print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts));
return;
}
};
let mut appkey_file = File::open(
Path::new(&*matches.opt_str("a").unwrap())
).expect("Could not open app key.");
let username = matches.opt_str("u").unwrap();
let cache_location = matches.opt_str("c").unwrap();
let name = matches.opt_str("n").unwrap();
let password = matches.opt_str("p").unwrap_or_else(|| {
print!("Password: ");
stdout().flush().unwrap();
read_password().unwrap()
});
let mut appkey = Vec::new();
appkey_file.read_to_end(&mut appkey).unwrap();
let config = Config {
application_key: appkey,
user_agent: version_string(),
device_id: name.clone(),
cache_location: PathBuf::from(cache_location)
};
let session = Session::new(config);
session.login(username.clone(), password);
session.poll();
let _session = session.clone();
thread::spawn(move || {
loop {
_session.poll();
}
});
let player = Player::new(&session);
let mut spirc_manager = SpircManager::new(&session, player, name);
spirc_manager.run();
}
| {
let brief = format!("Usage: {} [options]", program);
format!("{}", opts.usage(&brief))
} | identifier_body |
sys.rs | // Copyright 2020 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::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with
/// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical
/// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the
/// guest, so another mutable borrow would violate Rust assumptions about references.)
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct IoBufMut<'a> {
iov: iovec,
phantom: PhantomData<&'a mut [u8]>,
}
impl<'a> IoBufMut<'a> {
pub fn new(buf: &mut [u8]) -> IoBufMut<'a> {
// Safe because buf's memory is of the supplied length, and
// guaranteed to exist for the lifetime of the returned value.
unsafe { Self::from_raw_parts(buf.as_mut_ptr(), buf.len()) }
}
/// Creates a `IoBufMut` from a pointer and a length.
///
/// # Safety
///
/// In order to use this method safely, `addr` must be valid for reads and writes of `len` bytes
/// and should live for the entire duration of lifetime `'a`.
pub unsafe fn from_raw_parts(addr: *mut u8, len: usize) -> IoBufMut<'a> {
IoBufMut {
iov: iovec {
iov_base: addr as *mut c_void,
iov_len: len,
},
phantom: PhantomData,
}
}
/// Advance the internal position of the buffer.
///
/// Panics if `count > self.len()`.
pub fn advance(&mut self, count: usize) {
assert!(count <= self.len());
self.iov.iov_len -= count;
// Safe because we've checked that `count <= self.len()` so both the starting and resulting
// pointer are within the bounds of the allocation.
self.iov.iov_base = unsafe { self.iov.iov_base.add(count) };
}
/// Shorten the length of the buffer.
///
/// Has no effect if `len > self.len()`.
pub fn truncate(&mut self, len: usize) {
if len < self.len() {
self.iov.iov_len = len;
}
}
#[inline]
pub fn len(&self) -> usize {
self.iov.iov_len as usize
}
#[inline]
pub fn is_empty(&self) -> bool {
self.iov.iov_len == 0
}
/// Gets a const pointer to this slice's memory.
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.iov.iov_base as *const u8
}
/// Gets a mutable pointer to this slice's memory.
#[inline]
pub fn as_mut_ptr(&self) -> *mut u8 {
self.iov.iov_base as *mut u8
}
/// Converts a slice of `IoBufMut`s into a slice of `iovec`s.
#[allow(clippy::wrong_self_convention)]
#[inline]
pub fn as_iobufs<'slice>(iovs: &'slice [IoBufMut<'_>]) -> &'slice [iovec] |
}
impl<'a> AsRef<libc::iovec> for IoBufMut<'a> {
fn as_ref(&self) -> &libc::iovec {
&self.iov
}
}
impl<'a> AsMut<libc::iovec> for IoBufMut<'a> {
fn as_mut(&mut self) -> &mut libc::iovec {
&mut self.iov
}
}
// It's safe to implement Send + Sync for this type for the same reason that `std::io::IoBufMut`
// is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send
// + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the
// pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342.
unsafe impl<'a> Send for IoBufMut<'a> {}
unsafe impl<'a> Sync for IoBufMut<'a> {}
struct DebugIovec(iovec);
impl Debug for DebugIovec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("iovec")
.field("iov_base", &self.0.iov_base)
.field("iov_len", &self.0.iov_len)
.finish()
}
}
impl<'a> Debug for IoBufMut<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("IoBufMut")
.field("iov", &DebugIovec(self.iov))
.field("phantom", &self.phantom)
.finish()
}
}
| {
// Safe because `IoBufMut` is ABI-compatible with `iovec`.
unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) }
} | identifier_body |
sys.rs | // Copyright 2020 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::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with
/// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical
/// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the
/// guest, so another mutable borrow would violate Rust assumptions about references.)
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct IoBufMut<'a> {
iov: iovec,
phantom: PhantomData<&'a mut [u8]>,
}
impl<'a> IoBufMut<'a> {
pub fn new(buf: &mut [u8]) -> IoBufMut<'a> {
// Safe because buf's memory is of the supplied length, and
// guaranteed to exist for the lifetime of the returned value.
unsafe { Self::from_raw_parts(buf.as_mut_ptr(), buf.len()) }
}
/// Creates a `IoBufMut` from a pointer and a length.
///
/// # Safety
///
/// In order to use this method safely, `addr` must be valid for reads and writes of `len` bytes
/// and should live for the entire duration of lifetime `'a`.
pub unsafe fn from_raw_parts(addr: *mut u8, len: usize) -> IoBufMut<'a> {
IoBufMut {
iov: iovec {
iov_base: addr as *mut c_void,
iov_len: len,
},
phantom: PhantomData,
}
}
/// Advance the internal position of the buffer.
///
/// Panics if `count > self.len()`.
pub fn advance(&mut self, count: usize) {
assert!(count <= self.len());
self.iov.iov_len -= count;
// Safe because we've checked that `count <= self.len()` so both the starting and resulting
// pointer are within the bounds of the allocation.
self.iov.iov_base = unsafe { self.iov.iov_base.add(count) };
}
/// Shorten the length of the buffer.
///
/// Has no effect if `len > self.len()`.
pub fn truncate(&mut self, len: usize) {
if len < self.len() |
}
#[inline]
pub fn len(&self) -> usize {
self.iov.iov_len as usize
}
#[inline]
pub fn is_empty(&self) -> bool {
self.iov.iov_len == 0
}
/// Gets a const pointer to this slice's memory.
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.iov.iov_base as *const u8
}
/// Gets a mutable pointer to this slice's memory.
#[inline]
pub fn as_mut_ptr(&self) -> *mut u8 {
self.iov.iov_base as *mut u8
}
/// Converts a slice of `IoBufMut`s into a slice of `iovec`s.
#[allow(clippy::wrong_self_convention)]
#[inline]
pub fn as_iobufs<'slice>(iovs: &'slice [IoBufMut<'_>]) -> &'slice [iovec] {
// Safe because `IoBufMut` is ABI-compatible with `iovec`.
unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) }
}
}
impl<'a> AsRef<libc::iovec> for IoBufMut<'a> {
fn as_ref(&self) -> &libc::iovec {
&self.iov
}
}
impl<'a> AsMut<libc::iovec> for IoBufMut<'a> {
fn as_mut(&mut self) -> &mut libc::iovec {
&mut self.iov
}
}
// It's safe to implement Send + Sync for this type for the same reason that `std::io::IoBufMut`
// is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send
// + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the
// pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342.
unsafe impl<'a> Send for IoBufMut<'a> {}
unsafe impl<'a> Sync for IoBufMut<'a> {}
struct DebugIovec(iovec);
impl Debug for DebugIovec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("iovec")
.field("iov_base", &self.0.iov_base)
.field("iov_len", &self.0.iov_len)
.finish()
}
}
impl<'a> Debug for IoBufMut<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("IoBufMut")
.field("iov", &DebugIovec(self.iov))
.field("phantom", &self.phantom)
.finish()
}
}
| {
self.iov.iov_len = len;
} | conditional_block |
sys.rs | // Copyright 2020 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::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with
/// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical
/// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the
/// guest, so another mutable borrow would violate Rust assumptions about references.)
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct IoBufMut<'a> {
iov: iovec,
phantom: PhantomData<&'a mut [u8]>,
}
impl<'a> IoBufMut<'a> {
pub fn new(buf: &mut [u8]) -> IoBufMut<'a> {
// Safe because buf's memory is of the supplied length, and
// guaranteed to exist for the lifetime of the returned value.
unsafe { Self::from_raw_parts(buf.as_mut_ptr(), buf.len()) }
}
/// Creates a `IoBufMut` from a pointer and a length.
///
/// # Safety
///
/// In order to use this method safely, `addr` must be valid for reads and writes of `len` bytes
/// and should live for the entire duration of lifetime `'a`.
pub unsafe fn from_raw_parts(addr: *mut u8, len: usize) -> IoBufMut<'a> {
IoBufMut {
iov: iovec {
iov_base: addr as *mut c_void,
iov_len: len,
}, | }
/// Advance the internal position of the buffer.
///
/// Panics if `count > self.len()`.
pub fn advance(&mut self, count: usize) {
assert!(count <= self.len());
self.iov.iov_len -= count;
// Safe because we've checked that `count <= self.len()` so both the starting and resulting
// pointer are within the bounds of the allocation.
self.iov.iov_base = unsafe { self.iov.iov_base.add(count) };
}
/// Shorten the length of the buffer.
///
/// Has no effect if `len > self.len()`.
pub fn truncate(&mut self, len: usize) {
if len < self.len() {
self.iov.iov_len = len;
}
}
#[inline]
pub fn len(&self) -> usize {
self.iov.iov_len as usize
}
#[inline]
pub fn is_empty(&self) -> bool {
self.iov.iov_len == 0
}
/// Gets a const pointer to this slice's memory.
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.iov.iov_base as *const u8
}
/// Gets a mutable pointer to this slice's memory.
#[inline]
pub fn as_mut_ptr(&self) -> *mut u8 {
self.iov.iov_base as *mut u8
}
/// Converts a slice of `IoBufMut`s into a slice of `iovec`s.
#[allow(clippy::wrong_self_convention)]
#[inline]
pub fn as_iobufs<'slice>(iovs: &'slice [IoBufMut<'_>]) -> &'slice [iovec] {
// Safe because `IoBufMut` is ABI-compatible with `iovec`.
unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) }
}
}
impl<'a> AsRef<libc::iovec> for IoBufMut<'a> {
fn as_ref(&self) -> &libc::iovec {
&self.iov
}
}
impl<'a> AsMut<libc::iovec> for IoBufMut<'a> {
fn as_mut(&mut self) -> &mut libc::iovec {
&mut self.iov
}
}
// It's safe to implement Send + Sync for this type for the same reason that `std::io::IoBufMut`
// is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send
// + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the
// pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342.
unsafe impl<'a> Send for IoBufMut<'a> {}
unsafe impl<'a> Sync for IoBufMut<'a> {}
struct DebugIovec(iovec);
impl Debug for DebugIovec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("iovec")
.field("iov_base", &self.0.iov_base)
.field("iov_len", &self.0.iov_len)
.finish()
}
}
impl<'a> Debug for IoBufMut<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("IoBufMut")
.field("iov", &DebugIovec(self.iov))
.field("phantom", &self.phantom)
.finish()
}
} | phantom: PhantomData,
} | random_line_split |
sys.rs | // Copyright 2020 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::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with
/// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical
/// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the
/// guest, so another mutable borrow would violate Rust assumptions about references.)
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct | <'a> {
iov: iovec,
phantom: PhantomData<&'a mut [u8]>,
}
impl<'a> IoBufMut<'a> {
pub fn new(buf: &mut [u8]) -> IoBufMut<'a> {
// Safe because buf's memory is of the supplied length, and
// guaranteed to exist for the lifetime of the returned value.
unsafe { Self::from_raw_parts(buf.as_mut_ptr(), buf.len()) }
}
/// Creates a `IoBufMut` from a pointer and a length.
///
/// # Safety
///
/// In order to use this method safely, `addr` must be valid for reads and writes of `len` bytes
/// and should live for the entire duration of lifetime `'a`.
pub unsafe fn from_raw_parts(addr: *mut u8, len: usize) -> IoBufMut<'a> {
IoBufMut {
iov: iovec {
iov_base: addr as *mut c_void,
iov_len: len,
},
phantom: PhantomData,
}
}
/// Advance the internal position of the buffer.
///
/// Panics if `count > self.len()`.
pub fn advance(&mut self, count: usize) {
assert!(count <= self.len());
self.iov.iov_len -= count;
// Safe because we've checked that `count <= self.len()` so both the starting and resulting
// pointer are within the bounds of the allocation.
self.iov.iov_base = unsafe { self.iov.iov_base.add(count) };
}
/// Shorten the length of the buffer.
///
/// Has no effect if `len > self.len()`.
pub fn truncate(&mut self, len: usize) {
if len < self.len() {
self.iov.iov_len = len;
}
}
#[inline]
pub fn len(&self) -> usize {
self.iov.iov_len as usize
}
#[inline]
pub fn is_empty(&self) -> bool {
self.iov.iov_len == 0
}
/// Gets a const pointer to this slice's memory.
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.iov.iov_base as *const u8
}
/// Gets a mutable pointer to this slice's memory.
#[inline]
pub fn as_mut_ptr(&self) -> *mut u8 {
self.iov.iov_base as *mut u8
}
/// Converts a slice of `IoBufMut`s into a slice of `iovec`s.
#[allow(clippy::wrong_self_convention)]
#[inline]
pub fn as_iobufs<'slice>(iovs: &'slice [IoBufMut<'_>]) -> &'slice [iovec] {
// Safe because `IoBufMut` is ABI-compatible with `iovec`.
unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) }
}
}
impl<'a> AsRef<libc::iovec> for IoBufMut<'a> {
fn as_ref(&self) -> &libc::iovec {
&self.iov
}
}
impl<'a> AsMut<libc::iovec> for IoBufMut<'a> {
fn as_mut(&mut self) -> &mut libc::iovec {
&mut self.iov
}
}
// It's safe to implement Send + Sync for this type for the same reason that `std::io::IoBufMut`
// is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send
// + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the
// pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342.
unsafe impl<'a> Send for IoBufMut<'a> {}
unsafe impl<'a> Sync for IoBufMut<'a> {}
struct DebugIovec(iovec);
impl Debug for DebugIovec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("iovec")
.field("iov_base", &self.0.iov_base)
.field("iov_len", &self.0.iov_len)
.finish()
}
}
impl<'a> Debug for IoBufMut<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("IoBufMut")
.field("iov", &DebugIovec(self.iov))
.field("phantom", &self.phantom)
.finish()
}
}
| IoBufMut | identifier_name |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_placed(terrain : &mut Terrain, id: usize, position : Point) -> Person {
terrain.set_pt_val(&position, id as isize);
Person {id, position, has_escaped :false}
}
pub fn new_unplaced(id: usize) -> Person {
Person { id, position: Point { x: 0, y: 0 }, has_escaped : true }
}
pub fn new(id : usize, position : Point) -> Person {
Person { id, position, has_escaped : false }
}
// Select the best available move that reduces most the distance to the azimuth point
// or stay where you are.
pub fn choose_best_move (&self, possible_moves: &Vec<Point>) -> Point {
let azimuth: Point = Point{x: -2, y: 130};
#[derive(Debug)] // to allow println for debugging purposes.
let mut moves_and_dist: Vec<(&Point, f32)> = possible_moves.iter()
.map(|x| (x, x.square_distance_to( &azimuth)))
.collect();
moves_and_dist.sort_by(
|x, y| { x.1.partial_cmp((&y.1))
.unwrap_or(Equal)
}
);
debug!("debug sort :{:?}",moves_and_dist); // debug
match moves_and_dist.first() {
Some(&(ref point, _)) => Point{x:point.x, y:point.y},
None => Point{x: self.position.x, y: self.position.y}, // todo : stay where you are for now...
}
}
pub fn place_on_terrain(&mut self, terrain: &mut Terrain){
terrain.set_pt_val(&self.position, self.id as isize);
self.has_escaped = false;
}
pub fn remove_from_terrain(&mut self, terrain: &mut Terrain){
terrain.set_pt_val(&self.position, 0 as isize);
self.has_escaped = true;
}
pub fn move_to(&mut self, terrain: &mut Terrain, new_point: &Point) {
if self.has_escaped == true {
} else if terrain.get_exit_points().contains(new_point) | else {
terrain.move_src_to_dst(&self.position, new_point);
self.position.x = new_point.x; // change internal position (copy of x and y)
self.position.y = new_point.y;
}
}
/// This function encapulates a complete move for a person :
/// from looking around to actually moving to another place
/// (and mutating the Person and the Terrain).
pub fn look_and_move(&mut self, terrain : &mut Terrain) {
//println!("Dealing with : {}", self);
// look around
let moves = terrain.list_possible_moves(&self.position);
// select the best point (hope that no-one took it while thinking)
//println!("Possible moves : {:?}", moves);
#[derive(Debug)]
let good_point = self.choose_best_move(&moves);
// move to the best point
if good_point!= self.position {
trace!("Moving to : {}", good_point);
self.move_to(terrain, &good_point);
} else {
trace!("I, {} am staying here : {}", self.id, good_point);
}
}
}
impl cmp::PartialEq for Person {
fn eq(&self, other: &Person) -> bool {
(self.id == other.id)
}
fn ne(&self, other: &Person) -> bool {
!self.eq(other)
}
}
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position)
}
}
| {
terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts
trace!("I escaped : {}", self.id);
self.has_escaped = true;
self.remove_from_terrain(terrain);
} | conditional_block |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_placed(terrain : &mut Terrain, id: usize, position : Point) -> Person {
terrain.set_pt_val(&position, id as isize);
Person {id, position, has_escaped :false}
}
pub fn new_unplaced(id: usize) -> Person {
Person { id, position: Point { x: 0, y: 0 }, has_escaped : true }
}
pub fn new(id : usize, position : Point) -> Person {
Person { id, position, has_escaped : false }
}
// Select the best available move that reduces most the distance to the azimuth point
// or stay where you are.
pub fn choose_best_move (&self, possible_moves: &Vec<Point>) -> Point {
let azimuth: Point = Point{x: -2, y: 130};
#[derive(Debug)] // to allow println for debugging purposes.
let mut moves_and_dist: Vec<(&Point, f32)> = possible_moves.iter()
.map(|x| (x, x.square_distance_to( &azimuth)))
.collect();
moves_and_dist.sort_by(
|x, y| { x.1.partial_cmp((&y.1))
.unwrap_or(Equal)
}
);
debug!("debug sort :{:?}",moves_and_dist); // debug
match moves_and_dist.first() {
Some(&(ref point, _)) => Point{x:point.x, y:point.y},
None => Point{x: self.position.x, y: self.position.y}, // todo : stay where you are for now...
}
}
pub fn place_on_terrain(&mut self, terrain: &mut Terrain){
terrain.set_pt_val(&self.position, self.id as isize);
self.has_escaped = false;
}
pub fn remove_from_terrain(&mut self, terrain: &mut Terrain){
terrain.set_pt_val(&self.position, 0 as isize);
self.has_escaped = true;
}
pub fn move_to(&mut self, terrain: &mut Terrain, new_point: &Point) |
/// This function encapulates a complete move for a person :
/// from looking around to actually moving to another place
/// (and mutating the Person and the Terrain).
pub fn look_and_move(&mut self, terrain : &mut Terrain) {
//println!("Dealing with : {}", self);
// look around
let moves = terrain.list_possible_moves(&self.position);
// select the best point (hope that no-one took it while thinking)
//println!("Possible moves : {:?}", moves);
#[derive(Debug)]
let good_point = self.choose_best_move(&moves);
// move to the best point
if good_point!= self.position {
trace!("Moving to : {}", good_point);
self.move_to(terrain, &good_point);
} else {
trace!("I, {} am staying here : {}", self.id, good_point);
}
}
}
impl cmp::PartialEq for Person {
fn eq(&self, other: &Person) -> bool {
(self.id == other.id)
}
fn ne(&self, other: &Person) -> bool {
!self.eq(other)
}
}
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position)
}
}
| {
if self.has_escaped == true {
} else if terrain.get_exit_points().contains(new_point) {
terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts
trace!("I escaped : {}", self.id);
self.has_escaped = true;
self.remove_from_terrain(terrain);
} else {
terrain.move_src_to_dst(&self.position, new_point);
self.position.x = new_point.x; // change internal position (copy of x and y)
self.position.y = new_point.y;
}
} | identifier_body |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_placed(terrain : &mut Terrain, id: usize, position : Point) -> Person {
terrain.set_pt_val(&position, id as isize);
Person {id, position, has_escaped :false}
}
pub fn new_unplaced(id: usize) -> Person {
Person { id, position: Point { x: 0, y: 0 }, has_escaped : true }
}
pub fn new(id : usize, position : Point) -> Person {
Person { id, position, has_escaped : false }
}
// Select the best available move that reduces most the distance to the azimuth point
// or stay where you are.
pub fn choose_best_move (&self, possible_moves: &Vec<Point>) -> Point {
let azimuth: Point = Point{x: -2, y: 130};
#[derive(Debug)] // to allow println for debugging purposes.
let mut moves_and_dist: Vec<(&Point, f32)> = possible_moves.iter()
.map(|x| (x, x.square_distance_to( &azimuth)))
.collect();
moves_and_dist.sort_by(
|x, y| { x.1.partial_cmp((&y.1))
.unwrap_or(Equal)
}
);
debug!("debug sort :{:?}",moves_and_dist); // debug
match moves_and_dist.first() {
Some(&(ref point, _)) => Point{x:point.x, y:point.y},
None => Point{x: self.position.x, y: self.position.y}, // todo : stay where you are for now...
}
}
pub fn place_on_terrain(&mut self, terrain: &mut Terrain){
terrain.set_pt_val(&self.position, self.id as isize);
self.has_escaped = false;
}
pub fn remove_from_terrain(&mut self, terrain: &mut Terrain){
terrain.set_pt_val(&self.position, 0 as isize);
self.has_escaped = true;
}
pub fn move_to(&mut self, terrain: &mut Terrain, new_point: &Point) {
if self.has_escaped == true {
} else if terrain.get_exit_points().contains(new_point) {
terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts
trace!("I escaped : {}", self.id);
self.has_escaped = true;
self.remove_from_terrain(terrain);
} else {
terrain.move_src_to_dst(&self.position, new_point);
self.position.x = new_point.x; // change internal position (copy of x and y)
self.position.y = new_point.y;
}
}
/// This function encapulates a complete move for a person :
/// from looking around to actually moving to another place
/// (and mutating the Person and the Terrain).
pub fn look_and_move(&mut self, terrain : &mut Terrain) {
//println!("Dealing with : {}", self);
// look around
let moves = terrain.list_possible_moves(&self.position);
// select the best point (hope that no-one took it while thinking)
//println!("Possible moves : {:?}", moves);
#[derive(Debug)]
let good_point = self.choose_best_move(&moves);
// move to the best point
if good_point!= self.position {
trace!("Moving to : {}", good_point);
self.move_to(terrain, &good_point);
} else {
trace!("I, {} am staying here : {}", self.id, good_point);
}
}
}
impl cmp::PartialEq for Person {
fn eq(&self, other: &Person) -> bool {
(self.id == other.id)
}
fn ne(&self, other: &Person) -> bool {
!self.eq(other)
}
}
|
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position)
}
} | random_line_split |
|
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_placed(terrain : &mut Terrain, id: usize, position : Point) -> Person {
terrain.set_pt_val(&position, id as isize);
Person {id, position, has_escaped :false}
}
pub fn new_unplaced(id: usize) -> Person {
Person { id, position: Point { x: 0, y: 0 }, has_escaped : true }
}
pub fn new(id : usize, position : Point) -> Person {
Person { id, position, has_escaped : false }
}
// Select the best available move that reduces most the distance to the azimuth point
// or stay where you are.
pub fn choose_best_move (&self, possible_moves: &Vec<Point>) -> Point {
let azimuth: Point = Point{x: -2, y: 130};
#[derive(Debug)] // to allow println for debugging purposes.
let mut moves_and_dist: Vec<(&Point, f32)> = possible_moves.iter()
.map(|x| (x, x.square_distance_to( &azimuth)))
.collect();
moves_and_dist.sort_by(
|x, y| { x.1.partial_cmp((&y.1))
.unwrap_or(Equal)
}
);
debug!("debug sort :{:?}",moves_and_dist); // debug
match moves_and_dist.first() {
Some(&(ref point, _)) => Point{x:point.x, y:point.y},
None => Point{x: self.position.x, y: self.position.y}, // todo : stay where you are for now...
}
}
pub fn place_on_terrain(&mut self, terrain: &mut Terrain){
terrain.set_pt_val(&self.position, self.id as isize);
self.has_escaped = false;
}
pub fn remove_from_terrain(&mut self, terrain: &mut Terrain){
terrain.set_pt_val(&self.position, 0 as isize);
self.has_escaped = true;
}
pub fn move_to(&mut self, terrain: &mut Terrain, new_point: &Point) {
if self.has_escaped == true {
} else if terrain.get_exit_points().contains(new_point) {
terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts
trace!("I escaped : {}", self.id);
self.has_escaped = true;
self.remove_from_terrain(terrain);
} else {
terrain.move_src_to_dst(&self.position, new_point);
self.position.x = new_point.x; // change internal position (copy of x and y)
self.position.y = new_point.y;
}
}
/// This function encapulates a complete move for a person :
/// from looking around to actually moving to another place
/// (and mutating the Person and the Terrain).
pub fn look_and_move(&mut self, terrain : &mut Terrain) {
//println!("Dealing with : {}", self);
// look around
let moves = terrain.list_possible_moves(&self.position);
// select the best point (hope that no-one took it while thinking)
//println!("Possible moves : {:?}", moves);
#[derive(Debug)]
let good_point = self.choose_best_move(&moves);
// move to the best point
if good_point!= self.position {
trace!("Moving to : {}", good_point);
self.move_to(terrain, &good_point);
} else {
trace!("I, {} am staying here : {}", self.id, good_point);
}
}
}
impl cmp::PartialEq for Person {
fn eq(&self, other: &Person) -> bool {
(self.id == other.id)
}
fn ne(&self, other: &Person) -> bool {
!self.eq(other)
}
}
impl fmt::Display for Person {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position)
}
}
| fmt | identifier_name |
backtrace.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/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: https://github.com/servo/servo/issues/24881
//!
//! FIXME: if/when a future version of the `backtrace` crate has
//! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead.
use std::fmt::{self, Write};
use backtrace::{BytesOrWideString, PrintFmt};
#[inline(never)]
pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> {
write!(w, "{:?}", Print {
print_fn_address: print as usize,
})
}
struct Print {
print_fn_address: usize,
}
impl fmt::Debug for Print {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
// Safety: we’re in a signal handler that is about to call `libc::_exit`.
// Potential data races from using `*_unsynchronized` functions are perhaps
// less bad than potential deadlocks?
unsafe {
let mut print_fn_frame = 0;
let mut frame_count = 0;
backtrace::trace_unsynchronized(|frame| {
let found = frame.symbol_address() as usize == self.print_fn_address;
if found {
print_fn_frame = frame_count;
}
frame_count += 1;
!found
});
let mode = PrintFmt::Short;
let mut p = print_path;
let mut f = backtrace::BacktraceFmt::new(fmt, mode, &mut p);
f.add_context()?;
let mut result = Ok(());
let mut frame_count = 0;
backtrace::trace_unsynchronized(|frame| {
let skip = frame_count < print_fn_frame;
frame_count += 1;
if skip {
return true
}
let mut frame_fmt = f.frame();
let mut any_symbol = false;
backtrace::resolve_frame_unsynchronized(frame, |symbol| {
any_symbol = true;
if let Err(e) = frame_fmt.symbol(frame, symbol) {
result = Err(e)
}
});
if!any_symbol {
if let Err(e) = frame_fmt.print_raw(frame.ip(), None, None, None) {
result = Err(e)
}
}
result.is_ok()
});
result?;
f.finish()
}
}
}
| loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
}
Err(err) => {
fmt.write_char(std::char::REPLACEMENT_CHARACTER)?;
match err.error_len() {
Some(len) => bytes = &bytes[err.valid_up_to() + len..],
None => break,
}
}
}
}
}
BytesOrWideString::Wide(wide) => {
for c in std::char::decode_utf16(wide.iter().cloned()) {
fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))?
}
}
}
Ok(())
} | fn print_path(fmt: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
match path {
BytesOrWideString::Bytes(mut bytes) => { | random_line_split |
backtrace.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/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: https://github.com/servo/servo/issues/24881
//!
//! FIXME: if/when a future version of the `backtrace` crate has
//! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead.
use std::fmt::{self, Write};
use backtrace::{BytesOrWideString, PrintFmt};
#[inline(never)]
pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> {
write!(w, "{:?}", Print {
print_fn_address: print as usize,
})
}
struct Print {
print_fn_address: usize,
}
impl fmt::Debug for Print {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
// Safety: we’re in a signal handler that is about to call `libc::_exit`.
// Potential data races from using `*_unsynchronized` functions are perhaps
// less bad than potential deadlocks?
unsafe {
let mut print_fn_frame = 0;
let mut frame_count = 0;
backtrace::trace_unsynchronized(|frame| {
let found = frame.symbol_address() as usize == self.print_fn_address;
if found {
print_fn_frame = frame_count;
}
frame_count += 1;
!found
});
let mode = PrintFmt::Short;
let mut p = print_path;
let mut f = backtrace::BacktraceFmt::new(fmt, mode, &mut p);
f.add_context()?;
let mut result = Ok(());
let mut frame_count = 0;
backtrace::trace_unsynchronized(|frame| {
let skip = frame_count < print_fn_frame;
frame_count += 1;
if skip {
return true
}
let mut frame_fmt = f.frame();
let mut any_symbol = false;
backtrace::resolve_frame_unsynchronized(frame, |symbol| {
any_symbol = true;
if let Err(e) = frame_fmt.symbol(frame, symbol) {
result = Err(e)
}
});
if!any_symbol {
if let Err(e) = frame_fmt.print_raw(frame.ip(), None, None, None) {
result = Err(e)
}
}
result.is_ok()
});
result?;
f.finish()
}
}
}
fn print_path(fmt: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
| fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))?
}
}
}
Ok(())
}
| match path {
BytesOrWideString::Bytes(mut bytes) => {
loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
}
Err(err) => {
fmt.write_char(std::char::REPLACEMENT_CHARACTER)?;
match err.error_len() {
Some(len) => bytes = &bytes[err.valid_up_to() + len..],
None => break,
}
}
}
}
}
BytesOrWideString::Wide(wide) => {
for c in std::char::decode_utf16(wide.iter().cloned()) { | identifier_body |
backtrace.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/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: https://github.com/servo/servo/issues/24881
//!
//! FIXME: if/when a future version of the `backtrace` crate has
//! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead.
use std::fmt::{self, Write};
use backtrace::{BytesOrWideString, PrintFmt};
#[inline(never)]
pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> {
write!(w, "{:?}", Print {
print_fn_address: print as usize,
})
}
struct Print {
print_fn_address: usize,
}
impl fmt::Debug for Print {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
// Safety: we’re in a signal handler that is about to call `libc::_exit`.
// Potential data races from using `*_unsynchronized` functions are perhaps
// less bad than potential deadlocks?
unsafe {
let mut print_fn_frame = 0;
let mut frame_count = 0;
backtrace::trace_unsynchronized(|frame| {
let found = frame.symbol_address() as usize == self.print_fn_address;
if found {
print_fn_frame = frame_count;
}
frame_count += 1;
!found
});
let mode = PrintFmt::Short;
let mut p = print_path;
let mut f = backtrace::BacktraceFmt::new(fmt, mode, &mut p);
f.add_context()?;
let mut result = Ok(());
let mut frame_count = 0;
backtrace::trace_unsynchronized(|frame| {
let skip = frame_count < print_fn_frame;
frame_count += 1;
if skip {
return true
}
let mut frame_fmt = f.frame();
let mut any_symbol = false;
backtrace::resolve_frame_unsynchronized(frame, |symbol| {
any_symbol = true;
if let Err(e) = frame_fmt.symbol(frame, symbol) {
result = Err(e)
}
});
if!any_symbol {
if let Err(e) = frame_fmt.print_raw(frame.ip(), None, None, None) {
result = Err(e)
}
}
result.is_ok()
});
result?;
f.finish()
}
}
}
fn prin | : &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
match path {
BytesOrWideString::Bytes(mut bytes) => {
loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
}
Err(err) => {
fmt.write_char(std::char::REPLACEMENT_CHARACTER)?;
match err.error_len() {
Some(len) => bytes = &bytes[err.valid_up_to() + len..],
None => break,
}
}
}
}
}
BytesOrWideString::Wide(wide) => {
for c in std::char::decode_utf16(wide.iter().cloned()) {
fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))?
}
}
}
Ok(())
}
| t_path(fmt | identifier_name |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);
//well, this is awkward. The logic in this function relies on arithmetic overflows
u = simulate_32bit_precision(u + 0xe91aaa35);
u = simulate_32bit_precision(u ^ (u >> 16));
u = simulate_32bit_precision(u + (u << 8));
u = simulate_32bit_precision(u ^ (u >> 4));
let b = simulate_32bit_precision((u >> 8) & 0x1ff);
let a = simulate_32bit_precision((u + (u << 2)) >> 19);
simulate_32bit_precision(a ^ (lookups::HASH_ADJUST[b] as usize))
}
pub fn eval_5cards(cards: [&Card; 5]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16;
if (c1 & c2 & c3 & c4 & c5 & 0xf000)!= 0 {
return lookups::FLUSHES[q] as HandRank;
}
let s = lookups::UNIQUE_5[q] as HandRank;
if s!= 0 |
//TODO: FIXME
// version: perfect hash. Not working currently
let lookup = find_fast(
((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize
);
HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank)
}
// don't use this.
pub fn eval_7cards(cards: [&Card; 7]) -> HandRank {
let mut tmp;
let mut best = 0;
for ids in lookups::PERM_7.iter() {
let subhand : [&Card; 5] = [
cards[ids[0] as usize],
cards[ids[1] as usize],
cards[ids[2] as usize],
cards[ids[3] as usize],
cards[ids[4] as usize]
];
tmp = eval_5cards(subhand);
if tmp > best {
best = tmp;
}
}
best
}
// these two guys only work by accident
/*
#[test]
fn get_rank_of_5_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let cards = [&c1, &c2, &c3, &c4, &c5];
let rank = perfect::eval_5cards(cards);
assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind);
}
#[test]
fn get_rank_of_7_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let c6 = Card(Value::Three, Suit::Diamonds);
let c7 = Card(Value::Three, Suit::Clubs);
let cards = [&c1, &c2, &c3, &c4, &c5, &c6, &c7];
let rank = perfect::eval_7cards(cards);
assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind);
}
*/
| {
return s;
} | conditional_block |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);
//well, this is awkward. The logic in this function relies on arithmetic overflows
u = simulate_32bit_precision(u + 0xe91aaa35);
u = simulate_32bit_precision(u ^ (u >> 16));
u = simulate_32bit_precision(u + (u << 8));
u = simulate_32bit_precision(u ^ (u >> 4));
let b = simulate_32bit_precision((u >> 8) & 0x1ff);
let a = simulate_32bit_precision((u + (u << 2)) >> 19);
simulate_32bit_precision(a ^ (lookups::HASH_ADJUST[b] as usize))
}
pub fn | (cards: [&Card; 5]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16;
if (c1 & c2 & c3 & c4 & c5 & 0xf000)!= 0 {
return lookups::FLUSHES[q] as HandRank;
}
let s = lookups::UNIQUE_5[q] as HandRank;
if s!= 0 {
return s;
}
//TODO: FIXME
// version: perfect hash. Not working currently
let lookup = find_fast(
((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize
);
HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank)
}
// don't use this.
pub fn eval_7cards(cards: [&Card; 7]) -> HandRank {
let mut tmp;
let mut best = 0;
for ids in lookups::PERM_7.iter() {
let subhand : [&Card; 5] = [
cards[ids[0] as usize],
cards[ids[1] as usize],
cards[ids[2] as usize],
cards[ids[3] as usize],
cards[ids[4] as usize]
];
tmp = eval_5cards(subhand);
if tmp > best {
best = tmp;
}
}
best
}
// these two guys only work by accident
/*
#[test]
fn get_rank_of_5_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let cards = [&c1, &c2, &c3, &c4, &c5];
let rank = perfect::eval_5cards(cards);
assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind);
}
#[test]
fn get_rank_of_7_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let c6 = Card(Value::Three, Suit::Diamonds);
let c7 = Card(Value::Three, Suit::Clubs);
let cards = [&c1, &c2, &c3, &c4, &c5, &c6, &c7];
let rank = perfect::eval_7cards(cards);
assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind);
}
*/
| eval_5cards | identifier_name |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);
//well, this is awkward. The logic in this function relies on arithmetic overflows
u = simulate_32bit_precision(u + 0xe91aaa35);
u = simulate_32bit_precision(u ^ (u >> 16));
u = simulate_32bit_precision(u + (u << 8));
u = simulate_32bit_precision(u ^ (u >> 4));
let b = simulate_32bit_precision((u >> 8) & 0x1ff);
let a = simulate_32bit_precision((u + (u << 2)) >> 19);
simulate_32bit_precision(a ^ (lookups::HASH_ADJUST[b] as usize))
}
pub fn eval_5cards(cards: [&Card; 5]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16;
if (c1 & c2 & c3 & c4 & c5 & 0xf000)!= 0 {
return lookups::FLUSHES[q] as HandRank;
}
let s = lookups::UNIQUE_5[q] as HandRank;
if s!= 0 {
return s;
}
//TODO: FIXME
// version: perfect hash. Not working currently
let lookup = find_fast(
((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize
);
HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank)
}
// don't use this.
pub fn eval_7cards(cards: [&Card; 7]) -> HandRank |
// these two guys only work by accident
/*
#[test]
fn get_rank_of_5_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let cards = [&c1, &c2, &c3, &c4, &c5];
let rank = perfect::eval_5cards(cards);
assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind);
}
#[test]
fn get_rank_of_7_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let c6 = Card(Value::Three, Suit::Diamonds);
let c7 = Card(Value::Three, Suit::Clubs);
let cards = [&c1, &c2, &c3, &c4, &c5, &c6, &c7];
let rank = perfect::eval_7cards(cards);
assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind);
}
*/
| {
let mut tmp;
let mut best = 0;
for ids in lookups::PERM_7.iter() {
let subhand : [&Card; 5] = [
cards[ids[0] as usize],
cards[ids[1] as usize],
cards[ids[2] as usize],
cards[ids[3] as usize],
cards[ids[4] as usize]
];
tmp = eval_5cards(subhand);
if tmp > best {
best = tmp;
}
}
best
} | identifier_body |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);
//well, this is awkward. The logic in this function relies on arithmetic overflows
u = simulate_32bit_precision(u + 0xe91aaa35);
u = simulate_32bit_precision(u ^ (u >> 16));
u = simulate_32bit_precision(u + (u << 8));
u = simulate_32bit_precision(u ^ (u >> 4));
let b = simulate_32bit_precision((u >> 8) & 0x1ff);
let a = simulate_32bit_precision((u + (u << 2)) >> 19);
simulate_32bit_precision(a ^ (lookups::HASH_ADJUST[b] as usize))
}
pub fn eval_5cards(cards: [&Card; 5]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16;
if (c1 & c2 & c3 & c4 & c5 & 0xf000)!= 0 {
return lookups::FLUSHES[q] as HandRank;
}
let s = lookups::UNIQUE_5[q] as HandRank;
if s!= 0 {
return s;
}
//TODO: FIXME
// version: perfect hash. Not working currently
let lookup = find_fast(
((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize
);
HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank)
}
// don't use this.
pub fn eval_7cards(cards: [&Card; 7]) -> HandRank {
let mut tmp;
let mut best = 0;
for ids in lookups::PERM_7.iter() {
let subhand : [&Card; 5] = [
cards[ids[0] as usize],
cards[ids[1] as usize],
cards[ids[2] as usize],
cards[ids[3] as usize],
cards[ids[4] as usize]
];
tmp = eval_5cards(subhand);
if tmp > best {
best = tmp;
}
}
best
}
// these two guys only work by accident
/*
#[test]
fn get_rank_of_5_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let cards = [&c1, &c2, &c3, &c4, &c5];
let rank = perfect::eval_5cards(cards);
assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind);
}
| let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let c6 = Card(Value::Three, Suit::Diamonds);
let c7 = Card(Value::Three, Suit::Clubs);
let cards = [&c1, &c2, &c3, &c4, &c5, &c6, &c7];
let rank = perfect::eval_7cards(cards);
assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind);
}
*/ | #[test]
fn get_rank_of_7_perfect() { | random_line_split |
backtrace.rs | which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need to consult both the local and dynamic symbol tables.
/// With that in mind, here's our options of translating an address to
/// a symbol.
///
/// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
/// behind the scenes to translate, and this is why backtrace() was not used.
/// Conveniently, this method works fantastically on OSX. It appears dladdr()
/// uses magic to consult the local symbol table, or we're putting everything
/// in the dynamic symbol table anyway. Regardless, for OSX, this is the
/// method used for translation. It's provided by the system and easy to do.o
///
/// Sadly, all other systems have a dladdr() implementation that does not
/// consult the local symbol table. This means that most functions are blank
/// because they don't have symbols. This means that we need another solution.
///
/// * Use unw_get_proc_name(). This is part of the libunwind api (not the
/// libgcc_s version of the libunwind api), but involves taking a dependency
/// to libunwind. We may pursue this route in the future if we bundle
/// libunwind, but libunwind was unwieldy enough that it was not chosen at
/// this time to provide this functionality.
///
/// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a
/// semi-reasonable solution. The stdlib already knows how to spawn processes,
/// so in theory it could invoke readelf, parse the output, and consult the
/// local/dynamic symbol tables from there. This ended up not getting chosen
/// due to the craziness of the idea plus the advent of the next option.
///
/// * Use `libbacktrace`. It turns out that this is a small library bundled in
/// the gcc repository which provides backtrace and symbol translation
/// functionality. All we really need from it is the backtrace functionality,
/// and we only really need this on everything that's not OSX, so this is the
/// chosen route for now.
///
/// In summary, the current situation uses libgcc_s to get a trace of stack
/// pointers, and we use dladdr() or libbacktrace to translate these addresses
/// to symbols. This is a bit of a hokey implementation as-is, but it works for
/// all unix platforms we support right now, so it at least gets the job done.
#[cfg(stage0)]
use prelude::v1::*;
use io::prelude::*;
use ffi::CStr;
use io;
use libc;
use str;
use sync::StaticMutex;
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block above, backtrace doesn't
/// play well with green threads, so while it is extremely nice
/// and simple to use it should be used only on iOS devices as the
/// only viable option.
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(never)]
pub fn write(w: &mut Write) -> io::Result<()> {
extern {
fn backtrace(buf: *mut *mut libc::c_void,
sz: libc::c_int) -> libc::c_int;
}
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
// couple of threads panic simultaneously
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
const SIZE: usize = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as usize};
// skipping the first one as it is write itself
for i in 1..cnt {
try!(print(w, i as isize, buf[i], buf[i]))
}
Ok(())
}
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
#[inline(never)] // if we know this is a function call, we can skip it when
// tracing
pub fn write(w: &mut Write) -> io::Result<()> | &mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
let cx: &mut Context = unsafe { &mut *(arg as *mut Context) };
let mut ip_before_insn = 0;
let mut ip = unsafe {
uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void
};
if!ip.is_null() && ip_before_insn == 0 {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
}
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction
// pointer points *outside* of the calling function, and by
// unwinding it we go back to the original function.
let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
ip
} else {
unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
};
// Don't print out the first few frames (they're not user frames)
cx.idx += 1;
if cx.idx <= 0 { return uw::_URC_NO_REASON }
// Don't print ginormous backtraces
if cx.idx > 100 {
match write!(cx.writer, "... <frames omitted>\n") {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
return uw::_URC_FAILURE
}
// Once we hit an error, stop trying to print more frames
if cx.last_error.is_some() { return uw::_URC_FAILURE }
match print(cx.writer, cx.idx, ip, symaddr) {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
// keep going
return uw::_URC_NO_REASON
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
_symaddr: *mut libc::c_void) -> io::Result<()> {
use intrinsics;
#[repr(C)]
struct Dl_info {
dli_fname: *const libc::c_char,
dli_fbase: *mut libc::c_void,
dli_sname: *const libc::c_char,
dli_saddr: *mut libc::c_void,
}
extern {
fn dladdr(addr: *const libc::c_void,
info: *mut Dl_info) -> libc::c_int;
}
let mut info: Dl_info = unsafe { intrinsics::init() };
if unsafe { dladdr(addr, &mut info) == 0 } {
output(w, idx,addr, None)
} else {
output(w, idx, addr, Some(unsafe {
CStr::from_ptr(info.dli_sname).to_bytes()
}))
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> io::Result<()> {
use env;
use os::unix::prelude::*;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
////////////////////////////////////////////////////////////////////////
type backtrace_syminfo_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
symname: *const libc::c_char,
symval: libc::uintptr_t,
symsize: libc::uintptr_t);
type backtrace_full_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
function: *const libc::c_char) -> libc::c_int;
type backtrace_error_callback =
extern "C" fn(data: *mut libc::c_void,
msg: *const libc::c_char,
errnum: libc::c_int);
enum backtrace_state {}
#[link(name = "backtrace", kind = "static")]
#[cfg(not(test))]
extern {}
extern {
fn backtrace_create_state(filename: *const libc::c_char,
threaded: libc::c_int,
error: backtrace_error_callback,
data: *mut libc::c_void)
-> *mut backtrace_state;
fn backtrace_syminfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_syminfo_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
fn backtrace_pcinfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_full_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
}
////////////////////////////////////////////////////////////////////////
// helper callbacks
////////////////////////////////////////////////////////////////////////
type FileLine = (*const libc::c_char, libc::c_int);
extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
_errnum: libc::c_int) {
// do nothing for now
}
extern fn syminfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
symname: *const libc::c_char,
_symval: libc::uintptr_t,
_symsize: libc::uintptr_t) {
let slot = data as *mut *const libc::c_char;
unsafe { *slot = symname; }
}
extern fn pcinfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
_function: *const libc::c_char) -> libc::c_int {
if!filename.is_null() {
let slot = data as *mut &mut [FileLine];
let buffer = unsafe {ptr::read(slot)};
// if the buffer is not full, add file:line to the buffer
// and adjust the buffer for next possible calls to pcinfo_cb.
if!buffer.is_empty() {
buffer[0] = (filename, lineno);
unsafe { ptr::write(slot, &mut buffer[1..]); }
}
}
0
}
// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// An additionally oddity in this function is that we initialize the
// filename via self_exe_name() to pass to libbacktrace. It turns out
// that on Linux libbacktrace seamlessly gets the filename of the
// current executable, but this fails on freebsd. by always providing
// it, we make sure that libbacktrace never has a reason to not look up
// the symbols. The libbacktrace API also states that the filename must
// be in "permanent memory", so we copy it to a static and then use the
// static as the pointer.
//
// FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
// tested if this is required or not.
unsafe fn init_state() -> *mut backtrace_state {
static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256];
if!STATE.is_null() { return STATE }
let selfname = if cfg!(target_os = "freebsd") ||
cfg!(target_os = "dragonfly") ||
cfg!(target_os = "bitrig") ||
cfg!(target_os = "netbsd") ||
cfg!(target_os = "openbsd") {
env::current_exe().ok()
} else {
None
};
let filename = match selfname {
Some(path) => {
let bytes = path.as_os_str().as_bytes();
if bytes.len() < LAST_FILENAME.len() {
let i = bytes.iter();
for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
*slot = *val as libc::c_char;
}
LAST_FILENAME.as_ptr()
} else {
ptr::null()
}
}
None => ptr::null(),
};
STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut());
return STATE
}
////////////////////////////////////////////////////////////////////////
// translation
////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
let data_addr = &mut data as *mut *const libc::c_char;
let ret = unsafe {
backtrace_syminfo(state, symaddr as libc::uintptr_t,
syminfo_cb, error_cb,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
}
// pcinfo may return an arbitrary number of file:line pairs,
// in the order of stack trace (i.e. inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), -1); FILELINE_SIZE];
let ret;
let fileline_count;
{
let mut fileline_win: &mut [FileLine] = &mut fileline_buf;
let fileline_addr = &mut fileline_win as *mut &mut [FileLine];
ret = unsafe {
backtrace_pcinfo(state, addr as libc::uintptr_t,
pcinfo_cb, error_cb,
fileline_addr as *mut libc::c_void)
};
fileline_count = FILELINE_SIZE - fileline_win.len();
}
if ret == 0 {
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() { continue; } // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
}
}
Ok(())
}
// Finally, after all that work above, we can emit a symbol.
fn output(w: &mut Write, idx: isize, addr: *mut libc::c_void,
s: Option<&[u8]>) -> io::Result<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
}
w.write_all(&['\n' as u8])
}
#[allow(dead_code)]
fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
more: bool) -> io::Result<()> {
let file = str::from_utf8(file).unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
try!(write!(w, " <... and possibly more>"));
}
w.write_all(&['\n' as u8])
}
/// Unwind library interface used for backtraces
///
/// Note that dead code is allowed as here are just bindings
/// iOS doesn't use all of them it but adding more
/// platform-specific configs pollutes the code too much
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(dead_code)]
mod uw {
pub use self::_Unwind_Reason_Code::*;
use libc;
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9, // used only by ARM EABI
}
pub enum _Unwind_Context {}
pub type _Unwind_Trace_Fn =
extern fn(ctx: *mut _Unwind_Context,
arg: *mut libc::c_void) -> _Unwind_Reason_Code;
extern {
// No native _Unwind_Backtrace on iOS
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
trace_argument: *mut libc::c_void)
-> _Unwind_Reason_Code;
// available since GCC 4.2.0, should be fine for our purpose
#[cfg(all(not(all(target_os = "android", target_arch = "arm")),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
ip_before_insn: *mut libc::c_int)
-> libc::uintptr_t;
#[cfg(all(not(target_os = "android"),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
-> *mut libc::c_void;
}
// On android, the function _Unwind_GetIP is a macro, and this is the
// expansion of the macro. This is all copy/pasted directly from the
// header file with the definition of _Unwind_GetIP.
| {
struct Context<'a> {
idx: isize,
writer: &'a mut (Write+'a),
last_error: Option<io::Error>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of printing anyway, and we know that all
// I/O done here is blocking I/O, not green I/O, so we don't have to
// worry about this being a native vs green mutex.
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {
uw::_Unwind_Backtrace(trace_fn, | identifier_body |
backtrace.rs | which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need to consult both the local and dynamic symbol tables.
/// With that in mind, here's our options of translating an address to
/// a symbol.
///
/// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
/// behind the scenes to translate, and this is why backtrace() was not used.
/// Conveniently, this method works fantastically on OSX. It appears dladdr()
/// uses magic to consult the local symbol table, or we're putting everything
/// in the dynamic symbol table anyway. Regardless, for OSX, this is the
/// method used for translation. It's provided by the system and easy to do.o
///
/// Sadly, all other systems have a dladdr() implementation that does not
/// consult the local symbol table. This means that most functions are blank
/// because they don't have symbols. This means that we need another solution.
///
/// * Use unw_get_proc_name(). This is part of the libunwind api (not the
/// libgcc_s version of the libunwind api), but involves taking a dependency
/// to libunwind. We may pursue this route in the future if we bundle
/// libunwind, but libunwind was unwieldy enough that it was not chosen at
/// this time to provide this functionality.
///
/// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a
/// semi-reasonable solution. The stdlib already knows how to spawn processes,
/// so in theory it could invoke readelf, parse the output, and consult the
/// local/dynamic symbol tables from there. This ended up not getting chosen
/// due to the craziness of the idea plus the advent of the next option.
///
/// * Use `libbacktrace`. It turns out that this is a small library bundled in
/// the gcc repository which provides backtrace and symbol translation
/// functionality. All we really need from it is the backtrace functionality,
/// and we only really need this on everything that's not OSX, so this is the
/// chosen route for now.
///
/// In summary, the current situation uses libgcc_s to get a trace of stack
/// pointers, and we use dladdr() or libbacktrace to translate these addresses
/// to symbols. This is a bit of a hokey implementation as-is, but it works for
/// all unix platforms we support right now, so it at least gets the job done.
#[cfg(stage0)]
use prelude::v1::*;
use io::prelude::*;
use ffi::CStr;
use io;
use libc;
use str;
use sync::StaticMutex;
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block above, backtrace doesn't
/// play well with green threads, so while it is extremely nice
/// and simple to use it should be used only on iOS devices as the
/// only viable option.
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(never)]
pub fn write(w: &mut Write) -> io::Result<()> {
extern {
fn backtrace(buf: *mut *mut libc::c_void,
sz: libc::c_int) -> libc::c_int;
}
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
// couple of threads panic simultaneously
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
const SIZE: usize = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as usize};
// skipping the first one as it is write itself
for i in 1..cnt {
try!(print(w, i as isize, buf[i], buf[i]))
}
Ok(())
}
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
#[inline(never)] // if we know this is a function call, we can skip it when
// tracing
pub fn write(w: &mut Write) -> io::Result<()> {
struct Context<'a> {
idx: isize,
writer: &'a mut (Write+'a),
last_error: Option<io::Error>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of printing anyway, and we know that all
// I/O done here is blocking I/O, not green I/O, so we don't have to
// worry about this being a native vs green mutex.
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {
uw::_Unwind_Backtrace(trace_fn,
&mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
let cx: &mut Context = unsafe { &mut *(arg as *mut Context) };
let mut ip_before_insn = 0;
let mut ip = unsafe {
uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void
};
if!ip.is_null() && ip_before_insn == 0 {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
}
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction
// pointer points *outside* of the calling function, and by
// unwinding it we go back to the original function.
let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
ip
} else {
unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
};
// Don't print out the first few frames (they're not user frames)
cx.idx += 1;
if cx.idx <= 0 { return uw::_URC_NO_REASON }
// Don't print ginormous backtraces
if cx.idx > 100 {
match write!(cx.writer, "... <frames omitted>\n") {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
return uw::_URC_FAILURE
}
// Once we hit an error, stop trying to print more frames
if cx.last_error.is_some() { return uw::_URC_FAILURE }
match print(cx.writer, cx.idx, ip, symaddr) {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
// keep going
return uw::_URC_NO_REASON
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
_symaddr: *mut libc::c_void) -> io::Result<()> {
use intrinsics;
#[repr(C)]
struct Dl_info {
dli_fname: *const libc::c_char,
dli_fbase: *mut libc::c_void,
dli_sname: *const libc::c_char,
dli_saddr: *mut libc::c_void,
}
extern {
fn dladdr(addr: *const libc::c_void,
info: *mut Dl_info) -> libc::c_int;
}
let mut info: Dl_info = unsafe { intrinsics::init() };
if unsafe { dladdr(addr, &mut info) == 0 } {
output(w, idx,addr, None)
} else {
output(w, idx, addr, Some(unsafe {
CStr::from_ptr(info.dli_sname).to_bytes()
}))
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn | (w: &mut Write, idx: isize, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> io::Result<()> {
use env;
use os::unix::prelude::*;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
////////////////////////////////////////////////////////////////////////
type backtrace_syminfo_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
symname: *const libc::c_char,
symval: libc::uintptr_t,
symsize: libc::uintptr_t);
type backtrace_full_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
function: *const libc::c_char) -> libc::c_int;
type backtrace_error_callback =
extern "C" fn(data: *mut libc::c_void,
msg: *const libc::c_char,
errnum: libc::c_int);
enum backtrace_state {}
#[link(name = "backtrace", kind = "static")]
#[cfg(not(test))]
extern {}
extern {
fn backtrace_create_state(filename: *const libc::c_char,
threaded: libc::c_int,
error: backtrace_error_callback,
data: *mut libc::c_void)
-> *mut backtrace_state;
fn backtrace_syminfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_syminfo_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
fn backtrace_pcinfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_full_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
}
////////////////////////////////////////////////////////////////////////
// helper callbacks
////////////////////////////////////////////////////////////////////////
type FileLine = (*const libc::c_char, libc::c_int);
extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
_errnum: libc::c_int) {
// do nothing for now
}
extern fn syminfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
symname: *const libc::c_char,
_symval: libc::uintptr_t,
_symsize: libc::uintptr_t) {
let slot = data as *mut *const libc::c_char;
unsafe { *slot = symname; }
}
extern fn pcinfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
_function: *const libc::c_char) -> libc::c_int {
if!filename.is_null() {
let slot = data as *mut &mut [FileLine];
let buffer = unsafe {ptr::read(slot)};
// if the buffer is not full, add file:line to the buffer
// and adjust the buffer for next possible calls to pcinfo_cb.
if!buffer.is_empty() {
buffer[0] = (filename, lineno);
unsafe { ptr::write(slot, &mut buffer[1..]); }
}
}
0
}
// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// An additionally oddity in this function is that we initialize the
// filename via self_exe_name() to pass to libbacktrace. It turns out
// that on Linux libbacktrace seamlessly gets the filename of the
// current executable, but this fails on freebsd. by always providing
// it, we make sure that libbacktrace never has a reason to not look up
// the symbols. The libbacktrace API also states that the filename must
// be in "permanent memory", so we copy it to a static and then use the
// static as the pointer.
//
// FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
// tested if this is required or not.
unsafe fn init_state() -> *mut backtrace_state {
static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256];
if!STATE.is_null() { return STATE }
let selfname = if cfg!(target_os = "freebsd") ||
cfg!(target_os = "dragonfly") ||
cfg!(target_os = "bitrig") ||
cfg!(target_os = "netbsd") ||
cfg!(target_os = "openbsd") {
env::current_exe().ok()
} else {
None
};
let filename = match selfname {
Some(path) => {
let bytes = path.as_os_str().as_bytes();
if bytes.len() < LAST_FILENAME.len() {
let i = bytes.iter();
for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
*slot = *val as libc::c_char;
}
LAST_FILENAME.as_ptr()
} else {
ptr::null()
}
}
None => ptr::null(),
};
STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut());
return STATE
}
////////////////////////////////////////////////////////////////////////
// translation
////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
let data_addr = &mut data as *mut *const libc::c_char;
let ret = unsafe {
backtrace_syminfo(state, symaddr as libc::uintptr_t,
syminfo_cb, error_cb,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
}
// pcinfo may return an arbitrary number of file:line pairs,
// in the order of stack trace (i.e. inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), -1); FILELINE_SIZE];
let ret;
let fileline_count;
{
let mut fileline_win: &mut [FileLine] = &mut fileline_buf;
let fileline_addr = &mut fileline_win as *mut &mut [FileLine];
ret = unsafe {
backtrace_pcinfo(state, addr as libc::uintptr_t,
pcinfo_cb, error_cb,
fileline_addr as *mut libc::c_void)
};
fileline_count = FILELINE_SIZE - fileline_win.len();
}
if ret == 0 {
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() { continue; } // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
}
}
Ok(())
}
// Finally, after all that work above, we can emit a symbol.
fn output(w: &mut Write, idx: isize, addr: *mut libc::c_void,
s: Option<&[u8]>) -> io::Result<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
}
w.write_all(&['\n' as u8])
}
#[allow(dead_code)]
fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
more: bool) -> io::Result<()> {
let file = str::from_utf8(file).unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
try!(write!(w, " <... and possibly more>"));
}
w.write_all(&['\n' as u8])
}
/// Unwind library interface used for backtraces
///
/// Note that dead code is allowed as here are just bindings
/// iOS doesn't use all of them it but adding more
/// platform-specific configs pollutes the code too much
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(dead_code)]
mod uw {
pub use self::_Unwind_Reason_Code::*;
use libc;
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9, // used only by ARM EABI
}
pub enum _Unwind_Context {}
pub type _Unwind_Trace_Fn =
extern fn(ctx: *mut _Unwind_Context,
arg: *mut libc::c_void) -> _Unwind_Reason_Code;
extern {
// No native _Unwind_Backtrace on iOS
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
trace_argument: *mut libc::c_void)
-> _Unwind_Reason_Code;
// available since GCC 4.2.0, should be fine for our purpose
#[cfg(all(not(all(target_os = "android", target_arch = "arm")),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
ip_before_insn: *mut libc::c_int)
-> libc::uintptr_t;
#[cfg(all(not(target_os = "android"),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
-> *mut libc::c_void;
}
// On android, the function _Unwind_GetIP is a macro, and this is the
// expansion of the macro. This is all copy/pasted directly from the
// header file with the definition of _Unwind_GetIP.
| print | identifier_name |
backtrace.rs | executable which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need to consult both the local and dynamic symbol tables.
/// With that in mind, here's our options of translating an address to
/// a symbol.
///
/// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
/// behind the scenes to translate, and this is why backtrace() was not used.
/// Conveniently, this method works fantastically on OSX. It appears dladdr()
/// uses magic to consult the local symbol table, or we're putting everything
/// in the dynamic symbol table anyway. Regardless, for OSX, this is the
/// method used for translation. It's provided by the system and easy to do.o
///
/// Sadly, all other systems have a dladdr() implementation that does not
/// consult the local symbol table. This means that most functions are blank
/// because they don't have symbols. This means that we need another solution.
///
/// * Use unw_get_proc_name(). This is part of the libunwind api (not the
/// libgcc_s version of the libunwind api), but involves taking a dependency
/// to libunwind. We may pursue this route in the future if we bundle
/// libunwind, but libunwind was unwieldy enough that it was not chosen at
/// this time to provide this functionality.
///
/// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a
/// semi-reasonable solution. The stdlib already knows how to spawn processes,
/// so in theory it could invoke readelf, parse the output, and consult the
/// local/dynamic symbol tables from there. This ended up not getting chosen
/// due to the craziness of the idea plus the advent of the next option.
///
/// * Use `libbacktrace`. It turns out that this is a small library bundled in
/// the gcc repository which provides backtrace and symbol translation
/// functionality. All we really need from it is the backtrace functionality,
/// and we only really need this on everything that's not OSX, so this is the
/// chosen route for now.
///
/// In summary, the current situation uses libgcc_s to get a trace of stack
/// pointers, and we use dladdr() or libbacktrace to translate these addresses
/// to symbols. This is a bit of a hokey implementation as-is, but it works for
/// all unix platforms we support right now, so it at least gets the job done.
#[cfg(stage0)]
use prelude::v1::*;
use io::prelude::*;
use ffi::CStr;
use io;
use libc;
use str;
use sync::StaticMutex;
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block above, backtrace doesn't
/// play well with green threads, so while it is extremely nice
/// and simple to use it should be used only on iOS devices as the
/// only viable option.
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(never)]
pub fn write(w: &mut Write) -> io::Result<()> {
extern {
fn backtrace(buf: *mut *mut libc::c_void,
sz: libc::c_int) -> libc::c_int;
}
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
// couple of threads panic simultaneously
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
const SIZE: usize = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as usize};
// skipping the first one as it is write itself
for i in 1..cnt {
try!(print(w, i as isize, buf[i], buf[i]))
}
Ok(())
}
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
#[inline(never)] // if we know this is a function call, we can skip it when
// tracing
pub fn write(w: &mut Write) -> io::Result<()> {
struct Context<'a> {
idx: isize,
writer: &'a mut (Write+'a),
last_error: Option<io::Error>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of printing anyway, and we know that all
// I/O done here is blocking I/O, not green I/O, so we don't have to
// worry about this being a native vs green mutex.
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {
uw::_Unwind_Backtrace(trace_fn,
&mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
let cx: &mut Context = unsafe { &mut *(arg as *mut Context) };
let mut ip_before_insn = 0;
let mut ip = unsafe {
uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void
};
if!ip.is_null() && ip_before_insn == 0 {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
}
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction
// pointer points *outside* of the calling function, and by
// unwinding it we go back to the original function.
let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
ip
} else {
unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
};
// Don't print out the first few frames (they're not user frames)
cx.idx += 1;
if cx.idx <= 0 { return uw::_URC_NO_REASON }
// Don't print ginormous backtraces
if cx.idx > 100 {
match write!(cx.writer, "... <frames omitted>\n") {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
return uw::_URC_FAILURE
}
// Once we hit an error, stop trying to print more frames
if cx.last_error.is_some() { return uw::_URC_FAILURE }
match print(cx.writer, cx.idx, ip, symaddr) {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
// keep going
return uw::_URC_NO_REASON
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
_symaddr: *mut libc::c_void) -> io::Result<()> {
use intrinsics;
#[repr(C)]
struct Dl_info {
dli_fname: *const libc::c_char,
dli_fbase: *mut libc::c_void,
dli_sname: *const libc::c_char,
dli_saddr: *mut libc::c_void,
}
extern {
fn dladdr(addr: *const libc::c_void,
info: *mut Dl_info) -> libc::c_int;
}
let mut info: Dl_info = unsafe { intrinsics::init() };
if unsafe { dladdr(addr, &mut info) == 0 } {
output(w, idx,addr, None)
} else {
output(w, idx, addr, Some(unsafe {
CStr::from_ptr(info.dli_sname).to_bytes()
}))
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> io::Result<()> {
use env;
use os::unix::prelude::*;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
////////////////////////////////////////////////////////////////////////
type backtrace_syminfo_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
symname: *const libc::c_char,
symval: libc::uintptr_t,
symsize: libc::uintptr_t);
type backtrace_full_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
function: *const libc::c_char) -> libc::c_int;
type backtrace_error_callback =
extern "C" fn(data: *mut libc::c_void,
msg: *const libc::c_char,
errnum: libc::c_int);
enum backtrace_state {}
#[link(name = "backtrace", kind = "static")]
#[cfg(not(test))]
extern {}
extern {
fn backtrace_create_state(filename: *const libc::c_char,
threaded: libc::c_int,
error: backtrace_error_callback,
data: *mut libc::c_void)
-> *mut backtrace_state;
fn backtrace_syminfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_syminfo_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
fn backtrace_pcinfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_full_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
}
////////////////////////////////////////////////////////////////////////
// helper callbacks
////////////////////////////////////////////////////////////////////////
type FileLine = (*const libc::c_char, libc::c_int);
extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
_errnum: libc::c_int) {
// do nothing for now
}
extern fn syminfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
symname: *const libc::c_char,
_symval: libc::uintptr_t,
_symsize: libc::uintptr_t) {
let slot = data as *mut *const libc::c_char;
unsafe { *slot = symname; }
}
extern fn pcinfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
_function: *const libc::c_char) -> libc::c_int {
if!filename.is_null() {
let slot = data as *mut &mut [FileLine];
let buffer = unsafe {ptr::read(slot)};
// if the buffer is not full, add file:line to the buffer
// and adjust the buffer for next possible calls to pcinfo_cb.
if!buffer.is_empty() {
buffer[0] = (filename, lineno);
unsafe { ptr::write(slot, &mut buffer[1..]); }
}
}
0
}
// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// An additionally oddity in this function is that we initialize the
// filename via self_exe_name() to pass to libbacktrace. It turns out
// that on Linux libbacktrace seamlessly gets the filename of the
// current executable, but this fails on freebsd. by always providing
// it, we make sure that libbacktrace never has a reason to not look up
// the symbols. The libbacktrace API also states that the filename must
// be in "permanent memory", so we copy it to a static and then use the
// static as the pointer.
//
// FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
// tested if this is required or not.
unsafe fn init_state() -> *mut backtrace_state {
static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256];
if!STATE.is_null() { return STATE }
let selfname = if cfg!(target_os = "freebsd") ||
cfg!(target_os = "dragonfly") ||
cfg!(target_os = "bitrig") ||
cfg!(target_os = "netbsd") ||
cfg!(target_os = "openbsd") {
env::current_exe().ok()
} else {
None
};
let filename = match selfname {
Some(path) => {
let bytes = path.as_os_str().as_bytes();
if bytes.len() < LAST_FILENAME.len() {
let i = bytes.iter();
for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
*slot = *val as libc::c_char;
}
LAST_FILENAME.as_ptr()
} else {
ptr::null()
}
}
None => ptr::null(),
};
STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut());
return STATE
}
| ////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
let data_addr = &mut data as *mut *const libc::c_char;
let ret = unsafe {
backtrace_syminfo(state, symaddr as libc::uintptr_t,
syminfo_cb, error_cb,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
}
// pcinfo may return an arbitrary number of file:line pairs,
// in the order of stack trace (i.e. inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), -1); FILELINE_SIZE];
let ret;
let fileline_count;
{
let mut fileline_win: &mut [FileLine] = &mut fileline_buf;
let fileline_addr = &mut fileline_win as *mut &mut [FileLine];
ret = unsafe {
backtrace_pcinfo(state, addr as libc::uintptr_t,
pcinfo_cb, error_cb,
fileline_addr as *mut libc::c_void)
};
fileline_count = FILELINE_SIZE - fileline_win.len();
}
if ret == 0 {
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() { continue; } // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
}
}
Ok(())
}
// Finally, after all that work above, we can emit a symbol.
fn output(w: &mut Write, idx: isize, addr: *mut libc::c_void,
s: Option<&[u8]>) -> io::Result<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
}
w.write_all(&['\n' as u8])
}
#[allow(dead_code)]
fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
more: bool) -> io::Result<()> {
let file = str::from_utf8(file).unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
try!(write!(w, " <... and possibly more>"));
}
w.write_all(&['\n' as u8])
}
/// Unwind library interface used for backtraces
///
/// Note that dead code is allowed as here are just bindings
/// iOS doesn't use all of them it but adding more
/// platform-specific configs pollutes the code too much
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(dead_code)]
mod uw {
pub use self::_Unwind_Reason_Code::*;
use libc;
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9, // used only by ARM EABI
}
pub enum _Unwind_Context {}
pub type _Unwind_Trace_Fn =
extern fn(ctx: *mut _Unwind_Context,
arg: *mut libc::c_void) -> _Unwind_Reason_Code;
extern {
// No native _Unwind_Backtrace on iOS
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
trace_argument: *mut libc::c_void)
-> _Unwind_Reason_Code;
// available since GCC 4.2.0, should be fine for our purpose
#[cfg(all(not(all(target_os = "android", target_arch = "arm")),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
ip_before_insn: *mut libc::c_int)
-> libc::uintptr_t;
#[cfg(all(not(target_os = "android"),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
-> *mut libc::c_void;
}
// On android, the function _Unwind_GetIP is a macro, and this is the
// expansion of the macro. This is all copy/pasted directly from the
// header file with the definition of _Unwind_GetIP.
#[ | ////////////////////////////////////////////////////////////////////////
// translation | random_line_split |
backtrace.rs | which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need to consult both the local and dynamic symbol tables.
/// With that in mind, here's our options of translating an address to
/// a symbol.
///
/// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
/// behind the scenes to translate, and this is why backtrace() was not used.
/// Conveniently, this method works fantastically on OSX. It appears dladdr()
/// uses magic to consult the local symbol table, or we're putting everything
/// in the dynamic symbol table anyway. Regardless, for OSX, this is the
/// method used for translation. It's provided by the system and easy to do.o
///
/// Sadly, all other systems have a dladdr() implementation that does not
/// consult the local symbol table. This means that most functions are blank
/// because they don't have symbols. This means that we need another solution.
///
/// * Use unw_get_proc_name(). This is part of the libunwind api (not the
/// libgcc_s version of the libunwind api), but involves taking a dependency
/// to libunwind. We may pursue this route in the future if we bundle
/// libunwind, but libunwind was unwieldy enough that it was not chosen at
/// this time to provide this functionality.
///
/// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a
/// semi-reasonable solution. The stdlib already knows how to spawn processes,
/// so in theory it could invoke readelf, parse the output, and consult the
/// local/dynamic symbol tables from there. This ended up not getting chosen
/// due to the craziness of the idea plus the advent of the next option.
///
/// * Use `libbacktrace`. It turns out that this is a small library bundled in
/// the gcc repository which provides backtrace and symbol translation
/// functionality. All we really need from it is the backtrace functionality,
/// and we only really need this on everything that's not OSX, so this is the
/// chosen route for now.
///
/// In summary, the current situation uses libgcc_s to get a trace of stack
/// pointers, and we use dladdr() or libbacktrace to translate these addresses
/// to symbols. This is a bit of a hokey implementation as-is, but it works for
/// all unix platforms we support right now, so it at least gets the job done.
#[cfg(stage0)]
use prelude::v1::*;
use io::prelude::*;
use ffi::CStr;
use io;
use libc;
use str;
use sync::StaticMutex;
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block above, backtrace doesn't
/// play well with green threads, so while it is extremely nice
/// and simple to use it should be used only on iOS devices as the
/// only viable option.
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(never)]
pub fn write(w: &mut Write) -> io::Result<()> {
extern {
fn backtrace(buf: *mut *mut libc::c_void,
sz: libc::c_int) -> libc::c_int;
}
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
// couple of threads panic simultaneously
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
const SIZE: usize = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as usize};
// skipping the first one as it is write itself
for i in 1..cnt {
try!(print(w, i as isize, buf[i], buf[i]))
}
Ok(())
}
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
#[inline(never)] // if we know this is a function call, we can skip it when
// tracing
pub fn write(w: &mut Write) -> io::Result<()> {
struct Context<'a> {
idx: isize,
writer: &'a mut (Write+'a),
last_error: Option<io::Error>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of printing anyway, and we know that all
// I/O done here is blocking I/O, not green I/O, so we don't have to
// worry about this being a native vs green mutex.
static LOCK: StaticMutex = StaticMutex::new();
let _g = LOCK.lock();
try!(writeln!(w, "stack backtrace:"));
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {
uw::_Unwind_Backtrace(trace_fn,
&mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
let cx: &mut Context = unsafe { &mut *(arg as *mut Context) };
let mut ip_before_insn = 0;
let mut ip = unsafe {
uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void
};
if!ip.is_null() && ip_before_insn == 0 |
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction
// pointer points *outside* of the calling function, and by
// unwinding it we go back to the original function.
let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
ip
} else {
unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
};
// Don't print out the first few frames (they're not user frames)
cx.idx += 1;
if cx.idx <= 0 { return uw::_URC_NO_REASON }
// Don't print ginormous backtraces
if cx.idx > 100 {
match write!(cx.writer, "... <frames omitted>\n") {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
return uw::_URC_FAILURE
}
// Once we hit an error, stop trying to print more frames
if cx.last_error.is_some() { return uw::_URC_FAILURE }
match print(cx.writer, cx.idx, ip, symaddr) {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
// keep going
return uw::_URC_NO_REASON
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
_symaddr: *mut libc::c_void) -> io::Result<()> {
use intrinsics;
#[repr(C)]
struct Dl_info {
dli_fname: *const libc::c_char,
dli_fbase: *mut libc::c_void,
dli_sname: *const libc::c_char,
dli_saddr: *mut libc::c_void,
}
extern {
fn dladdr(addr: *const libc::c_void,
info: *mut Dl_info) -> libc::c_int;
}
let mut info: Dl_info = unsafe { intrinsics::init() };
if unsafe { dladdr(addr, &mut info) == 0 } {
output(w, idx,addr, None)
} else {
output(w, idx, addr, Some(unsafe {
CStr::from_ptr(info.dli_sname).to_bytes()
}))
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> io::Result<()> {
use env;
use os::unix::prelude::*;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
////////////////////////////////////////////////////////////////////////
type backtrace_syminfo_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
symname: *const libc::c_char,
symval: libc::uintptr_t,
symsize: libc::uintptr_t);
type backtrace_full_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
function: *const libc::c_char) -> libc::c_int;
type backtrace_error_callback =
extern "C" fn(data: *mut libc::c_void,
msg: *const libc::c_char,
errnum: libc::c_int);
enum backtrace_state {}
#[link(name = "backtrace", kind = "static")]
#[cfg(not(test))]
extern {}
extern {
fn backtrace_create_state(filename: *const libc::c_char,
threaded: libc::c_int,
error: backtrace_error_callback,
data: *mut libc::c_void)
-> *mut backtrace_state;
fn backtrace_syminfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_syminfo_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
fn backtrace_pcinfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_full_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
}
////////////////////////////////////////////////////////////////////////
// helper callbacks
////////////////////////////////////////////////////////////////////////
type FileLine = (*const libc::c_char, libc::c_int);
extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
_errnum: libc::c_int) {
// do nothing for now
}
extern fn syminfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
symname: *const libc::c_char,
_symval: libc::uintptr_t,
_symsize: libc::uintptr_t) {
let slot = data as *mut *const libc::c_char;
unsafe { *slot = symname; }
}
extern fn pcinfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
_function: *const libc::c_char) -> libc::c_int {
if!filename.is_null() {
let slot = data as *mut &mut [FileLine];
let buffer = unsafe {ptr::read(slot)};
// if the buffer is not full, add file:line to the buffer
// and adjust the buffer for next possible calls to pcinfo_cb.
if!buffer.is_empty() {
buffer[0] = (filename, lineno);
unsafe { ptr::write(slot, &mut buffer[1..]); }
}
}
0
}
// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// An additionally oddity in this function is that we initialize the
// filename via self_exe_name() to pass to libbacktrace. It turns out
// that on Linux libbacktrace seamlessly gets the filename of the
// current executable, but this fails on freebsd. by always providing
// it, we make sure that libbacktrace never has a reason to not look up
// the symbols. The libbacktrace API also states that the filename must
// be in "permanent memory", so we copy it to a static and then use the
// static as the pointer.
//
// FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
// tested if this is required or not.
unsafe fn init_state() -> *mut backtrace_state {
static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256];
if!STATE.is_null() { return STATE }
let selfname = if cfg!(target_os = "freebsd") ||
cfg!(target_os = "dragonfly") ||
cfg!(target_os = "bitrig") ||
cfg!(target_os = "netbsd") ||
cfg!(target_os = "openbsd") {
env::current_exe().ok()
} else {
None
};
let filename = match selfname {
Some(path) => {
let bytes = path.as_os_str().as_bytes();
if bytes.len() < LAST_FILENAME.len() {
let i = bytes.iter();
for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
*slot = *val as libc::c_char;
}
LAST_FILENAME.as_ptr()
} else {
ptr::null()
}
}
None => ptr::null(),
};
STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut());
return STATE
}
////////////////////////////////////////////////////////////////////////
// translation
////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
let data_addr = &mut data as *mut *const libc::c_char;
let ret = unsafe {
backtrace_syminfo(state, symaddr as libc::uintptr_t,
syminfo_cb, error_cb,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
}
// pcinfo may return an arbitrary number of file:line pairs,
// in the order of stack trace (i.e. inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), -1); FILELINE_SIZE];
let ret;
let fileline_count;
{
let mut fileline_win: &mut [FileLine] = &mut fileline_buf;
let fileline_addr = &mut fileline_win as *mut &mut [FileLine];
ret = unsafe {
backtrace_pcinfo(state, addr as libc::uintptr_t,
pcinfo_cb, error_cb,
fileline_addr as *mut libc::c_void)
};
fileline_count = FILELINE_SIZE - fileline_win.len();
}
if ret == 0 {
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() { continue; } // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
}
}
Ok(())
}
// Finally, after all that work above, we can emit a symbol.
fn output(w: &mut Write, idx: isize, addr: *mut libc::c_void,
s: Option<&[u8]>) -> io::Result<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
}
w.write_all(&['\n' as u8])
}
#[allow(dead_code)]
fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
more: bool) -> io::Result<()> {
let file = str::from_utf8(file).unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
try!(write!(w, " <... and possibly more>"));
}
w.write_all(&['\n' as u8])
}
/// Unwind library interface used for backtraces
///
/// Note that dead code is allowed as here are just bindings
/// iOS doesn't use all of them it but adding more
/// platform-specific configs pollutes the code too much
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(dead_code)]
mod uw {
pub use self::_Unwind_Reason_Code::*;
use libc;
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9, // used only by ARM EABI
}
pub enum _Unwind_Context {}
pub type _Unwind_Trace_Fn =
extern fn(ctx: *mut _Unwind_Context,
arg: *mut libc::c_void) -> _Unwind_Reason_Code;
extern {
// No native _Unwind_Backtrace on iOS
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
trace_argument: *mut libc::c_void)
-> _Unwind_Reason_Code;
// available since GCC 4.2.0, should be fine for our purpose
#[cfg(all(not(all(target_os = "android", target_arch = "arm")),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
ip_before_insn: *mut libc::c_int)
-> libc::uintptr_t;
#[cfg(all(not(target_os = "android"),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
-> *mut libc::c_void;
}
// On android, the function _Unwind_GetIP is a macro, and this is the
// expansion of the macro. This is all copy/pasted directly from the
// header file with the definition of _Unwind_GetIP.
| {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
} | conditional_block |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples must have length > 7 elements for the test to be valid.
///
/// # Panics
///
/// There are assertion panics if either sequence has <= 7 elements or
/// if the requested confidence level is not between 0 and 1.
///
/// # Examples
///
/// ```
/// extern crate kernel_density;
///
/// let xs = vec!(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0);
/// let ys = vec!(12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0);
/// let confidence = 0.95;
///
/// let result = kernel_density::kolmogorov_smirnov::test(&xs, &ys, confidence);
///
/// if result.is_rejected {
/// println!("{:?} and {:?} are not from the same distribution with probability {}.",
/// xs, ys, result.reject_probability);
/// }
/// ```
pub fn test(xs: &[f64], ys: &[f64], confidence: f64) -> TestResult {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(xs.len() > 7 && ys.len() > 7);
let statistic = calculate_statistic(xs, ys);
let critical_value = calculate_critical_value(xs.len(), ys.len(), confidence);
let reject_probability = calculate_reject_probability(statistic, xs.len(), ys.len());
let is_rejected = reject_probability > confidence;
TestResult {
is_rejected: is_rejected,
statistic: statistic,
reject_probability: reject_probability,
critical_value: critical_value,
confidence: confidence,
}
}
/// Calculate the test statistic for the two sample Kolmogorov-Smirnov test.
///
/// The test statistic is the maximum vertical distance between the ECDFs of
/// the two samples.
fn calculate_statistic(xs: &[f64], ys: &[f64]) -> f64 {
let n = xs.len();
let m = ys.len();
assert!(n > 0 && m > 0);
let mut xs = xs.to_vec();
let mut ys = ys.to_vec();
// xs and ys must be sorted for the stepwise ECDF calculations to work.
xs.sort_by(|x_1, x_2| x_1.partial_cmp(x_2).unwrap());
ys.sort_by(|y_1, y_2| y_1.partial_cmp(y_2).unwrap());
// The current value testing for ECDF difference. Sweeps up through elements
// present in xs and ys.
let mut current: f64;
// i, j index the first values in xs and ys that are greater than current.
let mut i = 0;
let mut j = 0;
// ecdf_xs, ecdf_ys always hold the ECDF(current) of xs and ys.
let mut ecdf_xs = 0.0;
let mut ecdf_ys = 0.0;
// The test statistic value computed over values <= current.
let mut statistic = 0.0;
while i < n && j < m {
// Advance i through duplicate samples in xs.
let x_i = xs[i];
while i + 1 < n && x_i == xs[i + 1] {
i += 1;
}
// Advance j through duplicate samples in ys.
let y_j = ys[j];
while j + 1 < m && y_j == ys[j + 1] {
j += 1;
}
// Step to the next sample value in the ECDF sweep from low to high.
current = x_i.min(y_j);
// Update invariant conditions for i, j, ecdf_xs, and ecdf_ys.
if current == x_i {
ecdf_xs = (i + 1) as f64 / n as f64;
i += 1;
}
if current == y_j {
ecdf_ys = (j + 1) as f64 / m as f64;
j += 1;
}
// Update invariant conditions for the test statistic.
let diff = (ecdf_xs - ecdf_ys).abs();
if diff > statistic {
statistic = diff;
}
}
// Don't need to walk the rest of the samples because one of the ecdfs is
// already one and the other will be increasing up to one. This means the
// difference will be monotonically decreasing, so we have our test
// statistic value already.
statistic
}
/// Calculate the probability that the null hypothesis is false for a two sample
/// Kolmogorov-Smirnov test. Can only reject the null hypothesis if this
/// evidence exceeds the confidence level required.
fn calculate_reject_probability(statistic: f64, n1: usize, n2: usize) -> f64 {
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
let n1 = n1 as f64;
let n2 = n2 as f64;
let factor = ((n1 * n2) / (n1 + n2)).sqrt();
let term = (factor + 0.12 + 0.11 / factor) * statistic;
let reject_probability = 1.0 - probability_kolmogorov_smirnov(term);
assert!(0.0 <= reject_probability && reject_probability <= 1.0);
reject_probability
}
/// Calculate the critical value for the two sample Kolmogorov-Smirnov test.
///
/// # Panics
///
/// There are assertion panics if either sequence size is <= 7 or if the
/// requested confidence level is not between 0 and 1.
///
/// No convergence panic if the binary search does not locate the critical
/// value in less than 200 iterations.
///
/// # Examples
///
/// ```
/// extern crate kernel_density;
///
/// let critical_value = kernel_density::kolmogorov_smirnov::calculate_critical_value(
/// 256, 256, 0.95);
/// println!("Critical value at 95% confidence for samples of size 256 is {}",
/// critical_value);
/// ```
pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
// The test statistic is between zero and one so can binary search quickly
// for the critical value.
let mut low = 0.0;
let mut high = 1.0;
for _ in 1..200 {
if low + 1e-8 >= high {
return high;
}
let mid = low + (high - low) / 2.0;
let reject_probability = calculate_reject_probability(mid, n1, n2);
if reject_probability > confidence | else {
// Maintain invariant that reject_probability(low) <= confidence.
low = mid;
}
}
panic!("No convergence in calculate_critical_value({}, {}, {}).",
n1,
n2,
confidence);
}
/// Calculate the Kolmogorov-Smirnov probability function.
fn probability_kolmogorov_smirnov(lambda: f64) -> f64 {
if lambda == 0.0 {
return 1.0;
}
let minus_two_lambda_squared = -2.0 * lambda * lambda;
let mut q_ks = 0.0;
for j in 1..200 {
let sign = if j % 2 == 1 {
1.0
} else {
-1.0
};
let j = j as f64;
let term = sign * 2.0 * (minus_two_lambda_squared * j * j).exp();
q_ks += term;
if term.abs() < 1e-8 {
// Trim results that exceed 1.
return q_ks.min(1.0);
}
}
panic!("No convergence in probability_kolmogorov_smirnov({}).",
lambda);
}
| {
// Maintain invariant that reject_probability(high) > confidence.
high = mid;
} | conditional_block |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples must have length > 7 elements for the test to be valid.
///
/// # Panics
///
/// There are assertion panics if either sequence has <= 7 elements or
/// if the requested confidence level is not between 0 and 1.
///
/// # Examples
///
/// ```
/// extern crate kernel_density;
///
/// let xs = vec!(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0);
/// let ys = vec!(12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0);
/// let confidence = 0.95;
///
/// let result = kernel_density::kolmogorov_smirnov::test(&xs, &ys, confidence);
///
/// if result.is_rejected {
/// println!("{:?} and {:?} are not from the same distribution with probability {}.",
/// xs, ys, result.reject_probability);
/// }
/// ```
pub fn test(xs: &[f64], ys: &[f64], confidence: f64) -> TestResult {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(xs.len() > 7 && ys.len() > 7);
let statistic = calculate_statistic(xs, ys);
let critical_value = calculate_critical_value(xs.len(), ys.len(), confidence);
let reject_probability = calculate_reject_probability(statistic, xs.len(), ys.len());
let is_rejected = reject_probability > confidence;
TestResult {
is_rejected: is_rejected,
statistic: statistic,
reject_probability: reject_probability,
critical_value: critical_value,
confidence: confidence,
}
}
/// Calculate the test statistic for the two sample Kolmogorov-Smirnov test.
///
/// The test statistic is the maximum vertical distance between the ECDFs of
/// the two samples.
fn calculate_statistic(xs: &[f64], ys: &[f64]) -> f64 {
let n = xs.len();
let m = ys.len();
assert!(n > 0 && m > 0);
let mut xs = xs.to_vec();
let mut ys = ys.to_vec();
// xs and ys must be sorted for the stepwise ECDF calculations to work.
xs.sort_by(|x_1, x_2| x_1.partial_cmp(x_2).unwrap());
ys.sort_by(|y_1, y_2| y_1.partial_cmp(y_2).unwrap());
// The current value testing for ECDF difference. Sweeps up through elements
// present in xs and ys.
let mut current: f64;
// i, j index the first values in xs and ys that are greater than current.
let mut i = 0;
let mut j = 0;
// ecdf_xs, ecdf_ys always hold the ECDF(current) of xs and ys.
let mut ecdf_xs = 0.0;
let mut ecdf_ys = 0.0;
// The test statistic value computed over values <= current.
let mut statistic = 0.0;
while i < n && j < m {
// Advance i through duplicate samples in xs.
let x_i = xs[i];
while i + 1 < n && x_i == xs[i + 1] {
i += 1;
}
// Advance j through duplicate samples in ys.
let y_j = ys[j];
while j + 1 < m && y_j == ys[j + 1] {
j += 1;
}
// Step to the next sample value in the ECDF sweep from low to high.
current = x_i.min(y_j);
// Update invariant conditions for i, j, ecdf_xs, and ecdf_ys.
if current == x_i {
ecdf_xs = (i + 1) as f64 / n as f64;
i += 1;
}
if current == y_j {
ecdf_ys = (j + 1) as f64 / m as f64;
j += 1;
}
// Update invariant conditions for the test statistic.
let diff = (ecdf_xs - ecdf_ys).abs();
if diff > statistic {
statistic = diff;
}
}
// Don't need to walk the rest of the samples because one of the ecdfs is
// already one and the other will be increasing up to one. This means the
// difference will be monotonically decreasing, so we have our test
// statistic value already.
statistic
}
/// Calculate the probability that the null hypothesis is false for a two sample
/// Kolmogorov-Smirnov test. Can only reject the null hypothesis if this
/// evidence exceeds the confidence level required.
fn calculate_reject_probability(statistic: f64, n1: usize, n2: usize) -> f64 {
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
let n1 = n1 as f64;
let n2 = n2 as f64;
let factor = ((n1 * n2) / (n1 + n2)).sqrt();
let term = (factor + 0.12 + 0.11 / factor) * statistic;
let reject_probability = 1.0 - probability_kolmogorov_smirnov(term);
assert!(0.0 <= reject_probability && reject_probability <= 1.0);
reject_probability
}
/// Calculate the critical value for the two sample Kolmogorov-Smirnov test.
///
/// # Panics
///
/// There are assertion panics if either sequence size is <= 7 or if the
/// requested confidence level is not between 0 and 1.
///
/// No convergence panic if the binary search does not locate the critical
/// value in less than 200 iterations.
///
/// # Examples
///
/// ```
/// extern crate kernel_density;
///
/// let critical_value = kernel_density::kolmogorov_smirnov::calculate_critical_value(
/// 256, 256, 0.95);
/// println!("Critical value at 95% confidence for samples of size 256 is {}",
/// critical_value);
/// ```
pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 | // Maintain invariant that reject_probability(high) > confidence.
high = mid;
} else {
// Maintain invariant that reject_probability(low) <= confidence.
low = mid;
}
}
panic!("No convergence in calculate_critical_value({}, {}, {}).",
n1,
n2,
confidence);
}
/// Calculate the Kolmogorov-Smirnov probability function.
fn probability_kolmogorov_smirnov(lambda: f64) -> f64 {
if lambda == 0.0 {
return 1.0;
}
let minus_two_lambda_squared = -2.0 * lambda * lambda;
let mut q_ks = 0.0;
for j in 1..200 {
let sign = if j % 2 == 1 {
1.0
} else {
-1.0
};
let j = j as f64;
let term = sign * 2.0 * (minus_two_lambda_squared * j * j).exp();
q_ks += term;
if term.abs() < 1e-8 {
// Trim results that exceed 1.
return q_ks.min(1.0);
}
}
panic!("No convergence in probability_kolmogorov_smirnov({}).",
lambda);
}
| {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
// The test statistic is between zero and one so can binary search quickly
// for the critical value.
let mut low = 0.0;
let mut high = 1.0;
for _ in 1..200 {
if low + 1e-8 >= high {
return high;
}
let mid = low + (high - low) / 2.0;
let reject_probability = calculate_reject_probability(mid, n1, n2);
if reject_probability > confidence { | identifier_body |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples must have length > 7 elements for the test to be valid.
///
/// # Panics
///
/// There are assertion panics if either sequence has <= 7 elements or
/// if the requested confidence level is not between 0 and 1.
///
/// # Examples
///
/// ```
/// extern crate kernel_density;
///
/// let xs = vec!(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0);
/// let ys = vec!(12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0);
/// let confidence = 0.95;
///
/// let result = kernel_density::kolmogorov_smirnov::test(&xs, &ys, confidence);
///
/// if result.is_rejected {
/// println!("{:?} and {:?} are not from the same distribution with probability {}.",
/// xs, ys, result.reject_probability);
/// }
/// ```
pub fn test(xs: &[f64], ys: &[f64], confidence: f64) -> TestResult {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(xs.len() > 7 && ys.len() > 7);
let statistic = calculate_statistic(xs, ys);
let critical_value = calculate_critical_value(xs.len(), ys.len(), confidence);
let reject_probability = calculate_reject_probability(statistic, xs.len(), ys.len());
let is_rejected = reject_probability > confidence;
TestResult {
is_rejected: is_rejected,
statistic: statistic,
reject_probability: reject_probability,
critical_value: critical_value,
confidence: confidence,
}
}
/// Calculate the test statistic for the two sample Kolmogorov-Smirnov test.
///
/// The test statistic is the maximum vertical distance between the ECDFs of
/// the two samples.
fn calculate_statistic(xs: &[f64], ys: &[f64]) -> f64 {
let n = xs.len();
let m = ys.len();
assert!(n > 0 && m > 0);
let mut xs = xs.to_vec();
let mut ys = ys.to_vec();
// xs and ys must be sorted for the stepwise ECDF calculations to work.
xs.sort_by(|x_1, x_2| x_1.partial_cmp(x_2).unwrap());
ys.sort_by(|y_1, y_2| y_1.partial_cmp(y_2).unwrap());
// The current value testing for ECDF difference. Sweeps up through elements
// present in xs and ys.
let mut current: f64;
// i, j index the first values in xs and ys that are greater than current.
let mut i = 0;
let mut j = 0;
// ecdf_xs, ecdf_ys always hold the ECDF(current) of xs and ys.
let mut ecdf_xs = 0.0;
let mut ecdf_ys = 0.0;
// The test statistic value computed over values <= current.
let mut statistic = 0.0;
while i < n && j < m {
// Advance i through duplicate samples in xs.
let x_i = xs[i];
while i + 1 < n && x_i == xs[i + 1] {
i += 1;
}
// Advance j through duplicate samples in ys.
let y_j = ys[j];
while j + 1 < m && y_j == ys[j + 1] {
j += 1;
}
// Step to the next sample value in the ECDF sweep from low to high.
current = x_i.min(y_j);
// Update invariant conditions for i, j, ecdf_xs, and ecdf_ys.
if current == x_i {
ecdf_xs = (i + 1) as f64 / n as f64;
i += 1;
}
if current == y_j {
ecdf_ys = (j + 1) as f64 / m as f64;
j += 1;
}
// Update invariant conditions for the test statistic.
let diff = (ecdf_xs - ecdf_ys).abs();
if diff > statistic {
statistic = diff;
}
}
// Don't need to walk the rest of the samples because one of the ecdfs is
// already one and the other will be increasing up to one. This means the
// difference will be monotonically decreasing, so we have our test
// statistic value already.
statistic
}
/// Calculate the probability that the null hypothesis is false for a two sample
/// Kolmogorov-Smirnov test. Can only reject the null hypothesis if this
/// evidence exceeds the confidence level required.
fn | (statistic: f64, n1: usize, n2: usize) -> f64 {
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
let n1 = n1 as f64;
let n2 = n2 as f64;
let factor = ((n1 * n2) / (n1 + n2)).sqrt();
let term = (factor + 0.12 + 0.11 / factor) * statistic;
let reject_probability = 1.0 - probability_kolmogorov_smirnov(term);
assert!(0.0 <= reject_probability && reject_probability <= 1.0);
reject_probability
}
/// Calculate the critical value for the two sample Kolmogorov-Smirnov test.
///
/// # Panics
///
/// There are assertion panics if either sequence size is <= 7 or if the
/// requested confidence level is not between 0 and 1.
///
/// No convergence panic if the binary search does not locate the critical
/// value in less than 200 iterations.
///
/// # Examples
///
/// ```
/// extern crate kernel_density;
///
/// let critical_value = kernel_density::kolmogorov_smirnov::calculate_critical_value(
/// 256, 256, 0.95);
/// println!("Critical value at 95% confidence for samples of size 256 is {}",
/// critical_value);
/// ```
pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
// The test statistic is between zero and one so can binary search quickly
// for the critical value.
let mut low = 0.0;
let mut high = 1.0;
for _ in 1..200 {
if low + 1e-8 >= high {
return high;
}
let mid = low + (high - low) / 2.0;
let reject_probability = calculate_reject_probability(mid, n1, n2);
if reject_probability > confidence {
// Maintain invariant that reject_probability(high) > confidence.
high = mid;
} else {
// Maintain invariant that reject_probability(low) <= confidence.
low = mid;
}
}
panic!("No convergence in calculate_critical_value({}, {}, {}).",
n1,
n2,
confidence);
}
/// Calculate the Kolmogorov-Smirnov probability function.
fn probability_kolmogorov_smirnov(lambda: f64) -> f64 {
if lambda == 0.0 {
return 1.0;
}
let minus_two_lambda_squared = -2.0 * lambda * lambda;
let mut q_ks = 0.0;
for j in 1..200 {
let sign = if j % 2 == 1 {
1.0
} else {
-1.0
};
let j = j as f64;
let term = sign * 2.0 * (minus_two_lambda_squared * j * j).exp();
q_ks += term;
if term.abs() < 1e-8 {
// Trim results that exceed 1.
return q_ks.min(1.0);
}
}
panic!("No convergence in probability_kolmogorov_smirnov({}).",
lambda);
}
| calculate_reject_probability | identifier_name |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples must have length > 7 elements for the test to be valid.
///
/// # Panics
///
/// There are assertion panics if either sequence has <= 7 elements or
/// if the requested confidence level is not between 0 and 1.
///
/// # Examples
///
/// ```
/// extern crate kernel_density;
///
/// let xs = vec!(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0);
/// let ys = vec!(12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0);
/// let confidence = 0.95;
///
/// let result = kernel_density::kolmogorov_smirnov::test(&xs, &ys, confidence);
///
/// if result.is_rejected {
/// println!("{:?} and {:?} are not from the same distribution with probability {}.",
/// xs, ys, result.reject_probability);
/// }
/// ```
pub fn test(xs: &[f64], ys: &[f64], confidence: f64) -> TestResult {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(xs.len() > 7 && ys.len() > 7);
let statistic = calculate_statistic(xs, ys);
let critical_value = calculate_critical_value(xs.len(), ys.len(), confidence);
let reject_probability = calculate_reject_probability(statistic, xs.len(), ys.len());
let is_rejected = reject_probability > confidence;
TestResult {
is_rejected: is_rejected,
statistic: statistic,
reject_probability: reject_probability,
critical_value: critical_value,
confidence: confidence,
}
}
/// Calculate the test statistic for the two sample Kolmogorov-Smirnov test.
///
/// The test statistic is the maximum vertical distance between the ECDFs of
/// the two samples.
fn calculate_statistic(xs: &[f64], ys: &[f64]) -> f64 {
let n = xs.len();
let m = ys.len();
assert!(n > 0 && m > 0);
let mut xs = xs.to_vec();
let mut ys = ys.to_vec();
// xs and ys must be sorted for the stepwise ECDF calculations to work.
xs.sort_by(|x_1, x_2| x_1.partial_cmp(x_2).unwrap());
ys.sort_by(|y_1, y_2| y_1.partial_cmp(y_2).unwrap());
// The current value testing for ECDF difference. Sweeps up through elements
// present in xs and ys.
let mut current: f64;
// i, j index the first values in xs and ys that are greater than current.
let mut i = 0;
let mut j = 0;
// ecdf_xs, ecdf_ys always hold the ECDF(current) of xs and ys.
let mut ecdf_xs = 0.0;
let mut ecdf_ys = 0.0;
// The test statistic value computed over values <= current.
let mut statistic = 0.0;
while i < n && j < m {
// Advance i through duplicate samples in xs.
let x_i = xs[i];
while i + 1 < n && x_i == xs[i + 1] {
i += 1;
}
// Advance j through duplicate samples in ys.
let y_j = ys[j];
while j + 1 < m && y_j == ys[j + 1] {
j += 1;
}
// Step to the next sample value in the ECDF sweep from low to high.
current = x_i.min(y_j);
// Update invariant conditions for i, j, ecdf_xs, and ecdf_ys.
if current == x_i {
ecdf_xs = (i + 1) as f64 / n as f64;
i += 1;
}
if current == y_j {
ecdf_ys = (j + 1) as f64 / m as f64;
j += 1;
}
// Update invariant conditions for the test statistic.
let diff = (ecdf_xs - ecdf_ys).abs();
if diff > statistic {
statistic = diff;
}
}
// Don't need to walk the rest of the samples because one of the ecdfs is
// already one and the other will be increasing up to one. This means the
// difference will be monotonically decreasing, so we have our test
// statistic value already.
statistic
}
/// Calculate the probability that the null hypothesis is false for a two sample
/// Kolmogorov-Smirnov test. Can only reject the null hypothesis if this
/// evidence exceeds the confidence level required.
fn calculate_reject_probability(statistic: f64, n1: usize, n2: usize) -> f64 {
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
let n1 = n1 as f64;
let n2 = n2 as f64;
let factor = ((n1 * n2) / (n1 + n2)).sqrt();
let term = (factor + 0.12 + 0.11 / factor) * statistic;
let reject_probability = 1.0 - probability_kolmogorov_smirnov(term);
assert!(0.0 <= reject_probability && reject_probability <= 1.0);
reject_probability
}
/// Calculate the critical value for the two sample Kolmogorov-Smirnov test.
///
/// # Panics
///
/// There are assertion panics if either sequence size is <= 7 or if the
/// requested confidence level is not between 0 and 1.
///
/// No convergence panic if the binary search does not locate the critical
/// value in less than 200 iterations.
///
/// # Examples
///
/// ```
/// extern crate kernel_density;
///
/// let critical_value = kernel_density::kolmogorov_smirnov::calculate_critical_value(
/// 256, 256, 0.95);
/// println!("Critical value at 95% confidence for samples of size 256 is {}",
/// critical_value); | assert!(n1 > 7 && n2 > 7);
// The test statistic is between zero and one so can binary search quickly
// for the critical value.
let mut low = 0.0;
let mut high = 1.0;
for _ in 1..200 {
if low + 1e-8 >= high {
return high;
}
let mid = low + (high - low) / 2.0;
let reject_probability = calculate_reject_probability(mid, n1, n2);
if reject_probability > confidence {
// Maintain invariant that reject_probability(high) > confidence.
high = mid;
} else {
// Maintain invariant that reject_probability(low) <= confidence.
low = mid;
}
}
panic!("No convergence in calculate_critical_value({}, {}, {}).",
n1,
n2,
confidence);
}
/// Calculate the Kolmogorov-Smirnov probability function.
fn probability_kolmogorov_smirnov(lambda: f64) -> f64 {
if lambda == 0.0 {
return 1.0;
}
let minus_two_lambda_squared = -2.0 * lambda * lambda;
let mut q_ks = 0.0;
for j in 1..200 {
let sign = if j % 2 == 1 {
1.0
} else {
-1.0
};
let j = j as f64;
let term = sign * 2.0 * (minus_two_lambda_squared * j * j).exp();
q_ks += term;
if term.abs() < 1e-8 {
// Trim results that exceed 1.
return q_ks.min(1.0);
}
}
panic!("No convergence in probability_kolmogorov_smirnov({}).",
lambda);
} | /// ```
pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7. | random_line_split |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use canvas_traits::gl_enums;
gl_enums! {
pub enum TexImageTarget {
Texture2D = WebGLRenderingContextConstants::TEXTURE_2D,
CubeMapPositiveX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_X,
CubeMapNegativeX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_X,
CubeMapPositiveY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Y,
CubeMapNegativeY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Y,
CubeMapPositiveZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Z,
CubeMapNegativeZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Z,
}
}
impl TexImageTarget {
pub fn | (&self) -> bool {
match *self {
TexImageTarget::Texture2D => false,
_ => true,
}
}
}
| is_cubic | identifier_name |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use canvas_traits::gl_enums;
gl_enums! {
pub enum TexImageTarget {
Texture2D = WebGLRenderingContextConstants::TEXTURE_2D,
CubeMapPositiveX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_X,
CubeMapNegativeX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_X,
CubeMapPositiveY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Y,
CubeMapNegativeY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Y,
CubeMapPositiveZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Z,
CubeMapNegativeZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Z,
}
}
impl TexImageTarget {
pub fn is_cubic(&self) -> bool |
}
| {
match *self {
TexImageTarget::Texture2D => false,
_ => true,
}
} | identifier_body |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use canvas_traits::gl_enums;
gl_enums! {
pub enum TexImageTarget {
Texture2D = WebGLRenderingContextConstants::TEXTURE_2D,
CubeMapPositiveX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_X,
CubeMapNegativeX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_X,
CubeMapPositiveY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Y,
CubeMapNegativeY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Y,
CubeMapPositiveZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Z,
CubeMapNegativeZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Z,
}
}
impl TexImageTarget { | TexImageTarget::Texture2D => false,
_ => true,
}
}
} | pub fn is_cubic(&self) -> bool {
match *self { | random_line_split |
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use std::time::Instant;
/// A fake `Identity` that returns fixed values.
pub struct Identity {
firmware_version: Vec<u8>,
vendor_firmware_versions: HashMap<u8, Vec<u8>>,
unique_id: Vec<u8>,
}
impl Identity {
/// Creates a new `Identity`.
pub fn new<'a>(
firmware_version: &[u8],
vendor_firmware_versions: impl Iterator<Item = (u8, &'a [u8])>,
unique_id: &[u8],
) -> Self {
fn pad_to_32(data: &[u8]) -> Vec<u8> {
let mut vec = data.to_vec();
while vec.len() < 32 {
vec.push(0);
}
vec.truncate(32);
vec
}
Self {
firmware_version: pad_to_32(firmware_version),
vendor_firmware_versions: vendor_firmware_versions
.map(|(key, value)| (key, pad_to_32(value)))
.collect(),
unique_id: unique_id.to_vec(),
}
}
}
impl manticore::hardware::Identity for Identity {
fn firmware_version(&self) -> &[u8; 32] {
self.firmware_version[..32].try_into().unwrap()
}
fn vendor_firmware_version(&self, slot: u8) -> Option<&[u8; 32]> {
self.vendor_firmware_versions
.get(&slot)
.map(|data| data[..32].try_into().unwrap())
}
fn unique_device_identity(&self) -> &[u8] {
&self.unique_id[..]
}
}
/// A fake `Reset` that returns fixed values.
pub struct Reset {
startup_time: Instant,
resets_since_power_on: u32,
}
impl Reset {
/// Creates a new `Reset`.
pub fn new(resets_since_power_on: u32) -> Self {
Self {
startup_time: Instant::now(),
resets_since_power_on,
}
}
}
impl manticore::hardware::Reset for Reset {
fn resets_since_power_on(&self) -> u32 {
self.resets_since_power_on
}
fn | (&self) -> Duration {
self.startup_time.elapsed()
}
}
| uptime | identifier_name |
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use std::time::Instant;
/// A fake `Identity` that returns fixed values.
pub struct Identity {
firmware_version: Vec<u8>,
vendor_firmware_versions: HashMap<u8, Vec<u8>>,
unique_id: Vec<u8>,
}
impl Identity {
/// Creates a new `Identity`.
pub fn new<'a>(
firmware_version: &[u8],
vendor_firmware_versions: impl Iterator<Item = (u8, &'a [u8])>,
unique_id: &[u8],
) -> Self {
fn pad_to_32(data: &[u8]) -> Vec<u8> {
let mut vec = data.to_vec();
while vec.len() < 32 {
vec.push(0);
}
vec.truncate(32);
vec
}
Self {
firmware_version: pad_to_32(firmware_version),
vendor_firmware_versions: vendor_firmware_versions
.map(|(key, value)| (key, pad_to_32(value)))
.collect(),
unique_id: unique_id.to_vec(),
}
}
}
impl manticore::hardware::Identity for Identity {
fn firmware_version(&self) -> &[u8; 32] {
self.firmware_version[..32].try_into().unwrap()
}
fn vendor_firmware_version(&self, slot: u8) -> Option<&[u8; 32]> {
self.vendor_firmware_versions
.get(&slot)
.map(|data| data[..32].try_into().unwrap())
}
fn unique_device_identity(&self) -> &[u8] {
&self.unique_id[..]
}
}
/// A fake `Reset` that returns fixed values.
pub struct Reset {
startup_time: Instant,
resets_since_power_on: u32,
} |
impl Reset {
/// Creates a new `Reset`.
pub fn new(resets_since_power_on: u32) -> Self {
Self {
startup_time: Instant::now(),
resets_since_power_on,
}
}
}
impl manticore::hardware::Reset for Reset {
fn resets_since_power_on(&self) -> u32 {
self.resets_since_power_on
}
fn uptime(&self) -> Duration {
self.startup_time.elapsed()
}
} | random_line_split |
|
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use std::time::Instant;
/// A fake `Identity` that returns fixed values.
pub struct Identity {
firmware_version: Vec<u8>,
vendor_firmware_versions: HashMap<u8, Vec<u8>>,
unique_id: Vec<u8>,
}
impl Identity {
/// Creates a new `Identity`.
pub fn new<'a>(
firmware_version: &[u8],
vendor_firmware_versions: impl Iterator<Item = (u8, &'a [u8])>,
unique_id: &[u8],
) -> Self {
fn pad_to_32(data: &[u8]) -> Vec<u8> {
let mut vec = data.to_vec();
while vec.len() < 32 {
vec.push(0);
}
vec.truncate(32);
vec
}
Self {
firmware_version: pad_to_32(firmware_version),
vendor_firmware_versions: vendor_firmware_versions
.map(|(key, value)| (key, pad_to_32(value)))
.collect(),
unique_id: unique_id.to_vec(),
}
}
}
impl manticore::hardware::Identity for Identity {
fn firmware_version(&self) -> &[u8; 32] {
self.firmware_version[..32].try_into().unwrap()
}
fn vendor_firmware_version(&self, slot: u8) -> Option<&[u8; 32]> {
self.vendor_firmware_versions
.get(&slot)
.map(|data| data[..32].try_into().unwrap())
}
fn unique_device_identity(&self) -> &[u8] {
&self.unique_id[..]
}
}
/// A fake `Reset` that returns fixed values.
pub struct Reset {
startup_time: Instant,
resets_since_power_on: u32,
}
impl Reset {
/// Creates a new `Reset`.
pub fn new(resets_since_power_on: u32) -> Self {
Self {
startup_time: Instant::now(),
resets_since_power_on,
}
}
}
impl manticore::hardware::Reset for Reset {
fn resets_since_power_on(&self) -> u32 |
fn uptime(&self) -> Duration {
self.startup_time.elapsed()
}
}
| {
self.resets_since_power_on
} | identifier_body |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?P<vel_z>-?[0-9]+)>, a=<(?P<acc_x>-?[0-9]+),(?P<acc_y>-?[0-9]+),(?P<acc_z>-?[0-9]+)>$").unwrap();
}
#[derive(Debug, Copy, Clone)]
struct Particle {
pos: (f64, f64, f64),
vel: (f64, f64, f64),
acc: (f64, f64, f64),
}
impl FromStr for Particle {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let caps = PARTICLE_RE.captures(s).ok_or(())?;
let pos_x = caps.name("pos_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let pos_y = caps.name("pos_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let pos_z = caps.name("pos_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_x = caps.name("vel_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_y = caps.name("vel_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_z = caps.name("vel_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_x = caps.name("acc_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_y = caps.name("acc_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_z = caps.name("acc_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
Ok(Particle {
pos: (pos_x, pos_y, pos_z),
vel: (vel_x, vel_y, vel_z),
acc: (acc_x, acc_y, acc_z),
})
}
}
#[derive(Debug)]
struct Simulation(Vec<Particle>);
impl FromStr for Simulation {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Simulation(s.lines()
.map(|line| line.parse())
.collect::<Result<Vec<Particle>, ()>>()?))
}
}
impl Simulation {
fn do_step(&mut self) {
for particle in self.0.iter_mut() {
particle.vel.0 += particle.acc.0;
particle.vel.1 += particle.acc.1;
particle.vel.2 += particle.acc.2;
particle.pos.0 += particle.vel.0;
particle.pos.1 += particle.vel.1;
particle.pos.2 += particle.vel.2;
}
self.0 = self.0
.iter()
.filter(|particle_1| {
let occurrence_count = self.0.iter().fold(
0,
|acc, particle_2| if particle_1.pos ==
particle_2.pos
{
acc + 1
} else {
acc
},
);
occurrence_count <= 1
})
.cloned()
.collect();
}
fn get_longterm_closest_particle(&self) -> (usize, &Particle) |
fn get_num_particles(&self) -> usize {
self.0.len()
}
}
fn dot_product(left: &(f64, f64, f64), right: &(f64, f64, f64)) -> f64 {
left.0 * right.0 + left.1 * right.1 + left.2 * right.2
}
fn get_norm(vec: &(f64, f64, f64)) -> f64 {
dot_product(&vec, &vec).sqrt()
}
fn main() {
let mut input_str = String::new();
io::stdin().read_to_string(&mut input_str).expect(
"input error",
);
let mut sim: Simulation = input_str.parse().expect("parse error");
println!(
"The longterm closest particle is: {:?}",
sim.get_longterm_closest_particle()
);
println!("Running 100000 steps in the simulation");
for i in 0..100_000 {
if i % 10_000 == 0 {
println!("*** {}", i);
}
sim.do_step();
}
println!(
"There are {} particles left after 100000 steps.",
sim.get_num_particles()
);
}
#[cfg(test)]
mod tests {
use super::Simulation;
#[test]
fn simulation_test() {
let test_str = "p=<3,0,0>, v=<2,0,0>, a=<-1,0,0>\n\
p=<4,0,0>, v=<0,0,0>, a=<-2,0,0>";
let sim: Simulation = test_str.parse().unwrap();
assert_eq!(0, sim.get_longterm_closest_particle().0);
}
#[test]
fn crash_test() {
let test_str = "p=<-6,0,0>, v=<3,0,0>, a=<0,0,0>\n\
p=<-4,0,0>, v=<2,0,0>, a=<0,0,0>\n\
p=<-2,0,0>, v=<1,0,0>, a=<0,0,0>\n\
p=<3,0,0>, v=<-1,0,0>, a=<0,0,0>";
let mut sim: Simulation = test_str.parse().unwrap();
assert_eq!(4, sim.get_num_particles());
sim.do_step();
assert_eq!(4, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
}
}
| {
let (idx, part, _) = self.0
.iter()
.enumerate()
.map(|(idx, part)| {
let norm = get_norm(&part.acc);
(idx, part, norm)
})
.min_by(|&(_, _, l_norm), &(_, _, r_norm)| {
l_norm.partial_cmp(&r_norm).unwrap()
})
.unwrap();
(idx, part)
} | identifier_body |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?P<vel_z>-?[0-9]+)>, a=<(?P<acc_x>-?[0-9]+),(?P<acc_y>-?[0-9]+),(?P<acc_z>-?[0-9]+)>$").unwrap();
}
#[derive(Debug, Copy, Clone)]
struct Particle {
pos: (f64, f64, f64),
vel: (f64, f64, f64),
acc: (f64, f64, f64),
}
impl FromStr for Particle {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let caps = PARTICLE_RE.captures(s).ok_or(())?;
let pos_x = caps.name("pos_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let pos_y = caps.name("pos_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let pos_z = caps.name("pos_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_x = caps.name("vel_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_y = caps.name("vel_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_z = caps.name("vel_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_x = caps.name("acc_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_y = caps.name("acc_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_z = caps.name("acc_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
Ok(Particle {
pos: (pos_x, pos_y, pos_z),
vel: (vel_x, vel_y, vel_z),
acc: (acc_x, acc_y, acc_z),
})
}
}
#[derive(Debug)]
struct Simulation(Vec<Particle>);
impl FromStr for Simulation {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Simulation(s.lines()
.map(|line| line.parse())
.collect::<Result<Vec<Particle>, ()>>()?))
}
}
impl Simulation {
fn do_step(&mut self) {
for particle in self.0.iter_mut() {
particle.vel.0 += particle.acc.0;
particle.vel.1 += particle.acc.1;
particle.vel.2 += particle.acc.2;
particle.pos.0 += particle.vel.0;
particle.pos.1 += particle.vel.1;
particle.pos.2 += particle.vel.2;
}
self.0 = self.0
.iter()
.filter(|particle_1| {
let occurrence_count = self.0.iter().fold(
0,
|acc, particle_2| if particle_1.pos ==
particle_2.pos
| else {
acc
},
);
occurrence_count <= 1
})
.cloned()
.collect();
}
fn get_longterm_closest_particle(&self) -> (usize, &Particle) {
let (idx, part, _) = self.0
.iter()
.enumerate()
.map(|(idx, part)| {
let norm = get_norm(&part.acc);
(idx, part, norm)
})
.min_by(|&(_, _, l_norm), &(_, _, r_norm)| {
l_norm.partial_cmp(&r_norm).unwrap()
})
.unwrap();
(idx, part)
}
fn get_num_particles(&self) -> usize {
self.0.len()
}
}
fn dot_product(left: &(f64, f64, f64), right: &(f64, f64, f64)) -> f64 {
left.0 * right.0 + left.1 * right.1 + left.2 * right.2
}
fn get_norm(vec: &(f64, f64, f64)) -> f64 {
dot_product(&vec, &vec).sqrt()
}
fn main() {
let mut input_str = String::new();
io::stdin().read_to_string(&mut input_str).expect(
"input error",
);
let mut sim: Simulation = input_str.parse().expect("parse error");
println!(
"The longterm closest particle is: {:?}",
sim.get_longterm_closest_particle()
);
println!("Running 100000 steps in the simulation");
for i in 0..100_000 {
if i % 10_000 == 0 {
println!("*** {}", i);
}
sim.do_step();
}
println!(
"There are {} particles left after 100000 steps.",
sim.get_num_particles()
);
}
#[cfg(test)]
mod tests {
use super::Simulation;
#[test]
fn simulation_test() {
let test_str = "p=<3,0,0>, v=<2,0,0>, a=<-1,0,0>\n\
p=<4,0,0>, v=<0,0,0>, a=<-2,0,0>";
let sim: Simulation = test_str.parse().unwrap();
assert_eq!(0, sim.get_longterm_closest_particle().0);
}
#[test]
fn crash_test() {
let test_str = "p=<-6,0,0>, v=<3,0,0>, a=<0,0,0>\n\
p=<-4,0,0>, v=<2,0,0>, a=<0,0,0>\n\
p=<-2,0,0>, v=<1,0,0>, a=<0,0,0>\n\
p=<3,0,0>, v=<-1,0,0>, a=<0,0,0>";
let mut sim: Simulation = test_str.parse().unwrap();
assert_eq!(4, sim.get_num_particles());
sim.do_step();
assert_eq!(4, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
}
}
| {
acc + 1
} | conditional_block |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?P<vel_z>-?[0-9]+)>, a=<(?P<acc_x>-?[0-9]+),(?P<acc_y>-?[0-9]+),(?P<acc_z>-?[0-9]+)>$").unwrap();
}
#[derive(Debug, Copy, Clone)]
struct Particle {
pos: (f64, f64, f64),
vel: (f64, f64, f64),
acc: (f64, f64, f64),
}
impl FromStr for Particle {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let caps = PARTICLE_RE.captures(s).ok_or(())?;
let pos_x = caps.name("pos_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let pos_y = caps.name("pos_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let pos_z = caps.name("pos_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_x = caps.name("vel_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_y = caps.name("vel_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_z = caps.name("vel_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_x = caps.name("acc_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_y = caps.name("acc_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_z = caps.name("acc_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
Ok(Particle {
pos: (pos_x, pos_y, pos_z),
vel: (vel_x, vel_y, vel_z),
acc: (acc_x, acc_y, acc_z),
})
}
}
#[derive(Debug)]
struct Simulation(Vec<Particle>);
impl FromStr for Simulation {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Simulation(s.lines()
.map(|line| line.parse())
.collect::<Result<Vec<Particle>, ()>>()?))
}
}
impl Simulation {
fn do_step(&mut self) {
for particle in self.0.iter_mut() {
particle.vel.0 += particle.acc.0;
particle.vel.1 += particle.acc.1;
particle.vel.2 += particle.acc.2;
particle.pos.0 += particle.vel.0;
particle.pos.1 += particle.vel.1;
particle.pos.2 += particle.vel.2;
}
self.0 = self.0
.iter()
.filter(|particle_1| {
| acc + 1
} else {
acc
},
);
occurrence_count <= 1
})
.cloned()
.collect();
}
fn get_longterm_closest_particle(&self) -> (usize, &Particle) {
let (idx, part, _) = self.0
.iter()
.enumerate()
.map(|(idx, part)| {
let norm = get_norm(&part.acc);
(idx, part, norm)
})
.min_by(|&(_, _, l_norm), &(_, _, r_norm)| {
l_norm.partial_cmp(&r_norm).unwrap()
})
.unwrap();
(idx, part)
}
fn get_num_particles(&self) -> usize {
self.0.len()
}
}
fn dot_product(left: &(f64, f64, f64), right: &(f64, f64, f64)) -> f64 {
left.0 * right.0 + left.1 * right.1 + left.2 * right.2
}
fn get_norm(vec: &(f64, f64, f64)) -> f64 {
dot_product(&vec, &vec).sqrt()
}
fn main() {
let mut input_str = String::new();
io::stdin().read_to_string(&mut input_str).expect(
"input error",
);
let mut sim: Simulation = input_str.parse().expect("parse error");
println!(
"The longterm closest particle is: {:?}",
sim.get_longterm_closest_particle()
);
println!("Running 100000 steps in the simulation");
for i in 0..100_000 {
if i % 10_000 == 0 {
println!("*** {}", i);
}
sim.do_step();
}
println!(
"There are {} particles left after 100000 steps.",
sim.get_num_particles()
);
}
#[cfg(test)]
mod tests {
use super::Simulation;
#[test]
fn simulation_test() {
let test_str = "p=<3,0,0>, v=<2,0,0>, a=<-1,0,0>\n\
p=<4,0,0>, v=<0,0,0>, a=<-2,0,0>";
let sim: Simulation = test_str.parse().unwrap();
assert_eq!(0, sim.get_longterm_closest_particle().0);
}
#[test]
fn crash_test() {
let test_str = "p=<-6,0,0>, v=<3,0,0>, a=<0,0,0>\n\
p=<-4,0,0>, v=<2,0,0>, a=<0,0,0>\n\
p=<-2,0,0>, v=<1,0,0>, a=<0,0,0>\n\
p=<3,0,0>, v=<-1,0,0>, a=<0,0,0>";
let mut sim: Simulation = test_str.parse().unwrap();
assert_eq!(4, sim.get_num_particles());
sim.do_step();
assert_eq!(4, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
}
} | let occurrence_count = self.0.iter().fold(
0,
|acc, particle_2| if particle_1.pos ==
particle_2.pos
{ | random_line_split |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?P<vel_z>-?[0-9]+)>, a=<(?P<acc_x>-?[0-9]+),(?P<acc_y>-?[0-9]+),(?P<acc_z>-?[0-9]+)>$").unwrap();
}
#[derive(Debug, Copy, Clone)]
struct Particle {
pos: (f64, f64, f64),
vel: (f64, f64, f64),
acc: (f64, f64, f64),
}
impl FromStr for Particle {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let caps = PARTICLE_RE.captures(s).ok_or(())?;
let pos_x = caps.name("pos_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let pos_y = caps.name("pos_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let pos_z = caps.name("pos_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_x = caps.name("vel_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_y = caps.name("vel_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let vel_z = caps.name("vel_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_x = caps.name("acc_x").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_y = caps.name("acc_y").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
let acc_z = caps.name("acc_z").ok_or(())?.as_str().parse().map_err(
|_| (),
)?;
Ok(Particle {
pos: (pos_x, pos_y, pos_z),
vel: (vel_x, vel_y, vel_z),
acc: (acc_x, acc_y, acc_z),
})
}
}
#[derive(Debug)]
struct Simulation(Vec<Particle>);
impl FromStr for Simulation {
type Err = ();
fn | (s: &str) -> Result<Self, Self::Err> {
Ok(Simulation(s.lines()
.map(|line| line.parse())
.collect::<Result<Vec<Particle>, ()>>()?))
}
}
impl Simulation {
fn do_step(&mut self) {
for particle in self.0.iter_mut() {
particle.vel.0 += particle.acc.0;
particle.vel.1 += particle.acc.1;
particle.vel.2 += particle.acc.2;
particle.pos.0 += particle.vel.0;
particle.pos.1 += particle.vel.1;
particle.pos.2 += particle.vel.2;
}
self.0 = self.0
.iter()
.filter(|particle_1| {
let occurrence_count = self.0.iter().fold(
0,
|acc, particle_2| if particle_1.pos ==
particle_2.pos
{
acc + 1
} else {
acc
},
);
occurrence_count <= 1
})
.cloned()
.collect();
}
fn get_longterm_closest_particle(&self) -> (usize, &Particle) {
let (idx, part, _) = self.0
.iter()
.enumerate()
.map(|(idx, part)| {
let norm = get_norm(&part.acc);
(idx, part, norm)
})
.min_by(|&(_, _, l_norm), &(_, _, r_norm)| {
l_norm.partial_cmp(&r_norm).unwrap()
})
.unwrap();
(idx, part)
}
fn get_num_particles(&self) -> usize {
self.0.len()
}
}
fn dot_product(left: &(f64, f64, f64), right: &(f64, f64, f64)) -> f64 {
left.0 * right.0 + left.1 * right.1 + left.2 * right.2
}
fn get_norm(vec: &(f64, f64, f64)) -> f64 {
dot_product(&vec, &vec).sqrt()
}
fn main() {
let mut input_str = String::new();
io::stdin().read_to_string(&mut input_str).expect(
"input error",
);
let mut sim: Simulation = input_str.parse().expect("parse error");
println!(
"The longterm closest particle is: {:?}",
sim.get_longterm_closest_particle()
);
println!("Running 100000 steps in the simulation");
for i in 0..100_000 {
if i % 10_000 == 0 {
println!("*** {}", i);
}
sim.do_step();
}
println!(
"There are {} particles left after 100000 steps.",
sim.get_num_particles()
);
}
#[cfg(test)]
mod tests {
use super::Simulation;
#[test]
fn simulation_test() {
let test_str = "p=<3,0,0>, v=<2,0,0>, a=<-1,0,0>\n\
p=<4,0,0>, v=<0,0,0>, a=<-2,0,0>";
let sim: Simulation = test_str.parse().unwrap();
assert_eq!(0, sim.get_longterm_closest_particle().0);
}
#[test]
fn crash_test() {
let test_str = "p=<-6,0,0>, v=<3,0,0>, a=<0,0,0>\n\
p=<-4,0,0>, v=<2,0,0>, a=<0,0,0>\n\
p=<-2,0,0>, v=<1,0,0>, a=<0,0,0>\n\
p=<3,0,0>, v=<-1,0,0>, a=<0,0,0>";
let mut sim: Simulation = test_str.parse().unwrap();
assert_eq!(4, sim.get_num_particles());
sim.do_step();
assert_eq!(4, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
sim.do_step();
assert_eq!(1, sim.get_num_particles());
}
}
| from_str | identifier_name |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// 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
// OWNER 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.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not be edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
#![allow(non_snake_case, unused_imports)]
use eutil;
use interfaces;
use types;
use wrappers::CefWrap;
use libc;
use std::collections::HashMap;
use std::ptr;
//
// Structure representing a message. Can be used on any process and thread.
//
#[repr(C)]
pub struct _cef_process_message_t {
//
// Base structure.
//
pub base: types::cef_base_t,
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub is_valid: Option<extern "C" fn(
this: *mut cef_process_message_t) -> libc::c_int>,
//
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
//
pub is_read_only: Option<extern "C" fn(
this: *mut cef_process_message_t) -> libc::c_int>,
//
// Returns a writable copy of this object.
//
pub copy: Option<extern "C" fn(
this: *mut cef_process_message_t) -> *mut interfaces::cef_process_message_t>,
//
// Returns the message name.
//
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_name: Option<extern "C" fn(
this: *mut cef_process_message_t) -> types::cef_string_userfree_t>,
//
// Returns the list of arguments.
//
pub get_argument_list: Option<extern "C" fn(
this: *mut cef_process_message_t) -> *mut interfaces::cef_list_value_t>,
//
// The reference count. This will only be present for Rust instances!
//
pub ref_count: usize,
//
// Extra data. This will only be present for Rust instances!
//
pub extra: u8,
}
pub type cef_process_message_t = _cef_process_message_t;
//
// Structure representing a message. Can be used on any process and thread.
//
pub struct CefProcessMessage {
c_object: *mut cef_process_message_t,
}
impl Clone for CefProcessMessage {
fn clone(&self) -> CefProcessMessage{
unsafe {
if!self.c_object.is_null() {
((*self.c_object).base.add_ref.unwrap())(&mut (*self.c_object).base);
}
CefProcessMessage {
c_object: self.c_object,
}
}
}
}
impl Drop for CefProcessMessage {
fn drop(&mut self) |
}
impl CefProcessMessage {
pub unsafe fn from_c_object(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage {
c_object: c_object,
}
}
pub unsafe fn from_c_object_addref(c_object: *mut cef_process_message_t) -> CefProcessMessage {
if!c_object.is_null() {
((*c_object).base.add_ref.unwrap())(&mut (*c_object).base);
}
CefProcessMessage {
c_object: c_object,
}
}
pub fn c_object(&self) -> *mut cef_process_message_t {
self.c_object
}
pub fn c_object_addrefed(&self) -> *mut cef_process_message_t {
unsafe {
if!self.c_object.is_null() {
eutil::add_ref(self.c_object as *mut types::cef_base_t);
}
self.c_object
}
}
pub fn is_null_cef_object(&self) -> bool {
self.c_object.is_null()
}
pub fn is_not_null_cef_object(&self) -> bool {
!self.c_object.is_null()
}
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub fn is_valid(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_valid.unwrap())(
self.c_object))
}
}
//
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
//
pub fn is_read_only(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_read_only.unwrap())(
self.c_object))
}
}
//
// Returns a writable copy of this object.
//
pub fn copy(&self) -> interfaces::CefProcessMessage {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).copy.unwrap())(
self.c_object))
}
}
//
// Returns the message name.
//
// The resulting string must be freed by calling cef_string_userfree_free().
pub fn get_name(&self) -> String {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).get_name.unwrap())(
self.c_object))
}
}
//
// Returns the list of arguments.
//
pub fn get_argument_list(&self) -> interfaces::CefListValue {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).get_argument_list.unwrap())(
self.c_object))
}
}
//
// Create a new cef_process_message_t object with the specified name.
//
pub fn create(name: &[u16]) -> interfaces::CefProcessMessage {
unsafe {
CefWrap::to_rust(
::process_message::cef_process_message_create(
CefWrap::to_c(name)))
}
}
}
impl CefWrap<*mut cef_process_message_t> for CefProcessMessage {
fn to_c(rust_object: CefProcessMessage) -> *mut cef_process_message_t {
rust_object.c_object_addrefed()
}
unsafe fn to_rust(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage::from_c_object_addref(c_object)
}
}
impl CefWrap<*mut cef_process_message_t> for Option<CefProcessMessage> {
fn to_c(rust_object: Option<CefProcessMessage>) -> *mut cef_process_message_t {
match rust_object {
None => ptr::null_mut(),
Some(rust_object) => rust_object.c_object_addrefed(),
}
}
unsafe fn to_rust(c_object: *mut cef_process_message_t) -> Option<CefProcessMessage> {
if c_object.is_null() {
None
} else {
Some(CefProcessMessage::from_c_object_addref(c_object))
}
}
}
| {
unsafe {
if !self.c_object.is_null() {
((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base);
}
}
} | identifier_body |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// 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
// OWNER 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.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not be edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
#![allow(non_snake_case, unused_imports)]
use eutil;
use interfaces;
use types;
use wrappers::CefWrap;
use libc;
use std::collections::HashMap;
use std::ptr;
//
// Structure representing a message. Can be used on any process and thread.
//
#[repr(C)]
pub struct _cef_process_message_t {
//
// Base structure.
//
pub base: types::cef_base_t,
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub is_valid: Option<extern "C" fn(
this: *mut cef_process_message_t) -> libc::c_int>,
//
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
//
pub is_read_only: Option<extern "C" fn(
this: *mut cef_process_message_t) -> libc::c_int>,
//
// Returns a writable copy of this object.
//
pub copy: Option<extern "C" fn(
this: *mut cef_process_message_t) -> *mut interfaces::cef_process_message_t>,
//
// Returns the message name.
//
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_name: Option<extern "C" fn(
this: *mut cef_process_message_t) -> types::cef_string_userfree_t>,
//
// Returns the list of arguments.
//
pub get_argument_list: Option<extern "C" fn(
this: *mut cef_process_message_t) -> *mut interfaces::cef_list_value_t>,
//
// The reference count. This will only be present for Rust instances!
//
pub ref_count: usize,
//
// Extra data. This will only be present for Rust instances!
//
pub extra: u8,
}
pub type cef_process_message_t = _cef_process_message_t;
//
// Structure representing a message. Can be used on any process and thread.
//
pub struct CefProcessMessage {
c_object: *mut cef_process_message_t,
}
impl Clone for CefProcessMessage {
fn clone(&self) -> CefProcessMessage{
unsafe {
if!self.c_object.is_null() {
((*self.c_object).base.add_ref.unwrap())(&mut (*self.c_object).base);
}
CefProcessMessage {
c_object: self.c_object,
}
}
}
}
impl Drop for CefProcessMessage {
fn drop(&mut self) {
unsafe {
if!self.c_object.is_null() {
((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base);
}
}
}
}
impl CefProcessMessage {
pub unsafe fn from_c_object(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage {
c_object: c_object,
}
}
pub unsafe fn from_c_object_addref(c_object: *mut cef_process_message_t) -> CefProcessMessage {
if!c_object.is_null() |
CefProcessMessage {
c_object: c_object,
}
}
pub fn c_object(&self) -> *mut cef_process_message_t {
self.c_object
}
pub fn c_object_addrefed(&self) -> *mut cef_process_message_t {
unsafe {
if!self.c_object.is_null() {
eutil::add_ref(self.c_object as *mut types::cef_base_t);
}
self.c_object
}
}
pub fn is_null_cef_object(&self) -> bool {
self.c_object.is_null()
}
pub fn is_not_null_cef_object(&self) -> bool {
!self.c_object.is_null()
}
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub fn is_valid(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_valid.unwrap())(
self.c_object))
}
}
//
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
//
pub fn is_read_only(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_read_only.unwrap())(
self.c_object))
}
}
//
// Returns a writable copy of this object.
//
pub fn copy(&self) -> interfaces::CefProcessMessage {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).copy.unwrap())(
self.c_object))
}
}
//
// Returns the message name.
//
// The resulting string must be freed by calling cef_string_userfree_free().
pub fn get_name(&self) -> String {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).get_name.unwrap())(
self.c_object))
}
}
//
// Returns the list of arguments.
//
pub fn get_argument_list(&self) -> interfaces::CefListValue {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).get_argument_list.unwrap())(
self.c_object))
}
}
//
// Create a new cef_process_message_t object with the specified name.
//
pub fn create(name: &[u16]) -> interfaces::CefProcessMessage {
unsafe {
CefWrap::to_rust(
::process_message::cef_process_message_create(
CefWrap::to_c(name)))
}
}
}
impl CefWrap<*mut cef_process_message_t> for CefProcessMessage {
fn to_c(rust_object: CefProcessMessage) -> *mut cef_process_message_t {
rust_object.c_object_addrefed()
}
unsafe fn to_rust(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage::from_c_object_addref(c_object)
}
}
impl CefWrap<*mut cef_process_message_t> for Option<CefProcessMessage> {
fn to_c(rust_object: Option<CefProcessMessage>) -> *mut cef_process_message_t {
match rust_object {
None => ptr::null_mut(),
Some(rust_object) => rust_object.c_object_addrefed(),
}
}
unsafe fn to_rust(c_object: *mut cef_process_message_t) -> Option<CefProcessMessage> {
if c_object.is_null() {
None
} else {
Some(CefProcessMessage::from_c_object_addref(c_object))
}
}
}
| {
((*c_object).base.add_ref.unwrap())(&mut (*c_object).base);
} | conditional_block |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// 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
// OWNER 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.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not be edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
#![allow(non_snake_case, unused_imports)]
use eutil;
use interfaces;
use types;
use wrappers::CefWrap;
use libc;
use std::collections::HashMap;
use std::ptr;
//
// Structure representing a message. Can be used on any process and thread.
//
#[repr(C)]
pub struct _cef_process_message_t {
//
// Base structure.
//
pub base: types::cef_base_t,
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub is_valid: Option<extern "C" fn(
this: *mut cef_process_message_t) -> libc::c_int>,
//
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
//
pub is_read_only: Option<extern "C" fn(
this: *mut cef_process_message_t) -> libc::c_int>,
//
// Returns a writable copy of this object.
//
pub copy: Option<extern "C" fn(
this: *mut cef_process_message_t) -> *mut interfaces::cef_process_message_t>,
//
// Returns the message name.
//
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_name: Option<extern "C" fn(
this: *mut cef_process_message_t) -> types::cef_string_userfree_t>,
//
// Returns the list of arguments.
//
pub get_argument_list: Option<extern "C" fn(
this: *mut cef_process_message_t) -> *mut interfaces::cef_list_value_t>,
//
// The reference count. This will only be present for Rust instances!
//
pub ref_count: usize,
//
// Extra data. This will only be present for Rust instances!
//
pub extra: u8,
}
pub type cef_process_message_t = _cef_process_message_t;
//
// Structure representing a message. Can be used on any process and thread.
//
pub struct CefProcessMessage {
c_object: *mut cef_process_message_t,
}
impl Clone for CefProcessMessage {
fn clone(&self) -> CefProcessMessage{
unsafe {
if!self.c_object.is_null() {
((*self.c_object).base.add_ref.unwrap())(&mut (*self.c_object).base);
}
CefProcessMessage {
c_object: self.c_object,
}
}
}
}
impl Drop for CefProcessMessage {
fn drop(&mut self) {
unsafe {
if!self.c_object.is_null() {
((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base);
}
}
}
}
impl CefProcessMessage {
pub unsafe fn from_c_object(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage {
c_object: c_object,
}
}
pub unsafe fn from_c_object_addref(c_object: *mut cef_process_message_t) -> CefProcessMessage {
if!c_object.is_null() {
((*c_object).base.add_ref.unwrap())(&mut (*c_object).base);
}
CefProcessMessage {
c_object: c_object,
}
}
pub fn c_object(&self) -> *mut cef_process_message_t {
self.c_object
}
pub fn c_object_addrefed(&self) -> *mut cef_process_message_t {
unsafe {
if!self.c_object.is_null() {
eutil::add_ref(self.c_object as *mut types::cef_base_t);
}
self.c_object
}
}
pub fn is_null_cef_object(&self) -> bool {
self.c_object.is_null() | pub fn is_not_null_cef_object(&self) -> bool {
!self.c_object.is_null()
}
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub fn is_valid(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_valid.unwrap())(
self.c_object))
}
}
//
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
//
pub fn is_read_only(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_read_only.unwrap())(
self.c_object))
}
}
//
// Returns a writable copy of this object.
//
pub fn copy(&self) -> interfaces::CefProcessMessage {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).copy.unwrap())(
self.c_object))
}
}
//
// Returns the message name.
//
// The resulting string must be freed by calling cef_string_userfree_free().
pub fn get_name(&self) -> String {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).get_name.unwrap())(
self.c_object))
}
}
//
// Returns the list of arguments.
//
pub fn get_argument_list(&self) -> interfaces::CefListValue {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).get_argument_list.unwrap())(
self.c_object))
}
}
//
// Create a new cef_process_message_t object with the specified name.
//
pub fn create(name: &[u16]) -> interfaces::CefProcessMessage {
unsafe {
CefWrap::to_rust(
::process_message::cef_process_message_create(
CefWrap::to_c(name)))
}
}
}
impl CefWrap<*mut cef_process_message_t> for CefProcessMessage {
fn to_c(rust_object: CefProcessMessage) -> *mut cef_process_message_t {
rust_object.c_object_addrefed()
}
unsafe fn to_rust(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage::from_c_object_addref(c_object)
}
}
impl CefWrap<*mut cef_process_message_t> for Option<CefProcessMessage> {
fn to_c(rust_object: Option<CefProcessMessage>) -> *mut cef_process_message_t {
match rust_object {
None => ptr::null_mut(),
Some(rust_object) => rust_object.c_object_addrefed(),
}
}
unsafe fn to_rust(c_object: *mut cef_process_message_t) -> Option<CefProcessMessage> {
if c_object.is_null() {
None
} else {
Some(CefProcessMessage::from_c_object_addref(c_object))
}
}
} | } | random_line_split |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// 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
// OWNER 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.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not be edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
#![allow(non_snake_case, unused_imports)]
use eutil;
use interfaces;
use types;
use wrappers::CefWrap;
use libc;
use std::collections::HashMap;
use std::ptr;
//
// Structure representing a message. Can be used on any process and thread.
//
#[repr(C)]
pub struct _cef_process_message_t {
//
// Base structure.
//
pub base: types::cef_base_t,
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub is_valid: Option<extern "C" fn(
this: *mut cef_process_message_t) -> libc::c_int>,
//
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
//
pub is_read_only: Option<extern "C" fn(
this: *mut cef_process_message_t) -> libc::c_int>,
//
// Returns a writable copy of this object.
//
pub copy: Option<extern "C" fn(
this: *mut cef_process_message_t) -> *mut interfaces::cef_process_message_t>,
//
// Returns the message name.
//
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_name: Option<extern "C" fn(
this: *mut cef_process_message_t) -> types::cef_string_userfree_t>,
//
// Returns the list of arguments.
//
pub get_argument_list: Option<extern "C" fn(
this: *mut cef_process_message_t) -> *mut interfaces::cef_list_value_t>,
//
// The reference count. This will only be present for Rust instances!
//
pub ref_count: usize,
//
// Extra data. This will only be present for Rust instances!
//
pub extra: u8,
}
pub type cef_process_message_t = _cef_process_message_t;
//
// Structure representing a message. Can be used on any process and thread.
//
pub struct CefProcessMessage {
c_object: *mut cef_process_message_t,
}
impl Clone for CefProcessMessage {
fn clone(&self) -> CefProcessMessage{
unsafe {
if!self.c_object.is_null() {
((*self.c_object).base.add_ref.unwrap())(&mut (*self.c_object).base);
}
CefProcessMessage {
c_object: self.c_object,
}
}
}
}
impl Drop for CefProcessMessage {
fn drop(&mut self) {
unsafe {
if!self.c_object.is_null() {
((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base);
}
}
}
}
impl CefProcessMessage {
pub unsafe fn from_c_object(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage {
c_object: c_object,
}
}
pub unsafe fn from_c_object_addref(c_object: *mut cef_process_message_t) -> CefProcessMessage {
if!c_object.is_null() {
((*c_object).base.add_ref.unwrap())(&mut (*c_object).base);
}
CefProcessMessage {
c_object: c_object,
}
}
pub fn c_object(&self) -> *mut cef_process_message_t {
self.c_object
}
pub fn c_object_addrefed(&self) -> *mut cef_process_message_t {
unsafe {
if!self.c_object.is_null() {
eutil::add_ref(self.c_object as *mut types::cef_base_t);
}
self.c_object
}
}
pub fn is_null_cef_object(&self) -> bool {
self.c_object.is_null()
}
pub fn is_not_null_cef_object(&self) -> bool {
!self.c_object.is_null()
}
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub fn is_valid(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_valid.unwrap())(
self.c_object))
}
}
//
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
//
pub fn | (&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_read_only.unwrap())(
self.c_object))
}
}
//
// Returns a writable copy of this object.
//
pub fn copy(&self) -> interfaces::CefProcessMessage {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).copy.unwrap())(
self.c_object))
}
}
//
// Returns the message name.
//
// The resulting string must be freed by calling cef_string_userfree_free().
pub fn get_name(&self) -> String {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).get_name.unwrap())(
self.c_object))
}
}
//
// Returns the list of arguments.
//
pub fn get_argument_list(&self) -> interfaces::CefListValue {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).get_argument_list.unwrap())(
self.c_object))
}
}
//
// Create a new cef_process_message_t object with the specified name.
//
pub fn create(name: &[u16]) -> interfaces::CefProcessMessage {
unsafe {
CefWrap::to_rust(
::process_message::cef_process_message_create(
CefWrap::to_c(name)))
}
}
}
impl CefWrap<*mut cef_process_message_t> for CefProcessMessage {
fn to_c(rust_object: CefProcessMessage) -> *mut cef_process_message_t {
rust_object.c_object_addrefed()
}
unsafe fn to_rust(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage::from_c_object_addref(c_object)
}
}
impl CefWrap<*mut cef_process_message_t> for Option<CefProcessMessage> {
fn to_c(rust_object: Option<CefProcessMessage>) -> *mut cef_process_message_t {
match rust_object {
None => ptr::null_mut(),
Some(rust_object) => rust_object.c_object_addrefed(),
}
}
unsafe fn to_rust(c_object: *mut cef_process_message_t) -> Option<CefProcessMessage> {
if c_object.is_null() {
None
} else {
Some(CefProcessMessage::from_c_object_addref(c_object))
}
}
}
| is_read_only | identifier_name |
videotracklist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{self, VideoTrackListMethods};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::Dom;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::eventtarget::EventTarget;
use crate::dom::htmlmediaelement::HTMLMediaElement;
use crate::dom::videotrack::VideoTrack;
use crate::dom::window::Window;
use crate::task_source::TaskSource;
use dom_struct::dom_struct;
#[dom_struct]
pub struct VideoTrackList {
eventtarget: EventTarget,
tracks: DomRefCell<Vec<Dom<VideoTrack>>>,
media_element: Option<Dom<HTMLMediaElement>>,
}
impl VideoTrackList {
pub fn new_inherited(
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> VideoTrackList {
VideoTrackList {
eventtarget: EventTarget::new_inherited(),
tracks: DomRefCell::new(tracks.iter().map(|track| Dom::from_ref(&**track)).collect()),
media_element: media_element.map(|m| Dom::from_ref(m)),
}
}
pub fn new(
window: &Window,
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> DomRoot<VideoTrackList> {
reflect_dom_object(
Box::new(VideoTrackList::new_inherited(tracks, media_element)),
window,
VideoTrackListBinding::Wrap,
)
}
pub fn len(&self) -> usize {
self.tracks.borrow().len()
}
pub fn find(&self, track: &VideoTrack) -> Option<usize> {
self.tracks.borrow().iter().position(|t| &**t == track)
}
pub fn item(&self, idx: usize) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.get(idx)
.map(|track| DomRoot::from_ref(&**track))
}
pub fn selected_index(&self) -> Option<usize> {
self.tracks
.borrow()
.iter()
.position(|track| track.selected())
}
pub fn set_selected(&self, idx: usize, value: bool) {
let track = match self.item(idx) {
Some(t) => t,
None => return,
};
// If the chosen tracks selected status is the same as the new status, return early.
if track.selected() == value {
return;
}
let global = &self.global();
let this = Trusted::new(self);
let (source, canceller) = global
.as_window()
.task_manager()
.media_element_task_source_with_canceller();
if let Some(current) = self.selected_index() {
self.tracks.borrow()[current].set_selected(false);
}
track.set_selected(value);
if let Some(media_element) = self.media_element.as_ref() {
media_element.set_video_track(idx, value);
}
let _ = source.queue_with_canceller(
task!(media_track_change: move || {
let this = this.root();
this.upcast::<EventTarget>().fire_event(atom!("change"));
}),
&canceller,
);
}
pub fn add(&self, track: &VideoTrack) {
self.tracks.borrow_mut().push(Dom::from_ref(track));
if track.selected() {
if let Some(idx) = self.selected_index() |
}
track.add_track_list(self);
}
pub fn clear(&self) {
self.tracks
.borrow()
.iter()
.for_each(|t| t.remove_track_list());
self.tracks.borrow_mut().clear();
}
}
impl VideoTrackListMethods for VideoTrackList {
// https://html.spec.whatwg.org/multipage/#dom-videotracklist-length
fn Length(&self) -> u32 {
self.len() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-tracklist-item
fn IndexedGetter(&self, idx: u32) -> Option<DomRoot<VideoTrack>> {
self.item(idx as usize)
}
// https://html.spec.whatwg.org/multipage/#dom-videotracklist-gettrackbyid
fn GetTrackById(&self, id: DOMString) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.iter()
.find(|track| track.id() == id)
.map(|track| DomRoot::from_ref(&**track))
}
// https://html.spec.whatwg.org/multipage/#dom-videotrack-selected
fn SelectedIndex(&self) -> i32 {
if let Some(idx) = self.selected_index() {
return idx as i32;
}
return -1;
}
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onchange
event_handler!(change, GetOnchange, SetOnchange);
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onaddtrack
event_handler!(addtrack, GetOnaddtrack, SetOnaddtrack);
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onremovetrack
event_handler!(removetrack, GetOnremovetrack, SetOnremovetrack);
}
| {
self.set_selected(idx, false);
} | conditional_block |
videotracklist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{self, VideoTrackListMethods};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::Dom;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::eventtarget::EventTarget;
use crate::dom::htmlmediaelement::HTMLMediaElement;
use crate::dom::videotrack::VideoTrack;
use crate::dom::window::Window;
use crate::task_source::TaskSource;
use dom_struct::dom_struct;
#[dom_struct]
pub struct VideoTrackList {
eventtarget: EventTarget,
tracks: DomRefCell<Vec<Dom<VideoTrack>>>,
media_element: Option<Dom<HTMLMediaElement>>,
}
impl VideoTrackList {
pub fn new_inherited(
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> VideoTrackList {
VideoTrackList {
eventtarget: EventTarget::new_inherited(),
tracks: DomRefCell::new(tracks.iter().map(|track| Dom::from_ref(&**track)).collect()),
media_element: media_element.map(|m| Dom::from_ref(m)),
}
}
pub fn new(
window: &Window,
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> DomRoot<VideoTrackList> {
reflect_dom_object(
Box::new(VideoTrackList::new_inherited(tracks, media_element)),
window,
VideoTrackListBinding::Wrap,
)
}
pub fn len(&self) -> usize {
self.tracks.borrow().len()
}
pub fn find(&self, track: &VideoTrack) -> Option<usize> {
self.tracks.borrow().iter().position(|t| &**t == track)
}
pub fn item(&self, idx: usize) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.get(idx)
.map(|track| DomRoot::from_ref(&**track))
}
pub fn selected_index(&self) -> Option<usize> {
self.tracks
.borrow()
.iter()
.position(|track| track.selected())
}
pub fn set_selected(&self, idx: usize, value: bool) {
let track = match self.item(idx) {
Some(t) => t,
None => return,
};
// If the chosen tracks selected status is the same as the new status, return early.
if track.selected() == value {
return;
}
let global = &self.global(); | let this = Trusted::new(self);
let (source, canceller) = global
.as_window()
.task_manager()
.media_element_task_source_with_canceller();
if let Some(current) = self.selected_index() {
self.tracks.borrow()[current].set_selected(false);
}
track.set_selected(value);
if let Some(media_element) = self.media_element.as_ref() {
media_element.set_video_track(idx, value);
}
let _ = source.queue_with_canceller(
task!(media_track_change: move || {
let this = this.root();
this.upcast::<EventTarget>().fire_event(atom!("change"));
}),
&canceller,
);
}
pub fn add(&self, track: &VideoTrack) {
self.tracks.borrow_mut().push(Dom::from_ref(track));
if track.selected() {
if let Some(idx) = self.selected_index() {
self.set_selected(idx, false);
}
}
track.add_track_list(self);
}
pub fn clear(&self) {
self.tracks
.borrow()
.iter()
.for_each(|t| t.remove_track_list());
self.tracks.borrow_mut().clear();
}
}
impl VideoTrackListMethods for VideoTrackList {
// https://html.spec.whatwg.org/multipage/#dom-videotracklist-length
fn Length(&self) -> u32 {
self.len() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-tracklist-item
fn IndexedGetter(&self, idx: u32) -> Option<DomRoot<VideoTrack>> {
self.item(idx as usize)
}
// https://html.spec.whatwg.org/multipage/#dom-videotracklist-gettrackbyid
fn GetTrackById(&self, id: DOMString) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.iter()
.find(|track| track.id() == id)
.map(|track| DomRoot::from_ref(&**track))
}
// https://html.spec.whatwg.org/multipage/#dom-videotrack-selected
fn SelectedIndex(&self) -> i32 {
if let Some(idx) = self.selected_index() {
return idx as i32;
}
return -1;
}
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onchange
event_handler!(change, GetOnchange, SetOnchange);
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onaddtrack
event_handler!(addtrack, GetOnaddtrack, SetOnaddtrack);
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onremovetrack
event_handler!(removetrack, GetOnremovetrack, SetOnremovetrack);
} | random_line_split |
|
videotracklist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{self, VideoTrackListMethods};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::Dom;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::eventtarget::EventTarget;
use crate::dom::htmlmediaelement::HTMLMediaElement;
use crate::dom::videotrack::VideoTrack;
use crate::dom::window::Window;
use crate::task_source::TaskSource;
use dom_struct::dom_struct;
#[dom_struct]
pub struct VideoTrackList {
eventtarget: EventTarget,
tracks: DomRefCell<Vec<Dom<VideoTrack>>>,
media_element: Option<Dom<HTMLMediaElement>>,
}
impl VideoTrackList {
pub fn new_inherited(
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> VideoTrackList {
VideoTrackList {
eventtarget: EventTarget::new_inherited(),
tracks: DomRefCell::new(tracks.iter().map(|track| Dom::from_ref(&**track)).collect()),
media_element: media_element.map(|m| Dom::from_ref(m)),
}
}
pub fn new(
window: &Window,
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> DomRoot<VideoTrackList> {
reflect_dom_object(
Box::new(VideoTrackList::new_inherited(tracks, media_element)),
window,
VideoTrackListBinding::Wrap,
)
}
pub fn len(&self) -> usize |
pub fn find(&self, track: &VideoTrack) -> Option<usize> {
self.tracks.borrow().iter().position(|t| &**t == track)
}
pub fn item(&self, idx: usize) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.get(idx)
.map(|track| DomRoot::from_ref(&**track))
}
pub fn selected_index(&self) -> Option<usize> {
self.tracks
.borrow()
.iter()
.position(|track| track.selected())
}
pub fn set_selected(&self, idx: usize, value: bool) {
let track = match self.item(idx) {
Some(t) => t,
None => return,
};
// If the chosen tracks selected status is the same as the new status, return early.
if track.selected() == value {
return;
}
let global = &self.global();
let this = Trusted::new(self);
let (source, canceller) = global
.as_window()
.task_manager()
.media_element_task_source_with_canceller();
if let Some(current) = self.selected_index() {
self.tracks.borrow()[current].set_selected(false);
}
track.set_selected(value);
if let Some(media_element) = self.media_element.as_ref() {
media_element.set_video_track(idx, value);
}
let _ = source.queue_with_canceller(
task!(media_track_change: move || {
let this = this.root();
this.upcast::<EventTarget>().fire_event(atom!("change"));
}),
&canceller,
);
}
pub fn add(&self, track: &VideoTrack) {
self.tracks.borrow_mut().push(Dom::from_ref(track));
if track.selected() {
if let Some(idx) = self.selected_index() {
self.set_selected(idx, false);
}
}
track.add_track_list(self);
}
pub fn clear(&self) {
self.tracks
.borrow()
.iter()
.for_each(|t| t.remove_track_list());
self.tracks.borrow_mut().clear();
}
}
impl VideoTrackListMethods for VideoTrackList {
// https://html.spec.whatwg.org/multipage/#dom-videotracklist-length
fn Length(&self) -> u32 {
self.len() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-tracklist-item
fn IndexedGetter(&self, idx: u32) -> Option<DomRoot<VideoTrack>> {
self.item(idx as usize)
}
// https://html.spec.whatwg.org/multipage/#dom-videotracklist-gettrackbyid
fn GetTrackById(&self, id: DOMString) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.iter()
.find(|track| track.id() == id)
.map(|track| DomRoot::from_ref(&**track))
}
// https://html.spec.whatwg.org/multipage/#dom-videotrack-selected
fn SelectedIndex(&self) -> i32 {
if let Some(idx) = self.selected_index() {
return idx as i32;
}
return -1;
}
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onchange
event_handler!(change, GetOnchange, SetOnchange);
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onaddtrack
event_handler!(addtrack, GetOnaddtrack, SetOnaddtrack);
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onremovetrack
event_handler!(removetrack, GetOnremovetrack, SetOnremovetrack);
}
| {
self.tracks.borrow().len()
} | identifier_body |
videotracklist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{self, VideoTrackListMethods};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::Dom;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::eventtarget::EventTarget;
use crate::dom::htmlmediaelement::HTMLMediaElement;
use crate::dom::videotrack::VideoTrack;
use crate::dom::window::Window;
use crate::task_source::TaskSource;
use dom_struct::dom_struct;
#[dom_struct]
pub struct | {
eventtarget: EventTarget,
tracks: DomRefCell<Vec<Dom<VideoTrack>>>,
media_element: Option<Dom<HTMLMediaElement>>,
}
impl VideoTrackList {
pub fn new_inherited(
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> VideoTrackList {
VideoTrackList {
eventtarget: EventTarget::new_inherited(),
tracks: DomRefCell::new(tracks.iter().map(|track| Dom::from_ref(&**track)).collect()),
media_element: media_element.map(|m| Dom::from_ref(m)),
}
}
pub fn new(
window: &Window,
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> DomRoot<VideoTrackList> {
reflect_dom_object(
Box::new(VideoTrackList::new_inherited(tracks, media_element)),
window,
VideoTrackListBinding::Wrap,
)
}
pub fn len(&self) -> usize {
self.tracks.borrow().len()
}
pub fn find(&self, track: &VideoTrack) -> Option<usize> {
self.tracks.borrow().iter().position(|t| &**t == track)
}
pub fn item(&self, idx: usize) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.get(idx)
.map(|track| DomRoot::from_ref(&**track))
}
pub fn selected_index(&self) -> Option<usize> {
self.tracks
.borrow()
.iter()
.position(|track| track.selected())
}
pub fn set_selected(&self, idx: usize, value: bool) {
let track = match self.item(idx) {
Some(t) => t,
None => return,
};
// If the chosen tracks selected status is the same as the new status, return early.
if track.selected() == value {
return;
}
let global = &self.global();
let this = Trusted::new(self);
let (source, canceller) = global
.as_window()
.task_manager()
.media_element_task_source_with_canceller();
if let Some(current) = self.selected_index() {
self.tracks.borrow()[current].set_selected(false);
}
track.set_selected(value);
if let Some(media_element) = self.media_element.as_ref() {
media_element.set_video_track(idx, value);
}
let _ = source.queue_with_canceller(
task!(media_track_change: move || {
let this = this.root();
this.upcast::<EventTarget>().fire_event(atom!("change"));
}),
&canceller,
);
}
pub fn add(&self, track: &VideoTrack) {
self.tracks.borrow_mut().push(Dom::from_ref(track));
if track.selected() {
if let Some(idx) = self.selected_index() {
self.set_selected(idx, false);
}
}
track.add_track_list(self);
}
pub fn clear(&self) {
self.tracks
.borrow()
.iter()
.for_each(|t| t.remove_track_list());
self.tracks.borrow_mut().clear();
}
}
impl VideoTrackListMethods for VideoTrackList {
// https://html.spec.whatwg.org/multipage/#dom-videotracklist-length
fn Length(&self) -> u32 {
self.len() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-tracklist-item
fn IndexedGetter(&self, idx: u32) -> Option<DomRoot<VideoTrack>> {
self.item(idx as usize)
}
// https://html.spec.whatwg.org/multipage/#dom-videotracklist-gettrackbyid
fn GetTrackById(&self, id: DOMString) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.iter()
.find(|track| track.id() == id)
.map(|track| DomRoot::from_ref(&**track))
}
// https://html.spec.whatwg.org/multipage/#dom-videotrack-selected
fn SelectedIndex(&self) -> i32 {
if let Some(idx) = self.selected_index() {
return idx as i32;
}
return -1;
}
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onchange
event_handler!(change, GetOnchange, SetOnchange);
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onaddtrack
event_handler!(addtrack, GetOnaddtrack, SetOnaddtrack);
// https://html.spec.whatwg.org/multipage/#handler-tracklist-onremovetrack
event_handler!(removetrack, GetOnremovetrack, SetOnremovetrack);
}
| VideoTrackList | identifier_name |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc;
pub mod ffi;
pub mod initiator;
pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registers an NFC device driver with libnfc
pub fn register_driver(ndr: *const ffi::nfc_driver) -> i32 {
unsafe { ffi::nfc_register_driver(ndr) }
}
/// Initializes libnfc. This function must be called before calling any other libnfc function
pub fn init(context: *mut *mut ffi::nfc_context) {
unsafe { ffi::nfc_init(context); }
}
/// Deinitializes libnfc. Should be called after closing all open devices and before your application terminates
pub fn exit(context: *mut ffi::nfc_context) {
unsafe { ffi::nfc_exit(context); }
}
// NFC Device/Hardware manipulation
// http://www.libnfc.org/api/group__dev.html
/// Open an NFC device
pub fn open(context: *mut ffi::nfc_context, connstring: *const ffi::nfc_connstring) -> *mut ffi::nfc_device {
unsafe { ffi::nfc_open(context, connstring) }
}
/// Close from a NFC device
pub fn close(pnd: *mut ffi::nfc_device) |
/// Scan for discoverable supported devices
pub fn list_devices(context: *mut ffi::nfc_context, connstrings: *mut ffi::nfc_connstring, constrings_len: size_t) -> size_t {
unsafe { ffi::nfc_list_devices(context, connstrings, constrings_len) }
}
/// Switches the NFC device to idle mode
pub fn idle(pnd: *mut ffi::nfc_device) -> i32 {
unsafe { ffi::nfc_idle(pnd) }
}
/// Aborts current running command
pub fn abort_command(pnd: *mut ffi::nfc_device) -> i32 {
unsafe { ffi::nfc_abort_command(pnd) }
}
| {
unsafe { ffi::nfc_close(pnd); }
} | identifier_body |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc; | pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registers an NFC device driver with libnfc
pub fn register_driver(ndr: *const ffi::nfc_driver) -> i32 {
unsafe { ffi::nfc_register_driver(ndr) }
}
/// Initializes libnfc. This function must be called before calling any other libnfc function
pub fn init(context: *mut *mut ffi::nfc_context) {
unsafe { ffi::nfc_init(context); }
}
/// Deinitializes libnfc. Should be called after closing all open devices and before your application terminates
pub fn exit(context: *mut ffi::nfc_context) {
unsafe { ffi::nfc_exit(context); }
}
// NFC Device/Hardware manipulation
// http://www.libnfc.org/api/group__dev.html
/// Open an NFC device
pub fn open(context: *mut ffi::nfc_context, connstring: *const ffi::nfc_connstring) -> *mut ffi::nfc_device {
unsafe { ffi::nfc_open(context, connstring) }
}
/// Close from a NFC device
pub fn close(pnd: *mut ffi::nfc_device) {
unsafe { ffi::nfc_close(pnd); }
}
/// Scan for discoverable supported devices
pub fn list_devices(context: *mut ffi::nfc_context, connstrings: *mut ffi::nfc_connstring, constrings_len: size_t) -> size_t {
unsafe { ffi::nfc_list_devices(context, connstrings, constrings_len) }
}
/// Switches the NFC device to idle mode
pub fn idle(pnd: *mut ffi::nfc_device) -> i32 {
unsafe { ffi::nfc_idle(pnd) }
}
/// Aborts current running command
pub fn abort_command(pnd: *mut ffi::nfc_device) -> i32 {
unsafe { ffi::nfc_abort_command(pnd) }
} |
pub mod ffi;
pub mod initiator; | random_line_split |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc;
pub mod ffi;
pub mod initiator;
pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registers an NFC device driver with libnfc
pub fn | (ndr: *const ffi::nfc_driver) -> i32 {
unsafe { ffi::nfc_register_driver(ndr) }
}
/// Initializes libnfc. This function must be called before calling any other libnfc function
pub fn init(context: *mut *mut ffi::nfc_context) {
unsafe { ffi::nfc_init(context); }
}
/// Deinitializes libnfc. Should be called after closing all open devices and before your application terminates
pub fn exit(context: *mut ffi::nfc_context) {
unsafe { ffi::nfc_exit(context); }
}
// NFC Device/Hardware manipulation
// http://www.libnfc.org/api/group__dev.html
/// Open an NFC device
pub fn open(context: *mut ffi::nfc_context, connstring: *const ffi::nfc_connstring) -> *mut ffi::nfc_device {
unsafe { ffi::nfc_open(context, connstring) }
}
/// Close from a NFC device
pub fn close(pnd: *mut ffi::nfc_device) {
unsafe { ffi::nfc_close(pnd); }
}
/// Scan for discoverable supported devices
pub fn list_devices(context: *mut ffi::nfc_context, connstrings: *mut ffi::nfc_connstring, constrings_len: size_t) -> size_t {
unsafe { ffi::nfc_list_devices(context, connstrings, constrings_len) }
}
/// Switches the NFC device to idle mode
pub fn idle(pnd: *mut ffi::nfc_device) -> i32 {
unsafe { ffi::nfc_idle(pnd) }
}
/// Aborts current running command
pub fn abort_command(pnd: *mut ffi::nfc_device) -> i32 {
unsafe { ffi::nfc_abort_command(pnd) }
}
| register_driver | identifier_name |
rastrigin.rs | // Copyright 2016 Martin Ankerl.
//
// 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.
extern crate differential_evolution;
use differential_evolution::self_adaptive_de;
use std::f32::consts::PI;
use std::env;
// The Rastrigin function is a non-convex function used as a
// performance test problem for optimization algorithms.
// see https://en.wikipedia.org/wiki/Rastrigin_function
fn rastrigin(pos: &[f32]) -> f32 {
pos.iter().fold(0.0, |sum, x|
sum + x * x - 10.0 * (2.0 * PI * x).cos() + 10.0)
}
fn main() | println!("{:?} best position", pos);
} | {
// command line args: dimension, number of evaluations
let args: Vec<String> = env::args().collect();
let dim = args[1].parse::<usize>().unwrap();
// initial search space for each dimension
let initial_min_max = vec![(-5.12, 5.12); dim];
// initialize differential evolution
let mut de = self_adaptive_de(initial_min_max, rastrigin);
// perform optimization for a maximum of 100000 cost evaluations,
// or until best cost is below 0.1.
de.iter().take(100000).find(|&cost| cost < 0.1);
// see what we've found
println!("{} evaluations done", de.num_cost_evaluations());
let (cost, pos) = de.best().unwrap();
println!("{} best cost", cost); | identifier_body |
rastrigin.rs | // Copyright 2016 Martin Ankerl.
//
// 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.
extern crate differential_evolution;
use differential_evolution::self_adaptive_de;
use std::f32::consts::PI;
use std::env;
// The Rastrigin function is a non-convex function used as a
// performance test problem for optimization algorithms.
// see https://en.wikipedia.org/wiki/Rastrigin_function
fn | (pos: &[f32]) -> f32 {
pos.iter().fold(0.0, |sum, x|
sum + x * x - 10.0 * (2.0 * PI * x).cos() + 10.0)
}
fn main() {
// command line args: dimension, number of evaluations
let args: Vec<String> = env::args().collect();
let dim = args[1].parse::<usize>().unwrap();
// initial search space for each dimension
let initial_min_max = vec![(-5.12, 5.12); dim];
// initialize differential evolution
let mut de = self_adaptive_de(initial_min_max, rastrigin);
// perform optimization for a maximum of 100000 cost evaluations,
// or until best cost is below 0.1.
de.iter().take(100000).find(|&cost| cost < 0.1);
// see what we've found
println!("{} evaluations done", de.num_cost_evaluations());
let (cost, pos) = de.best().unwrap();
println!("{} best cost", cost);
println!("{:?} best position", pos);
} | rastrigin | identifier_name |
rastrigin.rs | // Copyright 2016 Martin Ankerl.
// | // 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.
extern crate differential_evolution;
use differential_evolution::self_adaptive_de;
use std::f32::consts::PI;
use std::env;
// The Rastrigin function is a non-convex function used as a
// performance test problem for optimization algorithms.
// see https://en.wikipedia.org/wiki/Rastrigin_function
fn rastrigin(pos: &[f32]) -> f32 {
pos.iter().fold(0.0, |sum, x|
sum + x * x - 10.0 * (2.0 * PI * x).cos() + 10.0)
}
fn main() {
// command line args: dimension, number of evaluations
let args: Vec<String> = env::args().collect();
let dim = args[1].parse::<usize>().unwrap();
// initial search space for each dimension
let initial_min_max = vec![(-5.12, 5.12); dim];
// initialize differential evolution
let mut de = self_adaptive_de(initial_min_max, rastrigin);
// perform optimization for a maximum of 100000 cost evaluations,
// or until best cost is below 0.1.
de.iter().take(100000).find(|&cost| cost < 0.1);
// see what we've found
println!("{} evaluations done", de.num_cost_evaluations());
let (cost, pos) = de.best().unwrap();
println!("{} best cost", cost);
println!("{:?} best position", pos);
} | random_line_split |
|
broken.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use capnp::{any_pointer};
use capnp::Error;
use capnp::private::capability::{ClientHook, ParamsHook, PipelineHook, PipelineOp,
RequestHook, ResultsHook};
use capnp::capability::{Promise, RemotePromise};
use std::rc::{Rc};
pub struct Pipeline {
error: Error,
}
impl Pipeline {
pub fn new(error: Error) -> Pipeline {
Pipeline {
error: error
}
}
}
impl PipelineHook for Pipeline {
fn add_ref(&self) -> Box<dyn PipelineHook> {
Box::new(Pipeline::new(self.error.clone()))
}
fn get_pipelined_cap(&self, _ops: &[PipelineOp]) -> Box<dyn ClientHook> {
new_cap(self.error.clone())
}
}
pub struct | {
error: Error,
message: ::capnp::message::Builder<::capnp::message::HeapAllocator>,
}
impl Request {
pub fn new(error: Error, _size_hint: Option<::capnp::MessageSize>) -> Request {
Request {
error: error,
message: ::capnp::message::Builder::new_default(),
}
}
}
impl RequestHook for Request {
fn get<'a>(&'a mut self) -> any_pointer::Builder<'a> {
self.message.get_root().unwrap()
}
fn get_brand(&self) -> usize {
0
}
fn send<'a>(self: Box<Self>) -> RemotePromise<any_pointer::Owned> {
let pipeline = Pipeline::new(self.error.clone());
RemotePromise {
promise: Promise::err(self.error),
pipeline: any_pointer::Pipeline::new(Box::new(pipeline)),
}
}
fn tail_send(self: Box<Self>)
-> Option<(u32, Promise<(), Error>, Box<dyn PipelineHook>)>
{
None
}
}
struct ClientInner {
error: Error,
_resolved: bool,
brand: usize,
}
pub struct Client {
inner: Rc<ClientInner>,
}
impl Client {
pub fn new(error: Error, resolved: bool, brand: usize) -> Client {
Client {
inner: Rc::new(ClientInner {
error: error,
_resolved: resolved,
brand: brand,
}),
}
}
}
impl ClientHook for Client {
fn add_ref(&self) -> Box<dyn ClientHook> {
Box::new(Client { inner: self.inner.clone() } )
}
fn new_call(&self, _interface_id: u64, _method_id: u16,
size_hint: Option<::capnp::MessageSize>)
-> ::capnp::capability::Request<any_pointer::Owned, any_pointer::Owned>
{
::capnp::capability::Request::new(
Box::new(Request::new(self.inner.error.clone(), size_hint)))
}
fn call(&self, _interface_id: u64, _method_id: u16, _params: Box<dyn ParamsHook>, _results: Box<dyn ResultsHook>)
-> Promise<(), Error>
{
Promise::err(self.inner.error.clone())
}
fn get_ptr(&self) -> usize {
(self.inner.as_ref()) as * const _ as usize
}
fn get_brand(&self) -> usize {
self.inner.brand
}
fn get_resolved(&self) -> Option<Box<dyn ClientHook>> {
None
}
fn when_more_resolved(&self) -> Option<Promise<Box<dyn ClientHook>, Error>> {
None
}
}
pub fn new_cap(exception: Error) -> Box<dyn ClientHook> {
Box::new(Client::new(exception, false, 0))
}
| Request | identifier_name |
broken.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use capnp::{any_pointer};
use capnp::Error;
use capnp::private::capability::{ClientHook, ParamsHook, PipelineHook, PipelineOp,
RequestHook, ResultsHook};
use capnp::capability::{Promise, RemotePromise};
use std::rc::{Rc};
pub struct Pipeline {
error: Error,
}
impl Pipeline {
pub fn new(error: Error) -> Pipeline {
Pipeline {
error: error
}
}
}
impl PipelineHook for Pipeline {
fn add_ref(&self) -> Box<dyn PipelineHook> {
Box::new(Pipeline::new(self.error.clone()))
}
fn get_pipelined_cap(&self, _ops: &[PipelineOp]) -> Box<dyn ClientHook> {
new_cap(self.error.clone())
}
}
pub struct Request {
error: Error,
message: ::capnp::message::Builder<::capnp::message::HeapAllocator>,
}
impl Request {
pub fn new(error: Error, _size_hint: Option<::capnp::MessageSize>) -> Request {
Request {
error: error, | }
}
}
impl RequestHook for Request {
fn get<'a>(&'a mut self) -> any_pointer::Builder<'a> {
self.message.get_root().unwrap()
}
fn get_brand(&self) -> usize {
0
}
fn send<'a>(self: Box<Self>) -> RemotePromise<any_pointer::Owned> {
let pipeline = Pipeline::new(self.error.clone());
RemotePromise {
promise: Promise::err(self.error),
pipeline: any_pointer::Pipeline::new(Box::new(pipeline)),
}
}
fn tail_send(self: Box<Self>)
-> Option<(u32, Promise<(), Error>, Box<dyn PipelineHook>)>
{
None
}
}
struct ClientInner {
error: Error,
_resolved: bool,
brand: usize,
}
pub struct Client {
inner: Rc<ClientInner>,
}
impl Client {
pub fn new(error: Error, resolved: bool, brand: usize) -> Client {
Client {
inner: Rc::new(ClientInner {
error: error,
_resolved: resolved,
brand: brand,
}),
}
}
}
impl ClientHook for Client {
fn add_ref(&self) -> Box<dyn ClientHook> {
Box::new(Client { inner: self.inner.clone() } )
}
fn new_call(&self, _interface_id: u64, _method_id: u16,
size_hint: Option<::capnp::MessageSize>)
-> ::capnp::capability::Request<any_pointer::Owned, any_pointer::Owned>
{
::capnp::capability::Request::new(
Box::new(Request::new(self.inner.error.clone(), size_hint)))
}
fn call(&self, _interface_id: u64, _method_id: u16, _params: Box<dyn ParamsHook>, _results: Box<dyn ResultsHook>)
-> Promise<(), Error>
{
Promise::err(self.inner.error.clone())
}
fn get_ptr(&self) -> usize {
(self.inner.as_ref()) as * const _ as usize
}
fn get_brand(&self) -> usize {
self.inner.brand
}
fn get_resolved(&self) -> Option<Box<dyn ClientHook>> {
None
}
fn when_more_resolved(&self) -> Option<Promise<Box<dyn ClientHook>, Error>> {
None
}
}
pub fn new_cap(exception: Error) -> Box<dyn ClientHook> {
Box::new(Client::new(exception, false, 0))
} | message: ::capnp::message::Builder::new_default(), | random_line_split |
autoderef-method-priority.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait double {
fn double(self) -> uint;
}
impl double for uint {
fn double(self) -> uint { self }
}
impl double for Box<uint> {
fn | (self) -> uint { *self * 2u }
}
pub fn main() {
let x = box 3u;
assert_eq!(x.double(), 6u);
}
| double | identifier_name |
autoderef-method-priority.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait double {
fn double(self) -> uint;
}
impl double for uint {
fn double(self) -> uint { self }
}
impl double for Box<uint> {
fn double(self) -> uint { *self * 2u }
}
pub fn main() {
let x = box 3u;
assert_eq!(x.double(), 6u); | } | random_line_split |
|
autoderef-method-priority.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait double {
fn double(self) -> uint;
}
impl double for uint {
fn double(self) -> uint { self }
}
impl double for Box<uint> {
fn double(self) -> uint |
}
pub fn main() {
let x = box 3u;
assert_eq!(x.double(), 6u);
}
| { *self * 2u } | identifier_body |
simd-binop.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.
// ignore-tidy-linelength
#![allow(experimental)]
use std::unstable::simd::f32x4;
fn main() {
let _ = f32x4(0.0, 0.0, 0.0, 0.0) == f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `==` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0)!= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `!=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) < f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `<` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) <= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `<=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) >= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `>=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) > f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `>` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
} | random_line_split |
|
simd-binop.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.
// ignore-tidy-linelength
#![allow(experimental)]
use std::unstable::simd::f32x4;
fn | () {
let _ = f32x4(0.0, 0.0, 0.0, 0.0) == f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `==` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0)!= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `!=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) < f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `<` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) <= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `<=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) >= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `>=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) > f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `>` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
}
| main | identifier_name |
simd-binop.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.
// ignore-tidy-linelength
#![allow(experimental)]
use std::unstable::simd::f32x4;
fn main() | }
| {
let _ = f32x4(0.0, 0.0, 0.0, 0.0) == f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `==` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) != f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `!=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) < f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `<` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) <= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `<=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) >= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `>=` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) > f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `>` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
| identifier_body |
socks4.rs | //! Socks4a Protocol Definition
//!
//! <http://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol>
#![allow(dead_code)]
use std::{
fmt,
io::{self, ErrorKind},
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
};
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use thiserror::Error;
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use shadowsocks::relay::socks5;
#[rustfmt::skip]
mod consts {
pub const SOCKS4_VERSION: u8 = 4;
pub const SOCKS4_COMMAND_CONNECT: u8 = 1;
pub const SOCKS4_COMMAND_BIND: u8 = 2;
pub const SOCKS4_RESULT_REQUEST_GRANTED: u8 = 90;
pub const SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED: u8 = 91;
pub const SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT: u8 = 92;
pub const SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID: u8 = 93;
}
/// SOCKS4 Command
#[derive(Clone, Debug, Copy)]
pub enum Command {
/// CONNECT command
Connect,
/// BIND command
Bind,
}
impl Command {
#[inline]
fn as_u8(self) -> u8 {
match self {
Command::Connect => consts::SOCKS4_COMMAND_CONNECT,
Command::Bind => consts::SOCKS4_COMMAND_BIND,
}
}
#[inline]
fn from_u8(code: u8) -> Option<Command> {
match code {
consts::SOCKS4_COMMAND_CONNECT => Some(Command::Connect),
consts::SOCKS4_COMMAND_BIND => Some(Command::Bind),
_ => None,
}
}
}
/// SOCKS4 Result Code
#[derive(Clone, Debug, Copy, Eq, PartialEq)]
pub enum ResultCode {
/// 90: request granted
RequestGranted,
/// 91: request rejected or failed
RequestRejectedOrFailed,
/// 92: request rejected because SOCKS server cannot connect to identd on the client
RequestRejectedCannotConnect,
/// 93: request rejected because the client program and identd report different user-ids
RequestRejectedDifferentUserId,
/// Other replies
Other(u8),
}
impl ResultCode {
#[inline]
fn as_u8(self) -> u8 {
match self {
ResultCode::RequestGranted => consts::SOCKS4_RESULT_REQUEST_GRANTED,
ResultCode::RequestRejectedOrFailed => consts::SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED,
ResultCode::RequestRejectedCannotConnect => consts::SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT,
ResultCode::RequestRejectedDifferentUserId => consts::SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID,
ResultCode::Other(c) => c,
}
}
#[inline]
fn from_u8(code: u8) -> ResultCode {
match code {
consts::SOCKS4_RESULT_REQUEST_GRANTED => ResultCode::RequestGranted,
consts::SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED => ResultCode::RequestRejectedOrFailed,
consts::SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT => ResultCode::RequestRejectedCannotConnect,
consts::SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID => ResultCode::RequestRejectedDifferentUserId,
code => ResultCode::Other(code),
}
}
}
impl fmt::Display for ResultCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ResultCode::RequestGranted => f.write_str("request granted"),
ResultCode::RequestRejectedOrFailed => f.write_str("request rejected or failed"),
ResultCode::RequestRejectedCannotConnect => {
f.write_str("request rejected because SOCKS server cannot connect to identd on the client")
}
ResultCode::RequestRejectedDifferentUserId => {
f.write_str("request rejected because the client program and identd report different user-ids")
}
ResultCode::Other(code) => write!(f, "other result code {}", code),
}
}
}
/// SOCKS4 Address type
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum Address {
/// Socket address (IP Address)
SocketAddress(SocketAddrV4),
/// Domain name address (SOCKS4a)
DomainNameAddress(String, u16),
}
impl fmt::Debug for Address {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Address::SocketAddress(ref addr) => write!(f, "{}", addr),
Address::DomainNameAddress(ref addr, ref port) => write!(f, "{}:{}", addr, port),
}
}
}
impl fmt::Display for Address {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Address::SocketAddress(ref addr) => write!(f, "{}", addr),
Address::DomainNameAddress(ref addr, ref port) => write!(f, "{}:{}", addr, port),
}
}
}
impl From<SocketAddrV4> for Address {
fn from(s: SocketAddrV4) -> Address {
Address::SocketAddress(s)
}
}
impl From<(String, u16)> for Address {
fn from((dn, port): (String, u16)) -> Address {
Address::DomainNameAddress(dn, port)
}
}
impl From<(&str, u16)> for Address {
fn from((dn, port): (&str, u16)) -> Address {
Address::DomainNameAddress(dn.to_owned(), port)
}
}
impl From<&Address> for Address {
fn from(addr: &Address) -> Address {
addr.clone()
}
}
impl From<Address> for socks5::Address {
fn from(addr: Address) -> socks5::Address {
match addr {
Address::SocketAddress(a) => socks5::Address::SocketAddress(SocketAddr::V4(a)),
Address::DomainNameAddress(d, p) => socks5::Address::DomainNameAddress(d, p),
}
}
}
/// Handshake Request
///
/// ```plain
/// The client connects to the SOCKS server and sends a CONNECT/BIND request when
/// it wants to establish a connection to an application server. The client
/// includes in the request packet the IP address and the port number of the
/// destination host, and userid, in the following format.
///
/// +----+----+----+----+----+----+----+----+----+----+....+----+
/// | VN | CD | DSTPORT | DSTIP | USERID |NULL|
/// +----+----+----+----+----+----+----+----+----+----+....+----+
/// # of bytes: 1 1 2 4 variable 1
///
/// VN is the SOCKS protocol version number and should be 4. CD is the
/// SOCKS command code and should be 1 for CONNECT request, 2 for BIND request. NULL is a byte
/// of all zero bits.
/// ```
#[derive(Debug, Clone)]
pub struct HandshakeRequest {
pub cd: Command,
pub dst: Address,
pub user_id: Vec<u8>,
}
impl HandshakeRequest {
/// Read from a reader
pub async fn read_from<R>(r: &mut R) -> Result<HandshakeRequest, Error>
where
R: AsyncBufRead + Unpin,
{
let mut buf = [0u8; 8];
let _ = r.read_exact(&mut buf).await?;
let vn = buf[0];
if vn!= consts::SOCKS4_VERSION {
return Err(Error::UnsupportedSocksVersion(vn));
}
let cd = buf[1];
let command = match Command::from_u8(cd) {
Some(c) => c,
None => {
return Err(Error::UnsupportedSocksVersion(cd));
}
};
let port = BigEndian::read_u16(&buf[2..4]);
let mut user_id = Vec::new();
let _ = r.read_until(b'\0', &mut user_id).await?;
if user_id.is_empty() || user_id.last()!= Some(&b'\0') {
return Err(io::Error::from(ErrorKind::UnexpectedEof).into());
}
user_id.pop(); // Pops the last b'\0'
let dst = if buf[4] == 0x00 && buf[5] == 0x00 && buf[6] == 0x00 && buf[7]!= 0x00 {
// SOCKS4a, indicates that it is a HOST address
let mut host = Vec::new();
let _ = r.read_until(b'\0', &mut host).await?;
if host.is_empty() || host.last()!= Some(&b'\0') {
return Err(io::Error::from(ErrorKind::UnexpectedEof).into());
}
host.pop(); // Pops the last b'\0'
match String::from_utf8(host) {
Ok(host) => Address::DomainNameAddress(host, port),
Err(..) => {
return Err(Error::AddressHostInvalidEncoding);
}
}
} else {
let ip = Ipv4Addr::new(buf[4], buf[5], buf[6], buf[7]);
Address::SocketAddress(SocketAddrV4::new(ip, port))
};
Ok(HandshakeRequest {
cd: command,
dst,
user_id,
})
}
/// Writes to writer
pub async fn write_to<W>(&self, w: &mut W) -> io::Result<()>
where
W: AsyncWrite + Unpin,
{
let mut buf = BytesMut::with_capacity(self.serialized_len());
self.write_to_buf(&mut buf);
w.write_all(&buf).await
}
/// Writes to buffer
pub fn write_to_buf<B: BufMut>(&self, buf: &mut B) {
debug_assert!(
!self.user_id.contains(&b'\0'),
"USERID shouldn't contain any NULL characters"
);
buf.put_u8(consts::SOCKS4_VERSION);
buf.put_u8(self.cd.as_u8());
match self.dst {
Address::SocketAddress(ref saddr) => {
let port = saddr.port();
buf.put_u16(port);
buf.put_slice(&saddr.ip().octets());
buf.put_slice(&self.user_id);
buf.put_u8(b'\0');
}
Address::DomainNameAddress(ref dname, port) => {
buf.put_u16(port);
// 0.0.0.x (x!= 0)
const PLACEHOLDER: [u8; 4] = [0x00, 0x00, 0x00, 0xff];
buf.put_slice(&PLACEHOLDER);
buf.put_slice(&self.user_id);
buf.put_u8(b'\0');
buf.put_slice(dname.as_bytes());
buf.put_u8(b'\0');
}
}
}
/// Length in bytes
#[inline]
pub fn | (&self) -> usize {
let mut s = 1 + 1 + 2 + 4 + self.user_id.len() + 1; // USERID.LEN + NULL
if let Address::DomainNameAddress(ref dname, _) = self.dst {
s += dname.len() + 1;
}
s
}
}
/// Handshake Response
///
/// ```plain
/// +----+----+----+----+----+----+----+----+
/// | VN | CD | DSTPORT | DSTIP |
/// +----+----+----+----+----+----+----+----+
/// # of bytes: 1 1 2 4
/// ```
#[derive(Debug, Clone)]
pub struct HandshakeResponse {
pub cd: ResultCode,
}
impl HandshakeResponse {
/// Create a response with code
pub fn new(code: ResultCode) -> HandshakeResponse {
HandshakeResponse { cd: code }
}
/// Read from a reader
pub async fn read_from<R>(r: &mut R) -> Result<HandshakeResponse, Error>
where
R: AsyncRead + Unpin,
{
let mut buf = [0u8; 8];
let _ = r.read_exact(&mut buf).await?;
let vn = buf[0];
if vn!= 0 {
return Err(Error::UnsupportedSocksVersion(vn));
}
let cd = buf[1];
let result_code = ResultCode::from_u8(cd);
// DSTPORT, DSTIP are ignored
Ok(HandshakeResponse { cd: result_code })
}
/// Write data into a writer
pub async fn write_to<W>(&self, w: &mut W) -> io::Result<()>
where
W: AsyncWrite + Unpin,
{
let mut buf = BytesMut::with_capacity(self.serialized_len());
self.write_to_buf(&mut buf);
w.write_all(&buf).await
}
/// Writes to buffer
pub fn write_to_buf<B: BufMut>(&self, buf: &mut B) {
let HandshakeResponse { ref cd } = *self;
buf.put_slice(&[
// VN: Result Code's version, must be 0
0x00,
// CD: Result Code
cd.as_u8(),
// DSTPORT: Ignored
0x00,
0x00,
// DSTIP: Ignored
0x00,
0x00,
0x00,
0x00,
]);
}
/// Length in bytes
#[inline]
pub fn serialized_len(&self) -> usize {
1 + 1 + 2 + 4
}
}
/// SOCKS 4/4a Error
#[derive(Error, Debug)]
pub enum Error {
// I/O Error
#[error("{0}")]
IoError(#[from] io::Error),
#[error("host must be UTF-8 encoding")]
AddressHostInvalidEncoding,
#[error("unsupported socks version {0:#x}")]
UnsupportedSocksVersion(u8),
#[error("unsupported command {0:#x}")]
UnsupportedCommand(u8),
#[error("{0}")]
Result(ResultCode),
}
impl From<Error> for io::Error {
fn from(err: Error) -> io::Error {
match err {
Error::IoError(err) => err,
e => io::Error::new(ErrorKind::Other, e),
}
}
}
| serialized_len | identifier_name |
socks4.rs | //! Socks4a Protocol Definition
//!
//! <http://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol>
#![allow(dead_code)]
use std::{
fmt,
io::{self, ErrorKind},
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
};
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use thiserror::Error;
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use shadowsocks::relay::socks5;
#[rustfmt::skip]
mod consts {
pub const SOCKS4_VERSION: u8 = 4;
pub const SOCKS4_COMMAND_CONNECT: u8 = 1;
pub const SOCKS4_COMMAND_BIND: u8 = 2;
pub const SOCKS4_RESULT_REQUEST_GRANTED: u8 = 90;
pub const SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED: u8 = 91;
pub const SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT: u8 = 92;
pub const SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID: u8 = 93;
}
/// SOCKS4 Command
#[derive(Clone, Debug, Copy)]
pub enum Command {
/// CONNECT command
Connect,
/// BIND command
Bind,
}
impl Command {
#[inline]
fn as_u8(self) -> u8 {
match self {
Command::Connect => consts::SOCKS4_COMMAND_CONNECT,
Command::Bind => consts::SOCKS4_COMMAND_BIND,
}
}
#[inline]
fn from_u8(code: u8) -> Option<Command> {
match code {
consts::SOCKS4_COMMAND_CONNECT => Some(Command::Connect),
consts::SOCKS4_COMMAND_BIND => Some(Command::Bind),
_ => None,
}
}
}
/// SOCKS4 Result Code
#[derive(Clone, Debug, Copy, Eq, PartialEq)]
pub enum ResultCode {
/// 90: request granted
RequestGranted,
/// 91: request rejected or failed
RequestRejectedOrFailed,
/// 92: request rejected because SOCKS server cannot connect to identd on the client
RequestRejectedCannotConnect,
/// 93: request rejected because the client program and identd report different user-ids
RequestRejectedDifferentUserId,
/// Other replies
Other(u8),
}
impl ResultCode {
#[inline]
fn as_u8(self) -> u8 {
match self {
ResultCode::RequestGranted => consts::SOCKS4_RESULT_REQUEST_GRANTED,
ResultCode::RequestRejectedOrFailed => consts::SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED,
ResultCode::RequestRejectedCannotConnect => consts::SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT,
ResultCode::RequestRejectedDifferentUserId => consts::SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID,
ResultCode::Other(c) => c,
}
}
#[inline]
fn from_u8(code: u8) -> ResultCode {
match code {
consts::SOCKS4_RESULT_REQUEST_GRANTED => ResultCode::RequestGranted,
consts::SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED => ResultCode::RequestRejectedOrFailed,
consts::SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT => ResultCode::RequestRejectedCannotConnect,
consts::SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID => ResultCode::RequestRejectedDifferentUserId,
code => ResultCode::Other(code),
}
}
}
impl fmt::Display for ResultCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ResultCode::RequestGranted => f.write_str("request granted"),
ResultCode::RequestRejectedOrFailed => f.write_str("request rejected or failed"),
ResultCode::RequestRejectedCannotConnect => {
f.write_str("request rejected because SOCKS server cannot connect to identd on the client")
}
ResultCode::RequestRejectedDifferentUserId => {
f.write_str("request rejected because the client program and identd report different user-ids")
}
ResultCode::Other(code) => write!(f, "other result code {}", code),
}
}
}
/// SOCKS4 Address type
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum Address {
/// Socket address (IP Address)
SocketAddress(SocketAddrV4),
/// Domain name address (SOCKS4a)
DomainNameAddress(String, u16),
}
impl fmt::Debug for Address {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Address::SocketAddress(ref addr) => write!(f, "{}", addr),
Address::DomainNameAddress(ref addr, ref port) => write!(f, "{}:{}", addr, port),
}
}
}
impl fmt::Display for Address {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Address::SocketAddress(ref addr) => write!(f, "{}", addr),
Address::DomainNameAddress(ref addr, ref port) => write!(f, "{}:{}", addr, port),
}
}
}
impl From<SocketAddrV4> for Address {
fn from(s: SocketAddrV4) -> Address {
Address::SocketAddress(s)
}
}
impl From<(String, u16)> for Address {
fn from((dn, port): (String, u16)) -> Address {
Address::DomainNameAddress(dn, port)
}
}
impl From<(&str, u16)> for Address {
fn from((dn, port): (&str, u16)) -> Address {
Address::DomainNameAddress(dn.to_owned(), port)
}
}
impl From<&Address> for Address {
fn from(addr: &Address) -> Address {
addr.clone()
}
}
impl From<Address> for socks5::Address {
fn from(addr: Address) -> socks5::Address {
match addr {
Address::SocketAddress(a) => socks5::Address::SocketAddress(SocketAddr::V4(a)),
Address::DomainNameAddress(d, p) => socks5::Address::DomainNameAddress(d, p),
}
}
}
/// Handshake Request
///
/// ```plain
/// The client connects to the SOCKS server and sends a CONNECT/BIND request when
/// it wants to establish a connection to an application server. The client
/// includes in the request packet the IP address and the port number of the
/// destination host, and userid, in the following format.
///
/// +----+----+----+----+----+----+----+----+----+----+....+----+
/// | VN | CD | DSTPORT | DSTIP | USERID |NULL|
/// +----+----+----+----+----+----+----+----+----+----+....+----+
/// # of bytes: 1 1 2 4 variable 1
///
/// VN is the SOCKS protocol version number and should be 4. CD is the
/// SOCKS command code and should be 1 for CONNECT request, 2 for BIND request. NULL is a byte
/// of all zero bits.
/// ```
#[derive(Debug, Clone)]
pub struct HandshakeRequest {
pub cd: Command,
pub dst: Address,
pub user_id: Vec<u8>,
}
impl HandshakeRequest {
/// Read from a reader
pub async fn read_from<R>(r: &mut R) -> Result<HandshakeRequest, Error>
where
R: AsyncBufRead + Unpin,
{
let mut buf = [0u8; 8];
let _ = r.read_exact(&mut buf).await?;
let vn = buf[0];
if vn!= consts::SOCKS4_VERSION {
return Err(Error::UnsupportedSocksVersion(vn));
}
let cd = buf[1];
let command = match Command::from_u8(cd) {
Some(c) => c,
None => {
return Err(Error::UnsupportedSocksVersion(cd));
}
};
let port = BigEndian::read_u16(&buf[2..4]);
let mut user_id = Vec::new();
let _ = r.read_until(b'\0', &mut user_id).await?;
if user_id.is_empty() || user_id.last()!= Some(&b'\0') {
return Err(io::Error::from(ErrorKind::UnexpectedEof).into());
}
user_id.pop(); // Pops the last b'\0'
let dst = if buf[4] == 0x00 && buf[5] == 0x00 && buf[6] == 0x00 && buf[7]!= 0x00 {
// SOCKS4a, indicates that it is a HOST address
let mut host = Vec::new();
let _ = r.read_until(b'\0', &mut host).await?;
if host.is_empty() || host.last()!= Some(&b'\0') {
return Err(io::Error::from(ErrorKind::UnexpectedEof).into());
}
host.pop(); // Pops the last b'\0'
match String::from_utf8(host) {
Ok(host) => Address::DomainNameAddress(host, port),
Err(..) => {
return Err(Error::AddressHostInvalidEncoding);
}
}
} else {
let ip = Ipv4Addr::new(buf[4], buf[5], buf[6], buf[7]);
Address::SocketAddress(SocketAddrV4::new(ip, port))
};
Ok(HandshakeRequest {
cd: command,
dst,
user_id,
})
}
/// Writes to writer
pub async fn write_to<W>(&self, w: &mut W) -> io::Result<()>
where
W: AsyncWrite + Unpin,
{
let mut buf = BytesMut::with_capacity(self.serialized_len());
self.write_to_buf(&mut buf);
w.write_all(&buf).await
}
/// Writes to buffer
pub fn write_to_buf<B: BufMut>(&self, buf: &mut B) {
debug_assert!(
!self.user_id.contains(&b'\0'),
"USERID shouldn't contain any NULL characters"
);
buf.put_u8(consts::SOCKS4_VERSION);
buf.put_u8(self.cd.as_u8());
match self.dst {
Address::SocketAddress(ref saddr) => {
let port = saddr.port();
buf.put_u16(port);
buf.put_slice(&saddr.ip().octets());
buf.put_slice(&self.user_id);
buf.put_u8(b'\0');
}
Address::DomainNameAddress(ref dname, port) => {
buf.put_u16(port);
// 0.0.0.x (x!= 0)
const PLACEHOLDER: [u8; 4] = [0x00, 0x00, 0x00, 0xff];
buf.put_slice(&PLACEHOLDER);
buf.put_slice(&self.user_id);
buf.put_u8(b'\0');
buf.put_slice(dname.as_bytes());
buf.put_u8(b'\0');
}
}
}
/// Length in bytes
#[inline]
pub fn serialized_len(&self) -> usize {
let mut s = 1 + 1 + 2 + 4 + self.user_id.len() + 1; // USERID.LEN + NULL
if let Address::DomainNameAddress(ref dname, _) = self.dst {
s += dname.len() + 1;
}
s
}
}
/// Handshake Response
///
/// ```plain
/// +----+----+----+----+----+----+----+----+
/// | VN | CD | DSTPORT | DSTIP |
/// +----+----+----+----+----+----+----+----+
/// # of bytes: 1 1 2 4
/// ```
#[derive(Debug, Clone)]
pub struct HandshakeResponse {
pub cd: ResultCode,
}
impl HandshakeResponse {
/// Create a response with code
pub fn new(code: ResultCode) -> HandshakeResponse {
HandshakeResponse { cd: code }
}
/// Read from a reader
pub async fn read_from<R>(r: &mut R) -> Result<HandshakeResponse, Error>
where
R: AsyncRead + Unpin,
{
let mut buf = [0u8; 8];
let _ = r.read_exact(&mut buf).await?;
let vn = buf[0];
if vn!= 0 {
return Err(Error::UnsupportedSocksVersion(vn));
}
let cd = buf[1];
let result_code = ResultCode::from_u8(cd);
// DSTPORT, DSTIP are ignored
Ok(HandshakeResponse { cd: result_code })
}
/// Write data into a writer
pub async fn write_to<W>(&self, w: &mut W) -> io::Result<()>
where
W: AsyncWrite + Unpin,
{
let mut buf = BytesMut::with_capacity(self.serialized_len());
self.write_to_buf(&mut buf);
w.write_all(&buf).await
}
/// Writes to buffer
pub fn write_to_buf<B: BufMut>(&self, buf: &mut B) |
/// Length in bytes
#[inline]
pub fn serialized_len(&self) -> usize {
1 + 1 + 2 + 4
}
}
/// SOCKS 4/4a Error
#[derive(Error, Debug)]
pub enum Error {
// I/O Error
#[error("{0}")]
IoError(#[from] io::Error),
#[error("host must be UTF-8 encoding")]
AddressHostInvalidEncoding,
#[error("unsupported socks version {0:#x}")]
UnsupportedSocksVersion(u8),
#[error("unsupported command {0:#x}")]
UnsupportedCommand(u8),
#[error("{0}")]
Result(ResultCode),
}
impl From<Error> for io::Error {
fn from(err: Error) -> io::Error {
match err {
Error::IoError(err) => err,
e => io::Error::new(ErrorKind::Other, e),
}
}
}
| {
let HandshakeResponse { ref cd } = *self;
buf.put_slice(&[
// VN: Result Code's version, must be 0
0x00,
// CD: Result Code
cd.as_u8(),
// DSTPORT: Ignored
0x00,
0x00,
// DSTIP: Ignored
0x00,
0x00,
0x00,
0x00,
]);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.