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
authorized.rs
use session::game::{Session, GameState}; use session::game::chunk::{self, Ref}; use protocol::messages::authorized::*; use std::io::Result; use server::SERVER; #[register_handlers] impl Session { pub fn handle_admin_quiet_command_message<'a>(&mut self, chunk: Ref<'a>, msg: AdminQuietCommandMessage) -> Result<()> { let ch = match self.state { GameState::InContext(ref mut ch) => ch, _ => return Ok(()), }; if ch.movements.is_some() { return Ok(()); } let map_id: i32 = match msg.base.content.split(" ").last().map(|id| id.parse()) { Some(Ok(map_id)) => map_id, _ => return Ok(()), }; let cell_id = SERVER.with(|s| { s.maps.get(&map_id).map(|m| m.get_free_cell()).unwrap_or(None) }); if let Some(cell_id) = cell_id { chunk::teleport(chunk, ch, map_id, cell_id);
Ok(()) } }
}
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // For simd (currently x86_64/aarch64) #![cfg_attr(any(target_os = "linux", target_os = "android", target_os = "windows"), feature(heap_api))] #![feature(alloc)] #![feature(box_syntax)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(mpsc_select)] #![feature(plugin)] #![feature(range_contains)] #![feature(unique)] #![plugin(heapsize_plugin)] #![plugin(plugins)] #![plugin(serde_macros)] #![deny(unsafe_code)] extern crate alloc; extern crate app_units; extern crate azure; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; // Mac OS-specific library dependencies #[cfg(target_os = "macos")] extern crate byteorder; #[cfg(target_os = "macos")] extern crate core_foundation; #[cfg(target_os = "macos")] extern crate core_graphics; #[cfg(target_os = "macos")] extern crate core_text; extern crate euclid; extern crate fnv; // Platforms that use Freetype/Fontconfig library dependencies #[cfg(any(target_os = "linux", target_os = "android", all(target_os = "windows", target_env = "gnu")))] extern crate fontconfig; extern crate fontsan; #[cfg(any(target_os = "linux", target_os = "android", all(target_os = "windows", target_env = "gnu")))] extern crate freetype; extern crate gfx_traits; // Eventually we would like the shaper to be pluggable, as many operating systems have their own // shapers. For now, however, this is a hard dependency. extern crate harfbuzz_sys as harfbuzz; extern crate heapsize; extern crate ipc_channel; extern crate layers; #[allow(unused_extern_crates)] #[macro_use] extern crate lazy_static; extern crate libc; #[macro_use] extern crate log; extern crate mime; extern crate msg; extern crate net_traits; extern crate ordered_float; #[macro_use] extern crate profile_traits; extern crate rand; #[macro_use] extern crate range; extern crate rustc_serialize; extern crate serde; #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] extern crate simd; extern crate smallvec; #[macro_use] extern crate string_cache; extern crate style; extern crate style_traits; extern crate time; extern crate unicode_script; extern crate url; extern crate util; extern crate webrender_traits; extern crate xi_unicode; pub use paint_context::PaintContext; // Misc. mod filters; // Private painting modules mod paint_context; #[deny(unsafe_code)] pub mod display_list; // Fonts #[macro_use] pub mod font; pub mod font_cache_thread;
pub mod paint_thread; // Platform-specific implementations. #[allow(unsafe_code)] mod platform; // Text pub mod text;
pub mod font_context; pub mod font_template;
random_line_split
TestNativeDivide.rs
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh. #pragma version(1)
float __attribute__((kernel)) testNativeDivideFloatFloatFloat(float inLeftVector, unsigned int x) { float inRightVector = rsGetElementAt_float(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); } float2 __attribute__((kernel)) testNativeDivideFloat2Float2Float2(float2 inLeftVector, unsigned int x) { float2 inRightVector = rsGetElementAt_float2(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); } float3 __attribute__((kernel)) testNativeDivideFloat3Float3Float3(float3 inLeftVector, unsigned int x) { float3 inRightVector = rsGetElementAt_float3(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); } float4 __attribute__((kernel)) testNativeDivideFloat4Float4Float4(float4 inLeftVector, unsigned int x) { float4 inRightVector = rsGetElementAt_float4(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); } half __attribute__((kernel)) testNativeDivideHalfHalfHalf(half inLeftVector, unsigned int x) { half inRightVector = rsGetElementAt_half(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); } half2 __attribute__((kernel)) testNativeDivideHalf2Half2Half2(half2 inLeftVector, unsigned int x) { half2 inRightVector = rsGetElementAt_half2(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); } half3 __attribute__((kernel)) testNativeDivideHalf3Half3Half3(half3 inLeftVector, unsigned int x) { half3 inRightVector = rsGetElementAt_half3(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); } half4 __attribute__((kernel)) testNativeDivideHalf4Half4Half4(half4 inLeftVector, unsigned int x) { half4 inRightVector = rsGetElementAt_half4(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); }
#pragma rs java_package_name(android.renderscript.cts) rs_allocation gAllocInRightVector;
random_line_split
pthread.rs
//! Low level threading primitives #[cfg(not(target_os = "redox"))] use crate::errno::Errno; #[cfg(not(target_os = "redox"))] use crate::Result; use libc::{self, pthread_t}; /// Identifies an individual thread. pub type Pthread = pthread_t; /// Obtain ID of the calling thread (see /// [`pthread_self(3)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_self.html) /// /// The thread ID returned by `pthread_self()` is not the same thing as /// the kernel thread ID returned by a call to `gettid(2)`. #[inline] pub fn pthread_self() -> Pthread { unsafe { libc::pthread_self() } } feature! { #![feature = "signal"] /// Send a signal to a thread (see [`pthread_kill(3)`]). /// /// If `signal` is `None`, `pthread_kill` will only preform error checking and /// won't send any signal. /// /// [`pthread_kill(3)`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html #[cfg(not(target_os = "redox"))] pub fn pthread_kill<T>(thread: Pthread, signal: T) -> Result<()> where T: Into<Option<crate::sys::signal::Signal>> {
Errno::result(res).map(drop) } }
let sig = match signal.into() { Some(s) => s as libc::c_int, None => 0, }; let res = unsafe { libc::pthread_kill(thread, sig) };
random_line_split
pthread.rs
//! Low level threading primitives #[cfg(not(target_os = "redox"))] use crate::errno::Errno; #[cfg(not(target_os = "redox"))] use crate::Result; use libc::{self, pthread_t}; /// Identifies an individual thread. pub type Pthread = pthread_t; /// Obtain ID of the calling thread (see /// [`pthread_self(3)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_self.html) /// /// The thread ID returned by `pthread_self()` is not the same thing as /// the kernel thread ID returned by a call to `gettid(2)`. #[inline] pub fn pthread_self() -> Pthread
feature! { #![feature = "signal"] /// Send a signal to a thread (see [`pthread_kill(3)`]). /// /// If `signal` is `None`, `pthread_kill` will only preform error checking and /// won't send any signal. /// /// [`pthread_kill(3)`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html #[cfg(not(target_os = "redox"))] pub fn pthread_kill<T>(thread: Pthread, signal: T) -> Result<()> where T: Into<Option<crate::sys::signal::Signal>> { let sig = match signal.into() { Some(s) => s as libc::c_int, None => 0, }; let res = unsafe { libc::pthread_kill(thread, sig) }; Errno::result(res).map(drop) } }
{ unsafe { libc::pthread_self() } }
identifier_body
pthread.rs
//! Low level threading primitives #[cfg(not(target_os = "redox"))] use crate::errno::Errno; #[cfg(not(target_os = "redox"))] use crate::Result; use libc::{self, pthread_t}; /// Identifies an individual thread. pub type Pthread = pthread_t; /// Obtain ID of the calling thread (see /// [`pthread_self(3)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_self.html) /// /// The thread ID returned by `pthread_self()` is not the same thing as /// the kernel thread ID returned by a call to `gettid(2)`. #[inline] pub fn
() -> Pthread { unsafe { libc::pthread_self() } } feature! { #![feature = "signal"] /// Send a signal to a thread (see [`pthread_kill(3)`]). /// /// If `signal` is `None`, `pthread_kill` will only preform error checking and /// won't send any signal. /// /// [`pthread_kill(3)`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html #[cfg(not(target_os = "redox"))] pub fn pthread_kill<T>(thread: Pthread, signal: T) -> Result<()> where T: Into<Option<crate::sys::signal::Signal>> { let sig = match signal.into() { Some(s) => s as libc::c_int, None => 0, }; let res = unsafe { libc::pthread_kill(thread, sig) }; Errno::result(res).map(drop) } }
pthread_self
identifier_name
fastq.rs
// Copyright 2014-2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! FastQ reading and writing. //! //! # Example //! //! ``` //! use std::io; //! use bio::io::fastq; //! let reader = fastq::Reader::new(io::stdin()); //! ``` use std::convert::AsRef; use std::fmt; use std::fs; use std::io; use std::io::prelude::*; use std::path::Path; use utils::TextSlice; /// A FastQ reader. pub struct Reader<R: io::Read> { reader: io::BufReader<R>, sep_line: String, } impl Reader<fs::File> { /// Read from a given file. pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Self> { fs::File::open(path).map(Reader::new) } } impl<R: io::Read> Reader<R> { /// Read from a given `io::Read`. pub fn new(reader: R) -> Self { Reader { reader: io::BufReader::new(reader), sep_line: String::new(), } } /// Read into a given record. /// Returns an error if the record in incomplete or syntax is violated. /// The content of the record can be checked via the record object. pub fn read(&mut self, record: &mut Record) -> io::Result<()> { record.clear(); let mut header = String::new(); try!(self.reader.read_line(&mut header)); if!header.is_empty() { if!header.starts_with('@') { return Err(io::Error::new( io::ErrorKind::Other, "Expected @ at record start.", )); } record.id = header[1..] .trim_right() .splitn(2,'') .nth(0) .unwrap_or_default() .to_owned(); record.desc = header[1..] .trim_right() .splitn(2,'') .nth(1) .map(|s| s.to_owned());
try!(self.reader.read_line(&mut record.qual)); if record.qual.is_empty() { return Err(io::Error::new( io::ErrorKind::Other, "Incomplete record. Each FastQ record has to consist \ of 4 lines: header, sequence, separator and \ qualities.", )); } } Ok(()) } /// Return an iterator over the records of this FastQ file. pub fn records(self) -> Records<R> { Records { reader: self } } } /// A FastQ record. #[derive(Debug, Clone, Default)] pub struct Record { id: String, desc: Option<String>, seq: String, qual: String, } impl Record { /// Create a new, empty FastQ record. pub fn new() -> Self { Record { id: String::new(), desc: None, seq: String::new(), qual: String::new(), } } /// Create a new FastQ record from given attributes. pub fn with_attrs(id: &str, desc: Option<&str>, seq: TextSlice, qual: &[u8]) -> Self { let desc = match desc { Some(desc) => Some(desc.to_owned()), _ => None, }; Record { id: id.to_owned(), desc, seq: String::from_utf8(seq.to_vec()).unwrap(), qual: String::from_utf8(qual.to_vec()).unwrap(), } } /// Check if record is empty. pub fn is_empty(&self) -> bool { self.id.is_empty() && self.desc.is_none() && self.seq.is_empty() && self.qual.is_empty() } /// Check validity of FastQ record. pub fn check(&self) -> Result<(), &str> { if self.id().is_empty() { return Err("Expecting id for FastQ record."); } if!self.seq.is_ascii() { return Err("Non-ascii character found in sequence."); } if!self.qual.is_ascii() { return Err("Non-ascii character found in qualities."); } if self.seq().len()!= self.qual().len() { return Err("Unequal length of sequence an qualities."); } Ok(()) } /// Return the id of the record. pub fn id(&self) -> &str { self.id.as_ref() } /// Return descriptions if present. pub fn desc(&self) -> Option<&str> { match self.desc.as_ref() { Some(desc) => Some(&desc), None => None, } } /// Return the sequence of the record. pub fn seq(&self) -> TextSlice { self.seq.trim_right().as_bytes() } /// Return the base qualities of the record. pub fn qual(&self) -> &[u8] { self.qual.trim_right().as_bytes() } /// Clear the record. fn clear(&mut self) { self.id.clear(); self.desc = None; self.seq.clear(); self.qual.clear(); } } impl fmt::Display for Record { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( f, "@{} {}\n{}\n+\n{}", self.id, self.desc().unwrap_or_default(), self.seq, self.qual ) } } /// An iterator over the records of a FastQ file. pub struct Records<R: io::Read> { reader: Reader<R>, } impl<R: io::Read> Iterator for Records<R> { type Item = io::Result<Record>; fn next(&mut self) -> Option<io::Result<Record>> { let mut record = Record::new(); match self.reader.read(&mut record) { Ok(()) if record.is_empty() => None, Ok(()) => Some(Ok(record)), Err(err) => Some(Err(err)), } } } /// A FastQ writer. pub struct Writer<W: io::Write> { writer: io::BufWriter<W>, } impl Writer<fs::File> { /// Write to a given file path. pub fn to_file<P: AsRef<Path>>(path: P) -> io::Result<Self> { fs::File::create(path).map(Writer::new) } } impl<W: io::Write> Writer<W> { /// Write to a given `io::Write`. pub fn new(writer: W) -> Self { Writer { writer: io::BufWriter::new(writer), } } /// Directly write a FastQ record. pub fn write_record(&mut self, record: &Record) -> io::Result<()> { self.write(record.id(), record.desc(), record.seq(), record.qual()) } /// Write a FastQ record with given id, optional description, sequence and qualities. pub fn write( &mut self, id: &str, desc: Option<&str>, seq: TextSlice, qual: &[u8], ) -> io::Result<()> { try!(self.writer.write_all(b"@")); try!(self.writer.write_all(id.as_bytes())); if desc.is_some() { try!(self.writer.write_all(b" ")); try!(self.writer.write_all(desc.unwrap().as_bytes())); } try!(self.writer.write_all(b"\n")); try!(self.writer.write_all(seq)); try!(self.writer.write_all(b"\n+\n")); try!(self.writer.write_all(qual)); try!(self.writer.write_all(b"\n")); Ok(()) } /// Flush the writer, ensuring that everything is written. pub fn flush(&mut self) -> io::Result<()> { self.writer.flush() } } #[cfg(test)] mod tests { use super::*; use std::io; const FASTQ_FILE: &'static [u8] = b"@id desc ACCGTAGGCTGA + IIIIIIJJJJJJ "; #[test] fn test_reader() { let reader = Reader::new(FASTQ_FILE); let records: Vec<io::Result<Record>> = reader.records().collect(); assert!(records.len() == 1); for res in records { let record = res.ok().unwrap(); assert_eq!(record.check(), Ok(())); assert_eq!(record.id(), "id"); assert_eq!(record.desc(), Some("desc")); assert_eq!(record.seq(), b"ACCGTAGGCTGA"); assert_eq!(record.qual(), b"IIIIIIJJJJJJ"); } } #[test] fn test_record_with_attrs() { let record = Record::with_attrs("id_str", Some("desc"), b"ATGCGGG", b"QQQQQQQ"); assert_eq!(record.id(), "id_str"); assert_eq!(record.desc(), Some("desc")); assert_eq!(record.seq(), b"ATGCGGG"); assert_eq!(record.qual(), b"QQQQQQQ"); } #[test] fn test_writer() { let mut writer = Writer::new(Vec::new()); writer .write("id", Some("desc"), b"ACCGTAGGCTGA", b"IIIIIIJJJJJJ") .ok() .expect("Expected successful write"); writer.flush().ok().expect("Expected successful write"); assert_eq!(writer.writer.get_ref(), &FASTQ_FILE); } }
try!(self.reader.read_line(&mut record.seq)); try!(self.reader.read_line(&mut self.sep_line));
random_line_split
fastq.rs
// Copyright 2014-2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! FastQ reading and writing. //! //! # Example //! //! ``` //! use std::io; //! use bio::io::fastq; //! let reader = fastq::Reader::new(io::stdin()); //! ``` use std::convert::AsRef; use std::fmt; use std::fs; use std::io; use std::io::prelude::*; use std::path::Path; use utils::TextSlice; /// A FastQ reader. pub struct Reader<R: io::Read> { reader: io::BufReader<R>, sep_line: String, } impl Reader<fs::File> { /// Read from a given file. pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Self> { fs::File::open(path).map(Reader::new) } } impl<R: io::Read> Reader<R> { /// Read from a given `io::Read`. pub fn new(reader: R) -> Self { Reader { reader: io::BufReader::new(reader), sep_line: String::new(), } } /// Read into a given record. /// Returns an error if the record in incomplete or syntax is violated. /// The content of the record can be checked via the record object. pub fn read(&mut self, record: &mut Record) -> io::Result<()> { record.clear(); let mut header = String::new(); try!(self.reader.read_line(&mut header)); if!header.is_empty() { if!header.starts_with('@') { return Err(io::Error::new( io::ErrorKind::Other, "Expected @ at record start.", )); } record.id = header[1..] .trim_right() .splitn(2,'') .nth(0) .unwrap_or_default() .to_owned(); record.desc = header[1..] .trim_right() .splitn(2,'') .nth(1) .map(|s| s.to_owned()); try!(self.reader.read_line(&mut record.seq)); try!(self.reader.read_line(&mut self.sep_line)); try!(self.reader.read_line(&mut record.qual)); if record.qual.is_empty() { return Err(io::Error::new( io::ErrorKind::Other, "Incomplete record. Each FastQ record has to consist \ of 4 lines: header, sequence, separator and \ qualities.", )); } } Ok(()) } /// Return an iterator over the records of this FastQ file. pub fn records(self) -> Records<R> { Records { reader: self } } } /// A FastQ record. #[derive(Debug, Clone, Default)] pub struct Record { id: String, desc: Option<String>, seq: String, qual: String, } impl Record { /// Create a new, empty FastQ record. pub fn new() -> Self { Record { id: String::new(), desc: None, seq: String::new(), qual: String::new(), } } /// Create a new FastQ record from given attributes. pub fn with_attrs(id: &str, desc: Option<&str>, seq: TextSlice, qual: &[u8]) -> Self { let desc = match desc { Some(desc) => Some(desc.to_owned()), _ => None, }; Record { id: id.to_owned(), desc, seq: String::from_utf8(seq.to_vec()).unwrap(), qual: String::from_utf8(qual.to_vec()).unwrap(), } } /// Check if record is empty. pub fn is_empty(&self) -> bool { self.id.is_empty() && self.desc.is_none() && self.seq.is_empty() && self.qual.is_empty() } /// Check validity of FastQ record. pub fn check(&self) -> Result<(), &str> { if self.id().is_empty() { return Err("Expecting id for FastQ record."); } if!self.seq.is_ascii() {
if!self.qual.is_ascii() { return Err("Non-ascii character found in qualities."); } if self.seq().len()!= self.qual().len() { return Err("Unequal length of sequence an qualities."); } Ok(()) } /// Return the id of the record. pub fn id(&self) -> &str { self.id.as_ref() } /// Return descriptions if present. pub fn desc(&self) -> Option<&str> { match self.desc.as_ref() { Some(desc) => Some(&desc), None => None, } } /// Return the sequence of the record. pub fn seq(&self) -> TextSlice { self.seq.trim_right().as_bytes() } /// Return the base qualities of the record. pub fn qual(&self) -> &[u8] { self.qual.trim_right().as_bytes() } /// Clear the record. fn clear(&mut self) { self.id.clear(); self.desc = None; self.seq.clear(); self.qual.clear(); } } impl fmt::Display for Record { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( f, "@{} {}\n{}\n+\n{}", self.id, self.desc().unwrap_or_default(), self.seq, self.qual ) } } /// An iterator over the records of a FastQ file. pub struct Records<R: io::Read> { reader: Reader<R>, } impl<R: io::Read> Iterator for Records<R> { type Item = io::Result<Record>; fn next(&mut self) -> Option<io::Result<Record>> { let mut record = Record::new(); match self.reader.read(&mut record) { Ok(()) if record.is_empty() => None, Ok(()) => Some(Ok(record)), Err(err) => Some(Err(err)), } } } /// A FastQ writer. pub struct Writer<W: io::Write> { writer: io::BufWriter<W>, } impl Writer<fs::File> { /// Write to a given file path. pub fn to_file<P: AsRef<Path>>(path: P) -> io::Result<Self> { fs::File::create(path).map(Writer::new) } } impl<W: io::Write> Writer<W> { /// Write to a given `io::Write`. pub fn new(writer: W) -> Self { Writer { writer: io::BufWriter::new(writer), } } /// Directly write a FastQ record. pub fn write_record(&mut self, record: &Record) -> io::Result<()> { self.write(record.id(), record.desc(), record.seq(), record.qual()) } /// Write a FastQ record with given id, optional description, sequence and qualities. pub fn write( &mut self, id: &str, desc: Option<&str>, seq: TextSlice, qual: &[u8], ) -> io::Result<()> { try!(self.writer.write_all(b"@")); try!(self.writer.write_all(id.as_bytes())); if desc.is_some() { try!(self.writer.write_all(b" ")); try!(self.writer.write_all(desc.unwrap().as_bytes())); } try!(self.writer.write_all(b"\n")); try!(self.writer.write_all(seq)); try!(self.writer.write_all(b"\n+\n")); try!(self.writer.write_all(qual)); try!(self.writer.write_all(b"\n")); Ok(()) } /// Flush the writer, ensuring that everything is written. pub fn flush(&mut self) -> io::Result<()> { self.writer.flush() } } #[cfg(test)] mod tests { use super::*; use std::io; const FASTQ_FILE: &'static [u8] = b"@id desc ACCGTAGGCTGA + IIIIIIJJJJJJ "; #[test] fn test_reader() { let reader = Reader::new(FASTQ_FILE); let records: Vec<io::Result<Record>> = reader.records().collect(); assert!(records.len() == 1); for res in records { let record = res.ok().unwrap(); assert_eq!(record.check(), Ok(())); assert_eq!(record.id(), "id"); assert_eq!(record.desc(), Some("desc")); assert_eq!(record.seq(), b"ACCGTAGGCTGA"); assert_eq!(record.qual(), b"IIIIIIJJJJJJ"); } } #[test] fn test_record_with_attrs() { let record = Record::with_attrs("id_str", Some("desc"), b"ATGCGGG", b"QQQQQQQ"); assert_eq!(record.id(), "id_str"); assert_eq!(record.desc(), Some("desc")); assert_eq!(record.seq(), b"ATGCGGG"); assert_eq!(record.qual(), b"QQQQQQQ"); } #[test] fn test_writer() { let mut writer = Writer::new(Vec::new()); writer .write("id", Some("desc"), b"ACCGTAGGCTGA", b"IIIIIIJJJJJJ") .ok() .expect("Expected successful write"); writer.flush().ok().expect("Expected successful write"); assert_eq!(writer.writer.get_ref(), &FASTQ_FILE); } }
return Err("Non-ascii character found in sequence."); }
conditional_block
fastq.rs
// Copyright 2014-2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! FastQ reading and writing. //! //! # Example //! //! ``` //! use std::io; //! use bio::io::fastq; //! let reader = fastq::Reader::new(io::stdin()); //! ``` use std::convert::AsRef; use std::fmt; use std::fs; use std::io; use std::io::prelude::*; use std::path::Path; use utils::TextSlice; /// A FastQ reader. pub struct Reader<R: io::Read> { reader: io::BufReader<R>, sep_line: String, } impl Reader<fs::File> { /// Read from a given file. pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Self> { fs::File::open(path).map(Reader::new) } } impl<R: io::Read> Reader<R> { /// Read from a given `io::Read`. pub fn new(reader: R) -> Self { Reader { reader: io::BufReader::new(reader), sep_line: String::new(), } } /// Read into a given record. /// Returns an error if the record in incomplete or syntax is violated. /// The content of the record can be checked via the record object. pub fn read(&mut self, record: &mut Record) -> io::Result<()> { record.clear(); let mut header = String::new(); try!(self.reader.read_line(&mut header)); if!header.is_empty() { if!header.starts_with('@') { return Err(io::Error::new( io::ErrorKind::Other, "Expected @ at record start.", )); } record.id = header[1..] .trim_right() .splitn(2,'') .nth(0) .unwrap_or_default() .to_owned(); record.desc = header[1..] .trim_right() .splitn(2,'') .nth(1) .map(|s| s.to_owned()); try!(self.reader.read_line(&mut record.seq)); try!(self.reader.read_line(&mut self.sep_line)); try!(self.reader.read_line(&mut record.qual)); if record.qual.is_empty() { return Err(io::Error::new( io::ErrorKind::Other, "Incomplete record. Each FastQ record has to consist \ of 4 lines: header, sequence, separator and \ qualities.", )); } } Ok(()) } /// Return an iterator over the records of this FastQ file. pub fn records(self) -> Records<R> {
} /// A FastQ record. #[derive(Debug, Clone, Default)] pub struct Record { id: String, desc: Option<String>, seq: String, qual: String, } impl Record { /// Create a new, empty FastQ record. pub fn new() -> Self { Record { id: String::new(), desc: None, seq: String::new(), qual: String::new(), } } /// Create a new FastQ record from given attributes. pub fn with_attrs(id: &str, desc: Option<&str>, seq: TextSlice, qual: &[u8]) -> Self { let desc = match desc { Some(desc) => Some(desc.to_owned()), _ => None, }; Record { id: id.to_owned(), desc, seq: String::from_utf8(seq.to_vec()).unwrap(), qual: String::from_utf8(qual.to_vec()).unwrap(), } } /// Check if record is empty. pub fn is_empty(&self) -> bool { self.id.is_empty() && self.desc.is_none() && self.seq.is_empty() && self.qual.is_empty() } /// Check validity of FastQ record. pub fn check(&self) -> Result<(), &str> { if self.id().is_empty() { return Err("Expecting id for FastQ record."); } if!self.seq.is_ascii() { return Err("Non-ascii character found in sequence."); } if!self.qual.is_ascii() { return Err("Non-ascii character found in qualities."); } if self.seq().len()!= self.qual().len() { return Err("Unequal length of sequence an qualities."); } Ok(()) } /// Return the id of the record. pub fn id(&self) -> &str { self.id.as_ref() } /// Return descriptions if present. pub fn desc(&self) -> Option<&str> { match self.desc.as_ref() { Some(desc) => Some(&desc), None => None, } } /// Return the sequence of the record. pub fn seq(&self) -> TextSlice { self.seq.trim_right().as_bytes() } /// Return the base qualities of the record. pub fn qual(&self) -> &[u8] { self.qual.trim_right().as_bytes() } /// Clear the record. fn clear(&mut self) { self.id.clear(); self.desc = None; self.seq.clear(); self.qual.clear(); } } impl fmt::Display for Record { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( f, "@{} {}\n{}\n+\n{}", self.id, self.desc().unwrap_or_default(), self.seq, self.qual ) } } /// An iterator over the records of a FastQ file. pub struct Records<R: io::Read> { reader: Reader<R>, } impl<R: io::Read> Iterator for Records<R> { type Item = io::Result<Record>; fn next(&mut self) -> Option<io::Result<Record>> { let mut record = Record::new(); match self.reader.read(&mut record) { Ok(()) if record.is_empty() => None, Ok(()) => Some(Ok(record)), Err(err) => Some(Err(err)), } } } /// A FastQ writer. pub struct Writer<W: io::Write> { writer: io::BufWriter<W>, } impl Writer<fs::File> { /// Write to a given file path. pub fn to_file<P: AsRef<Path>>(path: P) -> io::Result<Self> { fs::File::create(path).map(Writer::new) } } impl<W: io::Write> Writer<W> { /// Write to a given `io::Write`. pub fn new(writer: W) -> Self { Writer { writer: io::BufWriter::new(writer), } } /// Directly write a FastQ record. pub fn write_record(&mut self, record: &Record) -> io::Result<()> { self.write(record.id(), record.desc(), record.seq(), record.qual()) } /// Write a FastQ record with given id, optional description, sequence and qualities. pub fn write( &mut self, id: &str, desc: Option<&str>, seq: TextSlice, qual: &[u8], ) -> io::Result<()> { try!(self.writer.write_all(b"@")); try!(self.writer.write_all(id.as_bytes())); if desc.is_some() { try!(self.writer.write_all(b" ")); try!(self.writer.write_all(desc.unwrap().as_bytes())); } try!(self.writer.write_all(b"\n")); try!(self.writer.write_all(seq)); try!(self.writer.write_all(b"\n+\n")); try!(self.writer.write_all(qual)); try!(self.writer.write_all(b"\n")); Ok(()) } /// Flush the writer, ensuring that everything is written. pub fn flush(&mut self) -> io::Result<()> { self.writer.flush() } } #[cfg(test)] mod tests { use super::*; use std::io; const FASTQ_FILE: &'static [u8] = b"@id desc ACCGTAGGCTGA + IIIIIIJJJJJJ "; #[test] fn test_reader() { let reader = Reader::new(FASTQ_FILE); let records: Vec<io::Result<Record>> = reader.records().collect(); assert!(records.len() == 1); for res in records { let record = res.ok().unwrap(); assert_eq!(record.check(), Ok(())); assert_eq!(record.id(), "id"); assert_eq!(record.desc(), Some("desc")); assert_eq!(record.seq(), b"ACCGTAGGCTGA"); assert_eq!(record.qual(), b"IIIIIIJJJJJJ"); } } #[test] fn test_record_with_attrs() { let record = Record::with_attrs("id_str", Some("desc"), b"ATGCGGG", b"QQQQQQQ"); assert_eq!(record.id(), "id_str"); assert_eq!(record.desc(), Some("desc")); assert_eq!(record.seq(), b"ATGCGGG"); assert_eq!(record.qual(), b"QQQQQQQ"); } #[test] fn test_writer() { let mut writer = Writer::new(Vec::new()); writer .write("id", Some("desc"), b"ACCGTAGGCTGA", b"IIIIIIJJJJJJ") .ok() .expect("Expected successful write"); writer.flush().ok().expect("Expected successful write"); assert_eq!(writer.writer.get_ref(), &FASTQ_FILE); } }
Records { reader: self } }
identifier_body
fastq.rs
// Copyright 2014-2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! FastQ reading and writing. //! //! # Example //! //! ``` //! use std::io; //! use bio::io::fastq; //! let reader = fastq::Reader::new(io::stdin()); //! ``` use std::convert::AsRef; use std::fmt; use std::fs; use std::io; use std::io::prelude::*; use std::path::Path; use utils::TextSlice; /// A FastQ reader. pub struct Reader<R: io::Read> { reader: io::BufReader<R>, sep_line: String, } impl Reader<fs::File> { /// Read from a given file. pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Self> { fs::File::open(path).map(Reader::new) } } impl<R: io::Read> Reader<R> { /// Read from a given `io::Read`. pub fn new(reader: R) -> Self { Reader { reader: io::BufReader::new(reader), sep_line: String::new(), } } /// Read into a given record. /// Returns an error if the record in incomplete or syntax is violated. /// The content of the record can be checked via the record object. pub fn read(&mut self, record: &mut Record) -> io::Result<()> { record.clear(); let mut header = String::new(); try!(self.reader.read_line(&mut header)); if!header.is_empty() { if!header.starts_with('@') { return Err(io::Error::new( io::ErrorKind::Other, "Expected @ at record start.", )); } record.id = header[1..] .trim_right() .splitn(2,'') .nth(0) .unwrap_or_default() .to_owned(); record.desc = header[1..] .trim_right() .splitn(2,'') .nth(1) .map(|s| s.to_owned()); try!(self.reader.read_line(&mut record.seq)); try!(self.reader.read_line(&mut self.sep_line)); try!(self.reader.read_line(&mut record.qual)); if record.qual.is_empty() { return Err(io::Error::new( io::ErrorKind::Other, "Incomplete record. Each FastQ record has to consist \ of 4 lines: header, sequence, separator and \ qualities.", )); } } Ok(()) } /// Return an iterator over the records of this FastQ file. pub fn records(self) -> Records<R> { Records { reader: self } } } /// A FastQ record. #[derive(Debug, Clone, Default)] pub struct Record { id: String, desc: Option<String>, seq: String, qual: String, } impl Record { /// Create a new, empty FastQ record. pub fn new() -> Self { Record { id: String::new(), desc: None, seq: String::new(), qual: String::new(), } } /// Create a new FastQ record from given attributes. pub fn with_attrs(id: &str, desc: Option<&str>, seq: TextSlice, qual: &[u8]) -> Self { let desc = match desc { Some(desc) => Some(desc.to_owned()), _ => None, }; Record { id: id.to_owned(), desc, seq: String::from_utf8(seq.to_vec()).unwrap(), qual: String::from_utf8(qual.to_vec()).unwrap(), } } /// Check if record is empty. pub fn is_empty(&self) -> bool { self.id.is_empty() && self.desc.is_none() && self.seq.is_empty() && self.qual.is_empty() } /// Check validity of FastQ record. pub fn check(&self) -> Result<(), &str> { if self.id().is_empty() { return Err("Expecting id for FastQ record."); } if!self.seq.is_ascii() { return Err("Non-ascii character found in sequence."); } if!self.qual.is_ascii() { return Err("Non-ascii character found in qualities."); } if self.seq().len()!= self.qual().len() { return Err("Unequal length of sequence an qualities."); } Ok(()) } /// Return the id of the record. pub fn id(&self) -> &str { self.id.as_ref() } /// Return descriptions if present. pub fn desc(&self) -> Option<&str> { match self.desc.as_ref() { Some(desc) => Some(&desc), None => None, } } /// Return the sequence of the record. pub fn seq(&self) -> TextSlice { self.seq.trim_right().as_bytes() } /// Return the base qualities of the record. pub fn qual(&self) -> &[u8] { self.qual.trim_right().as_bytes() } /// Clear the record. fn clear(&mut self) { self.id.clear(); self.desc = None; self.seq.clear(); self.qual.clear(); } } impl fmt::Display for Record { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( f, "@{} {}\n{}\n+\n{}", self.id, self.desc().unwrap_or_default(), self.seq, self.qual ) } } /// An iterator over the records of a FastQ file. pub struct Records<R: io::Read> { reader: Reader<R>, } impl<R: io::Read> Iterator for Records<R> { type Item = io::Result<Record>; fn next(&mut self) -> Option<io::Result<Record>> { let mut record = Record::new(); match self.reader.read(&mut record) { Ok(()) if record.is_empty() => None, Ok(()) => Some(Ok(record)), Err(err) => Some(Err(err)), } } } /// A FastQ writer. pub struct Writer<W: io::Write> { writer: io::BufWriter<W>, } impl Writer<fs::File> { /// Write to a given file path. pub fn to_file<P: AsRef<Path>>(path: P) -> io::Result<Self> { fs::File::create(path).map(Writer::new) } } impl<W: io::Write> Writer<W> { /// Write to a given `io::Write`. pub fn new(writer: W) -> Self { Writer { writer: io::BufWriter::new(writer), } } /// Directly write a FastQ record. pub fn write_record(&mut self, record: &Record) -> io::Result<()> { self.write(record.id(), record.desc(), record.seq(), record.qual()) } /// Write a FastQ record with given id, optional description, sequence and qualities. pub fn write( &mut self, id: &str, desc: Option<&str>, seq: TextSlice, qual: &[u8], ) -> io::Result<()> { try!(self.writer.write_all(b"@")); try!(self.writer.write_all(id.as_bytes())); if desc.is_some() { try!(self.writer.write_all(b" ")); try!(self.writer.write_all(desc.unwrap().as_bytes())); } try!(self.writer.write_all(b"\n")); try!(self.writer.write_all(seq)); try!(self.writer.write_all(b"\n+\n")); try!(self.writer.write_all(qual)); try!(self.writer.write_all(b"\n")); Ok(()) } /// Flush the writer, ensuring that everything is written. pub fn flush(&mut self) -> io::Result<()> { self.writer.flush() } } #[cfg(test)] mod tests { use super::*; use std::io; const FASTQ_FILE: &'static [u8] = b"@id desc ACCGTAGGCTGA + IIIIIIJJJJJJ "; #[test] fn t
) { let reader = Reader::new(FASTQ_FILE); let records: Vec<io::Result<Record>> = reader.records().collect(); assert!(records.len() == 1); for res in records { let record = res.ok().unwrap(); assert_eq!(record.check(), Ok(())); assert_eq!(record.id(), "id"); assert_eq!(record.desc(), Some("desc")); assert_eq!(record.seq(), b"ACCGTAGGCTGA"); assert_eq!(record.qual(), b"IIIIIIJJJJJJ"); } } #[test] fn test_record_with_attrs() { let record = Record::with_attrs("id_str", Some("desc"), b"ATGCGGG", b"QQQQQQQ"); assert_eq!(record.id(), "id_str"); assert_eq!(record.desc(), Some("desc")); assert_eq!(record.seq(), b"ATGCGGG"); assert_eq!(record.qual(), b"QQQQQQQ"); } #[test] fn test_writer() { let mut writer = Writer::new(Vec::new()); writer .write("id", Some("desc"), b"ACCGTAGGCTGA", b"IIIIIIJJJJJJ") .ok() .expect("Expected successful write"); writer.flush().ok().expect("Expected successful write"); assert_eq!(writer.writer.get_ref(), &FASTQ_FILE); } }
est_reader(
identifier_name
http_get.rs
extern crate clap; extern crate fibers; extern crate futures; extern crate miasht; use clap::{App, Arg}; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::{Future, IntoFuture}; use miasht::{Client, Method}; use miasht::builtin::{FutureExt, IoExt}; fn main()
Client::new() .connect(addr) .and_then(move |connection| connection.build_request(Method::Get, &path).finish()) .and_then(|req| req.read_response()) .and_then(|res| { res.into_body_reader() .into_future() .and_then(|r| r.read_all_str()) .map(|(_, body)| body) }), ); match executor.run_fiber(monitor).unwrap() { Ok(s) => println!("{}", s), Err(e) => println!("[ERROR] {:?}", e), } }
{ let matches = App::new("http_get") .arg(Arg::with_name("HOST").index(1).required(true)) .arg(Arg::with_name("PATH").index(2).required(true)) .arg( Arg::with_name("PORT") .short("p") .takes_value(true) .default_value("80"), ) .get_matches(); let host = matches.value_of("HOST").unwrap(); let path = matches.value_of("PATH").unwrap().to_string(); let port = matches.value_of("PORT").unwrap(); let addr = format!("{}:{}", host, port) .parse() .expect("Invalid address"); let mut executor = InPlaceExecutor::new().unwrap(); let monitor = executor.spawn_monitor(
identifier_body
http_get.rs
extern crate clap; extern crate fibers; extern crate futures; extern crate miasht; use clap::{App, Arg}; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::{Future, IntoFuture}; use miasht::{Client, Method}; use miasht::builtin::{FutureExt, IoExt}; fn main() { let matches = App::new("http_get") .arg(Arg::with_name("HOST").index(1).required(true)) .arg(Arg::with_name("PATH").index(2).required(true)) .arg( Arg::with_name("PORT") .short("p") .takes_value(true) .default_value("80"), ) .get_matches(); let host = matches.value_of("HOST").unwrap(); let path = matches.value_of("PATH").unwrap().to_string(); let port = matches.value_of("PORT").unwrap(); let addr = format!("{}:{}", host, port) .parse() .expect("Invalid address"); let mut executor = InPlaceExecutor::new().unwrap(); let monitor = executor.spawn_monitor( Client::new() .connect(addr) .and_then(move |connection| connection.build_request(Method::Get, &path).finish()) .and_then(|req| req.read_response()) .and_then(|res| { res.into_body_reader()
); match executor.run_fiber(monitor).unwrap() { Ok(s) => println!("{}", s), Err(e) => println!("[ERROR] {:?}", e), } }
.into_future() .and_then(|r| r.read_all_str()) .map(|(_, body)| body) }),
random_line_split
http_get.rs
extern crate clap; extern crate fibers; extern crate futures; extern crate miasht; use clap::{App, Arg}; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::{Future, IntoFuture}; use miasht::{Client, Method}; use miasht::builtin::{FutureExt, IoExt}; fn
() { let matches = App::new("http_get") .arg(Arg::with_name("HOST").index(1).required(true)) .arg(Arg::with_name("PATH").index(2).required(true)) .arg( Arg::with_name("PORT") .short("p") .takes_value(true) .default_value("80"), ) .get_matches(); let host = matches.value_of("HOST").unwrap(); let path = matches.value_of("PATH").unwrap().to_string(); let port = matches.value_of("PORT").unwrap(); let addr = format!("{}:{}", host, port) .parse() .expect("Invalid address"); let mut executor = InPlaceExecutor::new().unwrap(); let monitor = executor.spawn_monitor( Client::new() .connect(addr) .and_then(move |connection| connection.build_request(Method::Get, &path).finish()) .and_then(|req| req.read_response()) .and_then(|res| { res.into_body_reader() .into_future() .and_then(|r| r.read_all_str()) .map(|(_, body)| body) }), ); match executor.run_fiber(monitor).unwrap() { Ok(s) => println!("{}", s), Err(e) => println!("[ERROR] {:?}", e), } }
main
identifier_name
example.rs
extern crate int_range_check; use std::fmt::Display; use std::num::Int; use int_range_check::uncovered_and_overlapped; use int_range_check::IntRange; use int_range_check::IntRange::*; fn main() { example_driver("Example 1", vec![Bound(0i32, 5i32), From(3)]); example_driver("Example 2a", vec![To(5u8), From(250)]); example_driver("Example 2b", vec![Bound(0u8, 5), Bound(250, 255)]); } fn example_driver<T: Display+Int>(title: &str, ranges: Vec<IntRange<T>>) { let (uncovered, overlapped) = uncovered_and_overlapped(&ranges);
println!("{} uncovered ranges: {}", title, uncovered); println!("{} overlapping ranges: {}", title, overlapped); }
println!("{} input ranges: {}", title, ranges);
random_line_split
example.rs
extern crate int_range_check; use std::fmt::Display; use std::num::Int; use int_range_check::uncovered_and_overlapped; use int_range_check::IntRange; use int_range_check::IntRange::*; fn main() { example_driver("Example 1", vec![Bound(0i32, 5i32), From(3)]); example_driver("Example 2a", vec![To(5u8), From(250)]); example_driver("Example 2b", vec![Bound(0u8, 5), Bound(250, 255)]); } fn
<T: Display+Int>(title: &str, ranges: Vec<IntRange<T>>) { let (uncovered, overlapped) = uncovered_and_overlapped(&ranges); println!("{} input ranges: {}", title, ranges); println!("{} uncovered ranges: {}", title, uncovered); println!("{} overlapping ranges: {}", title, overlapped); }
example_driver
identifier_name
example.rs
extern crate int_range_check; use std::fmt::Display; use std::num::Int; use int_range_check::uncovered_and_overlapped; use int_range_check::IntRange; use int_range_check::IntRange::*; fn main()
fn example_driver<T: Display+Int>(title: &str, ranges: Vec<IntRange<T>>) { let (uncovered, overlapped) = uncovered_and_overlapped(&ranges); println!("{} input ranges: {}", title, ranges); println!("{} uncovered ranges: {}", title, uncovered); println!("{} overlapping ranges: {}", title, overlapped); }
{ example_driver("Example 1", vec![Bound(0i32, 5i32), From(3)]); example_driver("Example 2a", vec![To(5u8), From(250)]); example_driver("Example 2b", vec![Bound(0u8, 5), Bound(250, 255)]); }
identifier_body
group_by.rs
use deuterium::*; #[test] fn select_group_by() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let side = NamedField::<bool>::field_of("side", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_all().group_by(&[&name, &side]); assert_sql!(query, "SELECT * FROM jedi GROUP BY name, side;"); // Edge case where `by` is empty let empty: &[&UntypedExpression] = &[]; let query = jedi_table.select_all().group_by(empty); assert_sql!(query, "SELECT * FROM jedi;"); let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM(force_level) FROM jedi GROUP BY name;"); } #[test] fn
() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM(force_level) FROM jedi GROUP BY name;"); }
select_with_agg
identifier_name
group_by.rs
use deuterium::*; #[test] fn select_group_by() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let side = NamedField::<bool>::field_of("side", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_all().group_by(&[&name, &side]); assert_sql!(query, "SELECT * FROM jedi GROUP BY name, side;"); // Edge case where `by` is empty let empty: &[&UntypedExpression] = &[]; let query = jedi_table.select_all().group_by(empty); assert_sql!(query, "SELECT * FROM jedi;"); let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM(force_level) FROM jedi GROUP BY name;"); } #[test] fn select_with_agg()
{ let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM(force_level) FROM jedi GROUP BY name;"); }
identifier_body
group_by.rs
use deuterium::*; #[test] fn select_group_by() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let side = NamedField::<bool>::field_of("side", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_all().group_by(&[&name, &side]); assert_sql!(query, "SELECT * FROM jedi GROUP BY name, side;"); // Edge case where `by` is empty let empty: &[&UntypedExpression] = &[]; let query = jedi_table.select_all().group_by(empty); assert_sql!(query, "SELECT * FROM jedi;");
} #[test] fn select_with_agg() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM(force_level) FROM jedi GROUP BY name;"); }
let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM(force_level) FROM jedi GROUP BY name;");
random_line_split
worker.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::sync::*; use std::mem; use std::thread::{self, JoinHandle}; use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use crossbeam::sync::chase_lev; use io::service::{HandlerId, IoChannel, IoContext}; use io::IoHandler; use panics::*; pub enum WorkType<Message> { Readable, Writable, Hup, Timeout, Message(Message), } pub struct
<Message> { pub work_type: WorkType<Message>, pub token: usize, pub handler_id: HandlerId, pub handler: Arc<IoHandler<Message>>, } /// An IO worker thread /// Sorts them ready for blockchain insertion. pub struct Worker { thread: Option<JoinHandle<()>>, wait: Arc<Condvar>, deleting: Arc<AtomicBool>, wait_mutex: Arc<Mutex<()>>, } impl Worker { /// Creates a new worker instance. pub fn new<Message>(index: usize, stealer: chase_lev::Stealer<Work<Message>>, channel: IoChannel<Message>, wait: Arc<Condvar>, wait_mutex: Arc<Mutex<()>>, panic_handler: Arc<PanicHandler>) -> Worker where Message: Send + Sync + Clone +'static, { let deleting = Arc::new(AtomicBool::new(false)); let mut worker = Worker { thread: None, wait: wait.clone(), deleting: deleting.clone(), wait_mutex: wait_mutex.clone(), }; worker.thread = Some(thread::Builder::new() .name(format!("IO Worker #{}", index)) .spawn(move || { panic_handler.catch_panic(move || Worker::work_loop(stealer, channel.clone(), wait, wait_mutex.clone(), deleting)) .unwrap() }) .expect("Error creating worker thread")); worker } fn work_loop<Message>(stealer: chase_lev::Stealer<Work<Message>>, channel: IoChannel<Message>, wait: Arc<Condvar>, wait_mutex: Arc<Mutex<()>>, deleting: Arc<AtomicBool>) where Message: Send + Sync + Clone +'static, { loop { { let lock = wait_mutex.lock().unwrap(); if deleting.load(AtomicOrdering::Acquire) { return; } let _ = wait.wait(lock).unwrap(); } if deleting.load(AtomicOrdering::Acquire) { return; } while let chase_lev::Steal::Data(work) = stealer.steal() { Worker::do_work(work, channel.clone()); } } } fn do_work<Message>(work: Work<Message>, channel: IoChannel<Message>) where Message: Send + Sync + Clone +'static, { match work.work_type { WorkType::Readable => { work.handler.stream_readable(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Writable => { work.handler.stream_writable(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Hup => { work.handler.stream_hup(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Timeout => { work.handler.timeout(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Message(message) => { work.handler.message(&IoContext::new(channel, work.handler_id), &message); } } } } impl Drop for Worker { fn drop(&mut self) { trace!(target: "shutdown", "[IoWorker] Closing..."); let _ = self.wait_mutex.lock(); self.deleting.store(true, AtomicOrdering::Release); self.wait.notify_all(); let thread = mem::replace(&mut self.thread, None).unwrap(); thread.join().ok(); trace!(target: "shutdown", "[IoWorker] Closed"); } }
Work
identifier_name
worker.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::sync::*; use std::mem; use std::thread::{self, JoinHandle}; use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use crossbeam::sync::chase_lev; use io::service::{HandlerId, IoChannel, IoContext}; use io::IoHandler; use panics::*; pub enum WorkType<Message> { Readable, Writable, Hup, Timeout, Message(Message), } pub struct Work<Message> { pub work_type: WorkType<Message>, pub token: usize, pub handler_id: HandlerId, pub handler: Arc<IoHandler<Message>>, } /// An IO worker thread /// Sorts them ready for blockchain insertion. pub struct Worker { thread: Option<JoinHandle<()>>, wait: Arc<Condvar>, deleting: Arc<AtomicBool>, wait_mutex: Arc<Mutex<()>>, } impl Worker { /// Creates a new worker instance. pub fn new<Message>(index: usize, stealer: chase_lev::Stealer<Work<Message>>, channel: IoChannel<Message>, wait: Arc<Condvar>, wait_mutex: Arc<Mutex<()>>, panic_handler: Arc<PanicHandler>) -> Worker where Message: Send + Sync + Clone +'static, { let deleting = Arc::new(AtomicBool::new(false)); let mut worker = Worker { thread: None, wait: wait.clone(), deleting: deleting.clone(), wait_mutex: wait_mutex.clone(), }; worker.thread = Some(thread::Builder::new() .name(format!("IO Worker #{}", index)) .spawn(move || { panic_handler.catch_panic(move || Worker::work_loop(stealer, channel.clone(), wait, wait_mutex.clone(), deleting)) .unwrap() }) .expect("Error creating worker thread")); worker } fn work_loop<Message>(stealer: chase_lev::Stealer<Work<Message>>, channel: IoChannel<Message>, wait: Arc<Condvar>, wait_mutex: Arc<Mutex<()>>, deleting: Arc<AtomicBool>) where Message: Send + Sync + Clone +'static, { loop { { let lock = wait_mutex.lock().unwrap(); if deleting.load(AtomicOrdering::Acquire) { return; } let _ = wait.wait(lock).unwrap(); } if deleting.load(AtomicOrdering::Acquire) { return; } while let chase_lev::Steal::Data(work) = stealer.steal() { Worker::do_work(work, channel.clone()); } } } fn do_work<Message>(work: Work<Message>, channel: IoChannel<Message>) where Message: Send + Sync + Clone +'static, { match work.work_type { WorkType::Readable => { work.handler.stream_readable(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Writable => { work.handler.stream_writable(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Hup => { work.handler.stream_hup(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Timeout =>
WorkType::Message(message) => { work.handler.message(&IoContext::new(channel, work.handler_id), &message); } } } } impl Drop for Worker { fn drop(&mut self) { trace!(target: "shutdown", "[IoWorker] Closing..."); let _ = self.wait_mutex.lock(); self.deleting.store(true, AtomicOrdering::Release); self.wait.notify_all(); let thread = mem::replace(&mut self.thread, None).unwrap(); thread.join().ok(); trace!(target: "shutdown", "[IoWorker] Closed"); } }
{ work.handler.timeout(&IoContext::new(channel, work.handler_id), work.token); }
conditional_block
worker.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::sync::*; use std::mem; use std::thread::{self, JoinHandle}; use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use crossbeam::sync::chase_lev; use io::service::{HandlerId, IoChannel, IoContext}; use io::IoHandler; use panics::*; pub enum WorkType<Message> { Readable, Writable, Hup, Timeout, Message(Message), } pub struct Work<Message> { pub work_type: WorkType<Message>, pub token: usize, pub handler_id: HandlerId, pub handler: Arc<IoHandler<Message>>, } /// An IO worker thread /// Sorts them ready for blockchain insertion. pub struct Worker { thread: Option<JoinHandle<()>>, wait: Arc<Condvar>, deleting: Arc<AtomicBool>, wait_mutex: Arc<Mutex<()>>, } impl Worker { /// Creates a new worker instance. pub fn new<Message>(index: usize, stealer: chase_lev::Stealer<Work<Message>>, channel: IoChannel<Message>, wait: Arc<Condvar>, wait_mutex: Arc<Mutex<()>>, panic_handler: Arc<PanicHandler>) -> Worker where Message: Send + Sync + Clone +'static, { let deleting = Arc::new(AtomicBool::new(false)); let mut worker = Worker { thread: None, wait: wait.clone(), deleting: deleting.clone(), wait_mutex: wait_mutex.clone(), }; worker.thread = Some(thread::Builder::new() .name(format!("IO Worker #{}", index)) .spawn(move || { panic_handler.catch_panic(move || Worker::work_loop(stealer, channel.clone(), wait, wait_mutex.clone(), deleting)) .unwrap() }) .expect("Error creating worker thread")); worker } fn work_loop<Message>(stealer: chase_lev::Stealer<Work<Message>>, channel: IoChannel<Message>, wait: Arc<Condvar>, wait_mutex: Arc<Mutex<()>>, deleting: Arc<AtomicBool>) where Message: Send + Sync + Clone +'static, { loop { { let lock = wait_mutex.lock().unwrap(); if deleting.load(AtomicOrdering::Acquire) { return; } let _ = wait.wait(lock).unwrap(); } if deleting.load(AtomicOrdering::Acquire) { return; } while let chase_lev::Steal::Data(work) = stealer.steal() { Worker::do_work(work, channel.clone()); } } } fn do_work<Message>(work: Work<Message>, channel: IoChannel<Message>) where Message: Send + Sync + Clone +'static, { match work.work_type { WorkType::Readable => { work.handler.stream_readable(&IoContext::new(channel, work.handler_id), work.token);
} WorkType::Hup => { work.handler.stream_hup(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Timeout => { work.handler.timeout(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Message(message) => { work.handler.message(&IoContext::new(channel, work.handler_id), &message); } } } } impl Drop for Worker { fn drop(&mut self) { trace!(target: "shutdown", "[IoWorker] Closing..."); let _ = self.wait_mutex.lock(); self.deleting.store(true, AtomicOrdering::Release); self.wait.notify_all(); let thread = mem::replace(&mut self.thread, None).unwrap(); thread.join().ok(); trace!(target: "shutdown", "[IoWorker] Closed"); } }
} WorkType::Writable => { work.handler.stream_writable(&IoContext::new(channel, work.handler_id), work.token);
random_line_split
vec-matching-autoslice.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. // run-pass #![allow(illegal_floating_point_literal_pattern)] // FIXME #41620 pub fn
() { let x = [1, 2, 3]; match x { [2, _, _] => panic!(), [1, a, b] => { assert_eq!([a, b], [2, 3]); } [_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y { ([(1, a), (b, false)], _) => { assert_eq!(a, true); assert_eq!(b, 2); } ([_, _], 0.5) => panic!(), ([_, _], _) => panic!(), } }
main
identifier_name
vec-matching-autoslice.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. // run-pass #![allow(illegal_floating_point_literal_pattern)] // FIXME #41620
pub fn main() { let x = [1, 2, 3]; match x { [2, _, _] => panic!(), [1, a, b] => { assert_eq!([a, b], [2, 3]); } [_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y { ([(1, a), (b, false)], _) => { assert_eq!(a, true); assert_eq!(b, 2); } ([_, _], 0.5) => panic!(), ([_, _], _) => panic!(), } }
random_line_split
vec-matching-autoslice.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. // run-pass #![allow(illegal_floating_point_literal_pattern)] // FIXME #41620 pub fn main()
{ let x = [1, 2, 3]; match x { [2, _, _] => panic!(), [1, a, b] => { assert_eq!([a, b], [2, 3]); } [_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y { ([(1, a), (b, false)], _) => { assert_eq!(a, true); assert_eq!(b, 2); } ([_, _], 0.5) => panic!(), ([_, _], _) => panic!(), } }
identifier_body
lib.rs
//! Concurrent work-stealing deques. //! //! These data structures are most commonly used in work-stealing schedulers. The typical setup //! involves a number of threads, each having its own FIFO or LIFO queue (*worker*). There is also //! one global FIFO queue (*injector*) and a list of references to *worker* queues that are able to //! steal tasks (*stealers*). //! //! We spawn a new task onto the scheduler by pushing it into the *injector* queue. Each worker //! thread waits in a loop until it finds the next task to run and then runs it. To find a task, it //! first looks into its local *worker* queue, and then into the *injector* and *stealers*. //! //! # Queues //! //! [`Injector`] is a FIFO queue, where tasks are pushed and stolen from opposite ends. It is //! shared among threads and is usually the entry point for new tasks. //! //! [`Worker`] has two constructors: //! //! * [`new_fifo()`] - Creates a FIFO queue, in which tasks are pushed and popped from opposite //! ends. //! * [`new_lifo()`] - Creates a LIFO queue, in which tasks are pushed and popped from the same //! end. //! //! Each [`Worker`] is owned by a single thread and supports only push and pop operations. //! //! Method [`stealer()`] creates a [`Stealer`] that may be shared among threads and can only steal //! tasks from its [`Worker`]. Tasks are stolen from the end opposite to where they get pushed. //! //! # Stealing //! //! Steal operations come in three flavors: //! //! 1. [`steal()`] - Steals one task. //! 2. [`steal_batch()`] - Steals a batch of tasks and moves them into another worker. //! 3. [`steal_batch_and_pop()`] - Steals a batch of tasks, moves them into another queue, and pops //! one task from that worker. //! //! In contrast to push and pop operations, stealing can spuriously fail with [`Steal::Retry`], in //! which case the steal operation needs to be retried. //! //! # Examples //! //! Suppose a thread in a work-stealing scheduler is idle and looking for the next task to run. To //! find an available task, it might do the following: //! //! 1. Try popping one task from the local worker queue. //! 2. Try stealing a batch of tasks from the global injector queue. //! 3. Try stealing one task from another thread using the stealer list. //! //! An implementation of this work-stealing strategy: //! //! ``` //! use crossbeam_deque::{Injector, Stealer, Worker}; //! use std::iter; //! //! fn find_task<T>( //! local: &Worker<T>, //! global: &Injector<T>, //! stealers: &[Stealer<T>],
//! ) -> Option<T> { //! // Pop a task from the local queue, if not empty. //! local.pop().or_else(|| { //! // Otherwise, we need to look for a task elsewhere. //! iter::repeat_with(|| { //! // Try stealing a batch of tasks from the global queue. //! global.steal_batch_and_pop(local) //! // Or try stealing a task from one of the other threads. //! .or_else(|| stealers.iter().map(|s| s.steal()).collect()) //! }) //! // Loop while no task was stolen and any steal operation needs to be retried. //! .find(|s|!s.is_retry()) //! // Extract the stolen task, if there is one. //! .and_then(|s| s.success()) //! }) //! } //! ``` //! //! [`new_fifo()`]: Worker::new_fifo //! [`new_lifo()`]: Worker::new_lifo //! [`stealer()`]: Worker::stealer //! [`steal()`]: Stealer::steal //! [`steal_batch()`]: Stealer::steal_batch //! [`steal_batch_and_pop()`]: Stealer::steal_batch_and_pop #![doc(test( no_crate_inject, attr( deny(warnings, rust_2018_idioms), allow(dead_code, unused_assignments, unused_variables) ) ))] #![warn( missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub )] #![allow(clippy::question_mark)] // https://github.com/rust-lang/rust-clippy/issues/8281 #![cfg_attr(not(feature = "std"), no_std)] use cfg_if::cfg_if; cfg_if! { if #[cfg(feature = "std")] { use crossbeam_epoch as epoch; use crossbeam_utils as utils; mod deque; pub use crate::deque::{Injector, Steal, Stealer, Worker}; } }
random_line_split
scalar.rs
// mrusty. mruby safe bindings for Rust // Copyright (C) 2016 Dragoș Tiselice // // 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 mrusty::MrubyImpl; use super::Vector; #[derive(Clone, Debug, PartialEq)] pub struct S
{ pub value: f32 } impl Scalar { pub fn new(value: f32) -> Scalar { Scalar { value: value } } pub fn set_value(&mut self, value: f32) { self.value = value; } } mrusty_class!(Scalar, { def!("initialize", |v: f64| { Scalar::new(v as f32) }); def!("value", |mruby, slf: (&Scalar)| { mruby.float(slf.value as f64) }); def!("value=", |mruby, slf: (&mut Scalar), v: f64| { slf.set_value(v as f32); mruby.nil() }); def!("*", |mruby, slf: (&Scalar), vector: (&Vector)| { mruby.obj((*slf).clone() * (*vector).clone()) }); def!("panic", |_slf: Value| { panic!("I always panic."); }); });
calar
identifier_name
scalar.rs
// mrusty. mruby safe bindings for Rust // Copyright (C) 2016 Dragoș Tiselice // // 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 mrusty::MrubyImpl; use super::Vector; #[derive(Clone, Debug, PartialEq)] pub struct Scalar { pub value: f32 } impl Scalar { pub fn new(value: f32) -> Scalar { Scalar { value: value } } pub fn set_value(&mut self, value: f32) { self.value = value; } } mrusty_class!(Scalar, { def!("initialize", |v: f64| { Scalar::new(v as f32)
}); def!("value=", |mruby, slf: (&mut Scalar), v: f64| { slf.set_value(v as f32); mruby.nil() }); def!("*", |mruby, slf: (&Scalar), vector: (&Vector)| { mruby.obj((*slf).clone() * (*vector).clone()) }); def!("panic", |_slf: Value| { panic!("I always panic."); }); });
}); def!("value", |mruby, slf: (&Scalar)| { mruby.float(slf.value as f64)
random_line_split
scalar.rs
// mrusty. mruby safe bindings for Rust // Copyright (C) 2016 Dragoș Tiselice // // 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 mrusty::MrubyImpl; use super::Vector; #[derive(Clone, Debug, PartialEq)] pub struct Scalar { pub value: f32 } impl Scalar { pub fn new(value: f32) -> Scalar { Scalar { value: value } } pub fn set_value(&mut self, value: f32) {
} mrusty_class!(Scalar, { def!("initialize", |v: f64| { Scalar::new(v as f32) }); def!("value", |mruby, slf: (&Scalar)| { mruby.float(slf.value as f64) }); def!("value=", |mruby, slf: (&mut Scalar), v: f64| { slf.set_value(v as f32); mruby.nil() }); def!("*", |mruby, slf: (&Scalar), vector: (&Vector)| { mruby.obj((*slf).clone() * (*vector).clone()) }); def!("panic", |_slf: Value| { panic!("I always panic."); }); });
self.value = value; }
identifier_body
lib.rs
//! A simple X11 status bar for use with simple WMs. //! //! Cnx is written to be customisable, simple and fast. Where possible, it //! prefers to asynchronously wait for changes in the underlying data sources //! (and uses [`tokio`] to achieve this), rather than periodically //! calling out to external programs. //! //! # How to use //! //! Cnx is a library that allows you to make your own status bar. //! //! In normal usage, you will create a new binary project that relies on the //! `cnx` crate, and customize it through options passed to the main [`Cnx`] //! object and its widgets. (It's inspired by [`QTile`] and [`dwm`], in that the //! configuration is done entirely in code, allowing greater extensibility //! without needing complex configuration handling). //! //! An simple example of a binary using Cnx is: //! //! ```no_run //! //! use cnx::text::*; //! use cnx::widgets::*; //! use cnx::{Cnx, Position}; //! use anyhow::Result; //! //! fn main() -> Result<()> { //! let attr = Attributes { //! font: Font::new("Envy Code R 21"), //! fg_color: Color::white(), //! bg_color: None, //! padding: Padding::new(8.0, 8.0, 0.0, 0.0), //! }; //! //! let mut cnx = Cnx::new(Position::Top); //! cnx.add_widget(ActiveWindowTitle::new(attr.clone())); //! cnx.add_widget(Clock::new(attr.clone(), None)); //! cnx.run()?; //! //! Ok(()) //! } //! ``` //! //! A more complex example is given in [`cnx-bin/src/main.rs`] alongside the project. //! (This is the default `[bin]` target for the crate, so you _could_ use it by //! either executing `cargo run` from the crate root, or even running `cargo //! install cnx; cnx`. However, neither of these are recommended as options for //! customizing Cnx are then limited). //! //! Before running Cnx, you'll need to make sure your system has the required //! dependencies, which are described in the [`README`][readme-deps]. //! //! # Built-in widgets //! //! There are currently these widgets available: //! //! - [`crate::widgets::ActiveWindowTitle`] — Shows the title ([`EWMH`]'s `_NET_WM_NAME`) for //! the currently focused window ([`EWMH`]'s `_NEW_ACTIVE_WINDOW`). //! - [`crate::widgets::Pager`] — Shows the WM's workspaces/groups, highlighting whichever is //! currently active. (Uses [`EWMH`]'s `_NET_DESKTOP_NAMES`, //! `_NET_NUMBER_OF_DESKTOPS` and `_NET_CURRENT_DESKTOP`). //! - [`crate::widgets::Clock`] — Shows the time. //! //! The cnx-contrib crate contains additional widgets: //! //! - **Sensors** — Periodically parses and displays the output of the //! sensors provided by the system. //! - **Volume** - Shows the current volume/mute status of the default output //! device. //! - **Battery** - Shows the remaining battery and charge status. //! - **Wireless** - Shows the wireless strength of your current network. //! - **CPU** - Shows the current CPU consumption //! - **Weather** - Shows the Weather information of your location //! - **Disk Usage** - Show the current usage of your monted filesystem //! //! The Sensors, Volume and Battery widgets require platform //! support. They currently support Linux (see dependencies below) and OpenBSD. //! Support for additional platforms should be possible. //! //! # Dependencies //! //! In addition to the Rust dependencies in `Cargo.toml`, Cnx also depends on //! these system libraries: //! //! - `xcb-util`: `xcb-ewmh` / `xcb-icccm` / `xcb-keysyms` //! - `x11-xcb` //! - `pango` //! - `cairo` //! - `pangocairo` //! //! Some widgets have additional dependencies on Linux: //! //! - **Volume** widget relies on `alsa-lib` //! - **Sensors** widget relies on [`lm_sensors`] being installed. //! - **Wireless** widget relies on `libiw-dev`. //! //! # Creating new widgets //! //! Cnx is designed such that thirdparty widgets can be written in //! external crates and used with the main [`Cnx`] instance. We have //! [`cnx-contrib`] crate which contains various additional //! widgets. You can also create new crates or add it to the existing //! [`cnx-contrib`] crate. //! //! The built-in [`widgets`] should give you some examples on which to base //! your work. //! //! [`tokio`]: https://tokio.rs/ //! [`QTile`]: http://www.qtile.org/ //! [`dwm`]: http://dwm.suckless.org/ //! [readme-deps]: https://github.com/mjkillough/cnx/blob/master/README.md#dependencies //! [`cnx-bin/src/main.rs`]: https://github.com/mjkillough/cnx/blob/master/cnx-bin/src/main.rs //! [`EWMH`]: https://specifications.freedesktop.org/wm-spec/wm-spec-latest.html //! [`lm_sensors`]: https://wiki.archlinux.org/index.php/lm_sensors //! [`cnx-contrib`]: https://github.com/mjkillough/cnx/tree/master/cnx-contrib #![recursion_limit = "256"] mod bar; pub mod text; pub mod widgets; mod xcb; use anyhow::Result; use tokio::runtime::Runtime; use tokio::task; use tokio_stream::{StreamExt, StreamMap}; use crate::bar::Bar; use crate::widgets::Widget; use crate::xcb::XcbEventStream; pub use bar::Position; /// The main object, used to instantiate an instance of Cnx. /// /// Widgets can be added using the [`add_widget()`] method. Once configured, /// the [`run()`] method will take ownership of the instance and run it until /// the process is killed or an error occurs. /// /// [`add_widget()`]: #method.add_widget /// [`run()`]: #method.run pub struct Cnx { position: Position, widgets: Vec<Box<dyn Widget>>, } impl Cnx { /// Creates a new `Cnx` instance. /// /// This creates a new `Cnx` instance at either the top or bottom of the /// screen, depending on the value of the [`Position`] enum. /// /// [`Position`]: enum.Position.html pub fn new(position: Position) -> Self { let widgets = Vec::new(); Self { position, widgets } } /// Adds a widget to the `Cnx` instance. /// /// Takes ownership of the [`Widget`] and adds it to the Cnx instance to /// the right of any existing widgets. /// /// [`Widget`]: widgets/trait.Widget.html pub fn add_widget<W>(&mut self, widget: W) where W: Widget +'static, { self.widgets.push(Box::new(widget)); } /// Runs the Cnx instance. /// /// This method takes ownership of the Cnx instance and runs it until either /// the process is terminated, or an internal error is returned. pub fn run(self) -> Result<()> {
ync fn run_inner(self) -> Result<()> { let mut bar = Bar::new(self.position)?; let mut widgets = StreamMap::with_capacity(self.widgets.len()); for widget in self.widgets { let idx = bar.add_content(Vec::new())?; widgets.insert(idx, widget.into_stream()?); } let mut event_stream = XcbEventStream::new(bar.connection().clone())?; task::spawn_local(async move { loop { tokio::select! { // Pass each XCB event to the Bar. Some(event) = event_stream.next() => { if let Err(err) = bar.process_event(event) { println!("Error processing XCB event: {}", err); } }, // Each time a widget yields new values, pass to the bar. // Ignore (but log) any errors from widgets. Some((idx, result)) = widgets.next() => { match result { Err(err) => println!("Error from widget {}: {}", idx, err), Ok(texts) => { if let Err(err) = bar.update_content(idx, texts) { println!("Error updating widget {}: {}", idx, err); } } } } } } }) .await?; Ok(()) } }
// Use a single-threaded event loop. We aren't interested in // performance too much, so don't mind if we block the loop // occasionally. We are using events to get woken up as // infrequently as possible (to save battery). let rt = Runtime::new()?; let local = task::LocalSet::new(); local.block_on(&rt, self.run_inner())?; Ok(()) } as
identifier_body
lib.rs
//! A simple X11 status bar for use with simple WMs. //! //! Cnx is written to be customisable, simple and fast. Where possible, it //! prefers to asynchronously wait for changes in the underlying data sources //! (and uses [`tokio`] to achieve this), rather than periodically //! calling out to external programs. //! //! # How to use //! //! Cnx is a library that allows you to make your own status bar. //! //! In normal usage, you will create a new binary project that relies on the //! `cnx` crate, and customize it through options passed to the main [`Cnx`] //! object and its widgets. (It's inspired by [`QTile`] and [`dwm`], in that the //! configuration is done entirely in code, allowing greater extensibility //! without needing complex configuration handling). //! //! An simple example of a binary using Cnx is: //! //! ```no_run //! //! use cnx::text::*; //! use cnx::widgets::*; //! use cnx::{Cnx, Position}; //! use anyhow::Result; //! //! fn main() -> Result<()> { //! let attr = Attributes { //! font: Font::new("Envy Code R 21"), //! fg_color: Color::white(), //! bg_color: None, //! padding: Padding::new(8.0, 8.0, 0.0, 0.0), //! }; //! //! let mut cnx = Cnx::new(Position::Top); //! cnx.add_widget(ActiveWindowTitle::new(attr.clone())); //! cnx.add_widget(Clock::new(attr.clone(), None)); //! cnx.run()?; //! //! Ok(()) //! } //! ``` //!
//! customizing Cnx are then limited). //! //! Before running Cnx, you'll need to make sure your system has the required //! dependencies, which are described in the [`README`][readme-deps]. //! //! # Built-in widgets //! //! There are currently these widgets available: //! //! - [`crate::widgets::ActiveWindowTitle`] — Shows the title ([`EWMH`]'s `_NET_WM_NAME`) for //! the currently focused window ([`EWMH`]'s `_NEW_ACTIVE_WINDOW`). //! - [`crate::widgets::Pager`] — Shows the WM's workspaces/groups, highlighting whichever is //! currently active. (Uses [`EWMH`]'s `_NET_DESKTOP_NAMES`, //! `_NET_NUMBER_OF_DESKTOPS` and `_NET_CURRENT_DESKTOP`). //! - [`crate::widgets::Clock`] — Shows the time. //! //! The cnx-contrib crate contains additional widgets: //! //! - **Sensors** — Periodically parses and displays the output of the //! sensors provided by the system. //! - **Volume** - Shows the current volume/mute status of the default output //! device. //! - **Battery** - Shows the remaining battery and charge status. //! - **Wireless** - Shows the wireless strength of your current network. //! - **CPU** - Shows the current CPU consumption //! - **Weather** - Shows the Weather information of your location //! - **Disk Usage** - Show the current usage of your monted filesystem //! //! The Sensors, Volume and Battery widgets require platform //! support. They currently support Linux (see dependencies below) and OpenBSD. //! Support for additional platforms should be possible. //! //! # Dependencies //! //! In addition to the Rust dependencies in `Cargo.toml`, Cnx also depends on //! these system libraries: //! //! - `xcb-util`: `xcb-ewmh` / `xcb-icccm` / `xcb-keysyms` //! - `x11-xcb` //! - `pango` //! - `cairo` //! - `pangocairo` //! //! Some widgets have additional dependencies on Linux: //! //! - **Volume** widget relies on `alsa-lib` //! - **Sensors** widget relies on [`lm_sensors`] being installed. //! - **Wireless** widget relies on `libiw-dev`. //! //! # Creating new widgets //! //! Cnx is designed such that thirdparty widgets can be written in //! external crates and used with the main [`Cnx`] instance. We have //! [`cnx-contrib`] crate which contains various additional //! widgets. You can also create new crates or add it to the existing //! [`cnx-contrib`] crate. //! //! The built-in [`widgets`] should give you some examples on which to base //! your work. //! //! [`tokio`]: https://tokio.rs/ //! [`QTile`]: http://www.qtile.org/ //! [`dwm`]: http://dwm.suckless.org/ //! [readme-deps]: https://github.com/mjkillough/cnx/blob/master/README.md#dependencies //! [`cnx-bin/src/main.rs`]: https://github.com/mjkillough/cnx/blob/master/cnx-bin/src/main.rs //! [`EWMH`]: https://specifications.freedesktop.org/wm-spec/wm-spec-latest.html //! [`lm_sensors`]: https://wiki.archlinux.org/index.php/lm_sensors //! [`cnx-contrib`]: https://github.com/mjkillough/cnx/tree/master/cnx-contrib #![recursion_limit = "256"] mod bar; pub mod text; pub mod widgets; mod xcb; use anyhow::Result; use tokio::runtime::Runtime; use tokio::task; use tokio_stream::{StreamExt, StreamMap}; use crate::bar::Bar; use crate::widgets::Widget; use crate::xcb::XcbEventStream; pub use bar::Position; /// The main object, used to instantiate an instance of Cnx. /// /// Widgets can be added using the [`add_widget()`] method. Once configured, /// the [`run()`] method will take ownership of the instance and run it until /// the process is killed or an error occurs. /// /// [`add_widget()`]: #method.add_widget /// [`run()`]: #method.run pub struct Cnx { position: Position, widgets: Vec<Box<dyn Widget>>, } impl Cnx { /// Creates a new `Cnx` instance. /// /// This creates a new `Cnx` instance at either the top or bottom of the /// screen, depending on the value of the [`Position`] enum. /// /// [`Position`]: enum.Position.html pub fn new(position: Position) -> Self { let widgets = Vec::new(); Self { position, widgets } } /// Adds a widget to the `Cnx` instance. /// /// Takes ownership of the [`Widget`] and adds it to the Cnx instance to /// the right of any existing widgets. /// /// [`Widget`]: widgets/trait.Widget.html pub fn add_widget<W>(&mut self, widget: W) where W: Widget +'static, { self.widgets.push(Box::new(widget)); } /// Runs the Cnx instance. /// /// This method takes ownership of the Cnx instance and runs it until either /// the process is terminated, or an internal error is returned. pub fn run(self) -> Result<()> { // Use a single-threaded event loop. We aren't interested in // performance too much, so don't mind if we block the loop // occasionally. We are using events to get woken up as // infrequently as possible (to save battery). let rt = Runtime::new()?; let local = task::LocalSet::new(); local.block_on(&rt, self.run_inner())?; Ok(()) } async fn run_inner(self) -> Result<()> { let mut bar = Bar::new(self.position)?; let mut widgets = StreamMap::with_capacity(self.widgets.len()); for widget in self.widgets { let idx = bar.add_content(Vec::new())?; widgets.insert(idx, widget.into_stream()?); } let mut event_stream = XcbEventStream::new(bar.connection().clone())?; task::spawn_local(async move { loop { tokio::select! { // Pass each XCB event to the Bar. Some(event) = event_stream.next() => { if let Err(err) = bar.process_event(event) { println!("Error processing XCB event: {}", err); } }, // Each time a widget yields new values, pass to the bar. // Ignore (but log) any errors from widgets. Some((idx, result)) = widgets.next() => { match result { Err(err) => println!("Error from widget {}: {}", idx, err), Ok(texts) => { if let Err(err) = bar.update_content(idx, texts) { println!("Error updating widget {}: {}", idx, err); } } } } } } }) .await?; Ok(()) } }
//! A more complex example is given in [`cnx-bin/src/main.rs`] alongside the project. //! (This is the default `[bin]` target for the crate, so you _could_ use it by //! either executing `cargo run` from the crate root, or even running `cargo //! install cnx; cnx`. However, neither of these are recommended as options for
random_line_split
lib.rs
//! A simple X11 status bar for use with simple WMs. //! //! Cnx is written to be customisable, simple and fast. Where possible, it //! prefers to asynchronously wait for changes in the underlying data sources //! (and uses [`tokio`] to achieve this), rather than periodically //! calling out to external programs. //! //! # How to use //! //! Cnx is a library that allows you to make your own status bar. //! //! In normal usage, you will create a new binary project that relies on the //! `cnx` crate, and customize it through options passed to the main [`Cnx`] //! object and its widgets. (It's inspired by [`QTile`] and [`dwm`], in that the //! configuration is done entirely in code, allowing greater extensibility //! without needing complex configuration handling). //! //! An simple example of a binary using Cnx is: //! //! ```no_run //! //! use cnx::text::*; //! use cnx::widgets::*; //! use cnx::{Cnx, Position}; //! use anyhow::Result; //! //! fn main() -> Result<()> { //! let attr = Attributes { //! font: Font::new("Envy Code R 21"), //! fg_color: Color::white(), //! bg_color: None, //! padding: Padding::new(8.0, 8.0, 0.0, 0.0), //! }; //! //! let mut cnx = Cnx::new(Position::Top); //! cnx.add_widget(ActiveWindowTitle::new(attr.clone())); //! cnx.add_widget(Clock::new(attr.clone(), None)); //! cnx.run()?; //! //! Ok(()) //! } //! ``` //! //! A more complex example is given in [`cnx-bin/src/main.rs`] alongside the project. //! (This is the default `[bin]` target for the crate, so you _could_ use it by //! either executing `cargo run` from the crate root, or even running `cargo //! install cnx; cnx`. However, neither of these are recommended as options for //! customizing Cnx are then limited). //! //! Before running Cnx, you'll need to make sure your system has the required //! dependencies, which are described in the [`README`][readme-deps]. //! //! # Built-in widgets //! //! There are currently these widgets available: //! //! - [`crate::widgets::ActiveWindowTitle`] — Shows the title ([`EWMH`]'s `_NET_WM_NAME`) for //! the currently focused window ([`EWMH`]'s `_NEW_ACTIVE_WINDOW`). //! - [`crate::widgets::Pager`] — Shows the WM's workspaces/groups, highlighting whichever is //! currently active. (Uses [`EWMH`]'s `_NET_DESKTOP_NAMES`, //! `_NET_NUMBER_OF_DESKTOPS` and `_NET_CURRENT_DESKTOP`). //! - [`crate::widgets::Clock`] — Shows the time. //! //! The cnx-contrib crate contains additional widgets: //! //! - **Sensors** — Periodically parses and displays the output of the //! sensors provided by the system. //! - **Volume** - Shows the current volume/mute status of the default output //! device. //! - **Battery** - Shows the remaining battery and charge status. //! - **Wireless** - Shows the wireless strength of your current network. //! - **CPU** - Shows the current CPU consumption //! - **Weather** - Shows the Weather information of your location //! - **Disk Usage** - Show the current usage of your monted filesystem //! //! The Sensors, Volume and Battery widgets require platform //! support. They currently support Linux (see dependencies below) and OpenBSD. //! Support for additional platforms should be possible. //! //! # Dependencies //! //! In addition to the Rust dependencies in `Cargo.toml`, Cnx also depends on //! these system libraries: //! //! - `xcb-util`: `xcb-ewmh` / `xcb-icccm` / `xcb-keysyms` //! - `x11-xcb` //! - `pango` //! - `cairo` //! - `pangocairo` //! //! Some widgets have additional dependencies on Linux: //! //! - **Volume** widget relies on `alsa-lib` //! - **Sensors** widget relies on [`lm_sensors`] being installed. //! - **Wireless** widget relies on `libiw-dev`. //! //! # Creating new widgets //! //! Cnx is designed such that thirdparty widgets can be written in //! external crates and used with the main [`Cnx`] instance. We have //! [`cnx-contrib`] crate which contains various additional //! widgets. You can also create new crates or add it to the existing //! [`cnx-contrib`] crate. //! //! The built-in [`widgets`] should give you some examples on which to base //! your work. //! //! [`tokio`]: https://tokio.rs/ //! [`QTile`]: http://www.qtile.org/ //! [`dwm`]: http://dwm.suckless.org/ //! [readme-deps]: https://github.com/mjkillough/cnx/blob/master/README.md#dependencies //! [`cnx-bin/src/main.rs`]: https://github.com/mjkillough/cnx/blob/master/cnx-bin/src/main.rs //! [`EWMH`]: https://specifications.freedesktop.org/wm-spec/wm-spec-latest.html //! [`lm_sensors`]: https://wiki.archlinux.org/index.php/lm_sensors //! [`cnx-contrib`]: https://github.com/mjkillough/cnx/tree/master/cnx-contrib #![recursion_limit = "256"] mod bar; pub mod text; pub mod widgets; mod xcb; use anyhow::Result; use tokio::runtime::Runtime; use tokio::task; use tokio_stream::{StreamExt, StreamMap}; use crate::bar::Bar; use crate::widgets::Widget; use crate::xcb::XcbEventStream; pub use bar::Position; /// The main object, used to instantiate an instance of Cnx. /// /// Widgets can be added using the [`add_widget()`] method. Once configured, /// the [`run()`] method will take ownership of the instance and run it until /// the process is killed or an error occurs. /// /// [`add_widget()`]: #method.add_widget /// [`run()`]: #method.run pub struct Cnx { position: Position, widgets: Vec<Box<dyn Widget>>, } impl Cnx { /// Creates a new `Cnx` instance. /// /// This creates a new `Cnx` instance at either the top or bottom of the /// screen, depending on the value of the [`Position`] enum. /// /// [`Position`]: enum.Position.html pub fn new(position: Position) -> Self { let widgets = Vec::new(); Self { position, widgets } } /// Adds a widget to the `Cnx` instance. /// /// Takes ownership of the [`Widget`] and adds it to the Cnx instance to /// the right of any existing widgets. /// /// [`Widget`]: widgets/trait.Widget.html pub fn add_widg
self, widget: W) where W: Widget +'static, { self.widgets.push(Box::new(widget)); } /// Runs the Cnx instance. /// /// This method takes ownership of the Cnx instance and runs it until either /// the process is terminated, or an internal error is returned. pub fn run(self) -> Result<()> { // Use a single-threaded event loop. We aren't interested in // performance too much, so don't mind if we block the loop // occasionally. We are using events to get woken up as // infrequently as possible (to save battery). let rt = Runtime::new()?; let local = task::LocalSet::new(); local.block_on(&rt, self.run_inner())?; Ok(()) } async fn run_inner(self) -> Result<()> { let mut bar = Bar::new(self.position)?; let mut widgets = StreamMap::with_capacity(self.widgets.len()); for widget in self.widgets { let idx = bar.add_content(Vec::new())?; widgets.insert(idx, widget.into_stream()?); } let mut event_stream = XcbEventStream::new(bar.connection().clone())?; task::spawn_local(async move { loop { tokio::select! { // Pass each XCB event to the Bar. Some(event) = event_stream.next() => { if let Err(err) = bar.process_event(event) { println!("Error processing XCB event: {}", err); } }, // Each time a widget yields new values, pass to the bar. // Ignore (but log) any errors from widgets. Some((idx, result)) = widgets.next() => { match result { Err(err) => println!("Error from widget {}: {}", idx, err), Ok(texts) => { if let Err(err) = bar.update_content(idx, texts) { println!("Error updating widget {}: {}", idx, err); } } } } } } }) .await?; Ok(()) } }
et<W>(&mut
identifier_name
inherited_table.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside", needs_conversion="True", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")} <%helpers:longhand name="border-spacing" animation_value_type="ComputedValue" boxed="True" spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing"> use app_units::Au; use std::fmt; use style_traits::ToCss; use values::specified::{AllowQuirks, Length}; pub mod computed_value { use app_units::Au; use properties::animated_properties::Animatable; #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToCss)] pub struct T { pub horizontal: Au, pub vertical: Au, } /// https://drafts.csswg.org/css-transitions/#animtype-simple-list impl Animatable for T { #[inline] fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { Ok(T { horizontal: try!(self.horizontal.add_weighted(&other.horizontal, self_portion, other_portion)), vertical: try!(self.vertical.add_weighted(&other.vertical, self_portion, other_portion)), }) } #[inline] fn compute_distance(&self, other: &Self) -> Result<f64, ()> { self.compute_squared_distance(other).map(|sd| sd.sqrt()) } #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) + try!(self.vertical.compute_squared_distance(&other.vertical))) } } } #[derive(Clone, Debug, HasViewportPercentage, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct SpecifiedValue { pub horizontal: Length, pub vertical: Option<Length>, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { try!(self.horizontal.to_css(dest)); if let Some(vertical) = self.vertical.as_ref()
Ok(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { let horizontal = self.horizontal.to_computed_value(context); computed_value::T { horizontal: horizontal, vertical: self.vertical.as_ref().map_or(horizontal, |v| v.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &computed_value::T) -> Self { SpecifiedValue { horizontal: ToComputedValue::from_computed_value(&computed.horizontal), vertical: Some(ToComputedValue::from_computed_value(&computed.vertical)), } } } pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue,ParseError<'i>> { let mut first = None; let mut second = None; match Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes) { Err(_) => (), Ok(length) => { first = Some(length); if let Ok(len) = input.try(|i| Length::parse_non_negative_quirky(context, i, AllowQuirks::Yes)) { second = Some(len); } } } match (first, second) { (None, None) => Err(StyleParseError::UnspecifiedError.into()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length, vertical: None, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: Some(vertical), }) } (None, Some(_)) => unreachable!(), } } </%helpers:longhand>
{ try!(dest.write_str(" ")); vertical.to_css(dest)?; }
conditional_block
inherited_table.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside", needs_conversion="True", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")} <%helpers:longhand name="border-spacing" animation_value_type="ComputedValue" boxed="True" spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing"> use app_units::Au; use std::fmt; use style_traits::ToCss; use values::specified::{AllowQuirks, Length}; pub mod computed_value { use app_units::Au; use properties::animated_properties::Animatable; #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToCss)] pub struct T { pub horizontal: Au, pub vertical: Au, } /// https://drafts.csswg.org/css-transitions/#animtype-simple-list impl Animatable for T { #[inline] fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { Ok(T { horizontal: try!(self.horizontal.add_weighted(&other.horizontal, self_portion, other_portion)), vertical: try!(self.vertical.add_weighted(&other.vertical, self_portion, other_portion)), }) } #[inline] fn compute_distance(&self, other: &Self) -> Result<f64, ()> { self.compute_squared_distance(other).map(|sd| sd.sqrt()) } #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) + try!(self.vertical.compute_squared_distance(&other.vertical))) } } } #[derive(Clone, Debug, HasViewportPercentage, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct SpecifiedValue { pub horizontal: Length, pub vertical: Option<Length>, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { try!(self.horizontal.to_css(dest)); if let Some(vertical) = self.vertical.as_ref() { try!(dest.write_str(" ")); vertical.to_css(dest)?; } Ok(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { let horizontal = self.horizontal.to_computed_value(context); computed_value::T { horizontal: horizontal, vertical: self.vertical.as_ref().map_or(horizontal, |v| v.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &computed_value::T) -> Self { SpecifiedValue { horizontal: ToComputedValue::from_computed_value(&computed.horizontal), vertical: Some(ToComputedValue::from_computed_value(&computed.vertical)),
} } } pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue,ParseError<'i>> { let mut first = None; let mut second = None; match Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes) { Err(_) => (), Ok(length) => { first = Some(length); if let Ok(len) = input.try(|i| Length::parse_non_negative_quirky(context, i, AllowQuirks::Yes)) { second = Some(len); } } } match (first, second) { (None, None) => Err(StyleParseError::UnspecifiedError.into()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length, vertical: None, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: Some(vertical), }) } (None, Some(_)) => unreachable!(), } } </%helpers:longhand>
random_line_split
inherited_table.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside", needs_conversion="True", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")} <%helpers:longhand name="border-spacing" animation_value_type="ComputedValue" boxed="True" spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing"> use app_units::Au; use std::fmt; use style_traits::ToCss; use values::specified::{AllowQuirks, Length}; pub mod computed_value { use app_units::Au; use properties::animated_properties::Animatable; #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToCss)] pub struct T { pub horizontal: Au, pub vertical: Au, } /// https://drafts.csswg.org/css-transitions/#animtype-simple-list impl Animatable for T { #[inline] fn
(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { Ok(T { horizontal: try!(self.horizontal.add_weighted(&other.horizontal, self_portion, other_portion)), vertical: try!(self.vertical.add_weighted(&other.vertical, self_portion, other_portion)), }) } #[inline] fn compute_distance(&self, other: &Self) -> Result<f64, ()> { self.compute_squared_distance(other).map(|sd| sd.sqrt()) } #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) + try!(self.vertical.compute_squared_distance(&other.vertical))) } } } #[derive(Clone, Debug, HasViewportPercentage, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct SpecifiedValue { pub horizontal: Length, pub vertical: Option<Length>, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { try!(self.horizontal.to_css(dest)); if let Some(vertical) = self.vertical.as_ref() { try!(dest.write_str(" ")); vertical.to_css(dest)?; } Ok(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { let horizontal = self.horizontal.to_computed_value(context); computed_value::T { horizontal: horizontal, vertical: self.vertical.as_ref().map_or(horizontal, |v| v.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &computed_value::T) -> Self { SpecifiedValue { horizontal: ToComputedValue::from_computed_value(&computed.horizontal), vertical: Some(ToComputedValue::from_computed_value(&computed.vertical)), } } } pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue,ParseError<'i>> { let mut first = None; let mut second = None; match Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes) { Err(_) => (), Ok(length) => { first = Some(length); if let Ok(len) = input.try(|i| Length::parse_non_negative_quirky(context, i, AllowQuirks::Yes)) { second = Some(len); } } } match (first, second) { (None, None) => Err(StyleParseError::UnspecifiedError.into()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length, vertical: None, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: Some(vertical), }) } (None, Some(_)) => unreachable!(), } } </%helpers:longhand>
add_weighted
identifier_name
inherited_table.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside", needs_conversion="True", animation_value_type="discrete", spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")} <%helpers:longhand name="border-spacing" animation_value_type="ComputedValue" boxed="True" spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing"> use app_units::Au; use std::fmt; use style_traits::ToCss; use values::specified::{AllowQuirks, Length}; pub mod computed_value { use app_units::Au; use properties::animated_properties::Animatable; #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToCss)] pub struct T { pub horizontal: Au, pub vertical: Au, } /// https://drafts.csswg.org/css-transitions/#animtype-simple-list impl Animatable for T { #[inline] fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { Ok(T { horizontal: try!(self.horizontal.add_weighted(&other.horizontal, self_portion, other_portion)), vertical: try!(self.vertical.add_weighted(&other.vertical, self_portion, other_portion)), }) } #[inline] fn compute_distance(&self, other: &Self) -> Result<f64, ()>
#[inline] fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) + try!(self.vertical.compute_squared_distance(&other.vertical))) } } } #[derive(Clone, Debug, HasViewportPercentage, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct SpecifiedValue { pub horizontal: Length, pub vertical: Option<Length>, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { try!(self.horizontal.to_css(dest)); if let Some(vertical) = self.vertical.as_ref() { try!(dest.write_str(" ")); vertical.to_css(dest)?; } Ok(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { let horizontal = self.horizontal.to_computed_value(context); computed_value::T { horizontal: horizontal, vertical: self.vertical.as_ref().map_or(horizontal, |v| v.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &computed_value::T) -> Self { SpecifiedValue { horizontal: ToComputedValue::from_computed_value(&computed.horizontal), vertical: Some(ToComputedValue::from_computed_value(&computed.vertical)), } } } pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue,ParseError<'i>> { let mut first = None; let mut second = None; match Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes) { Err(_) => (), Ok(length) => { first = Some(length); if let Ok(len) = input.try(|i| Length::parse_non_negative_quirky(context, i, AllowQuirks::Yes)) { second = Some(len); } } } match (first, second) { (None, None) => Err(StyleParseError::UnspecifiedError.into()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length, vertical: None, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: Some(vertical), }) } (None, Some(_)) => unreachable!(), } } </%helpers:longhand>
{ self.compute_squared_distance(other).map(|sd| sd.sqrt()) }
identifier_body
main.rs
// Copyright (c) 2013-2015 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. #![crate_name="calculator"] #![crate_type="bin"] extern crate capnp; extern crate capnp_rpc; pub mod calculator_capnp { include!(concat!(env!("OUT_DIR"), "/calculator_capnp.rs")); } pub mod client; pub mod server; pub fn main() { let args : Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main(), "server" => return server::main(), _ => (), } }
println!("usage: {} [client | server] ADDRESS", args[0]); }
random_line_split
main.rs
// Copyright (c) 2013-2015 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. #![crate_name="calculator"] #![crate_type="bin"] extern crate capnp; extern crate capnp_rpc; pub mod calculator_capnp { include!(concat!(env!("OUT_DIR"), "/calculator_capnp.rs")); } pub mod client; pub mod server; pub fn main()
{ let args : Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main(), "server" => return server::main(), _ => (), } } println!("usage: {} [client | server] ADDRESS", args[0]); }
identifier_body
main.rs
// Copyright (c) 2013-2015 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. #![crate_name="calculator"] #![crate_type="bin"] extern crate capnp; extern crate capnp_rpc; pub mod calculator_capnp { include!(concat!(env!("OUT_DIR"), "/calculator_capnp.rs")); } pub mod client; pub mod server; pub fn
() { let args : Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main(), "server" => return server::main(), _ => (), } } println!("usage: {} [client | server] ADDRESS", args[0]); }
main
identifier_name
timestamp.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::define_newtype;
use chrono::prelude::*; use lazy_static::lazy_static; use std::env; use std::time; define_newtype!(TimestampSecs, i64); define_newtype!(TimestampMillis, i64); impl TimestampSecs { pub fn now() -> Self { Self(elapsed().as_secs() as i64) } pub fn zero() -> Self { Self(0) } pub fn elapsed_secs(self) -> u64 { (Self::now().0 - self.0).max(0) as u64 } /// YYYY-mm-dd pub(crate) fn date_string(self, offset: FixedOffset) -> String { offset.timestamp(self.0, 0).format("%Y-%m-%d").to_string() } pub fn local_utc_offset(self) -> FixedOffset { *Local.timestamp(self.0, 0).offset() } pub fn datetime(self, utc_offset: FixedOffset) -> DateTime<FixedOffset> { utc_offset.timestamp(self.0, 0) } pub fn adding_secs(self, secs: i64) -> Self { TimestampSecs(self.0 + secs) } } impl TimestampMillis { pub fn now() -> Self { Self(elapsed().as_millis() as i64) } pub fn zero() -> Self { Self(0) } pub fn as_secs(self) -> TimestampSecs { TimestampSecs(self.0 / 1000) } } lazy_static! { pub(crate) static ref TESTING: bool = env::var("ANKI_TEST_MODE").is_ok(); } fn elapsed() -> time::Duration { if *TESTING { // shift clock around rollover time to accomodate Python tests that make bad assumptions. // we should update the tests in the future and remove this hack. let mut elap = time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap(); let now = Utc::now(); if now.hour() >= 2 && now.hour() < 4 { elap -= time::Duration::from_secs(60 * 60 * 2); } elap } else { time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap() } }
random_line_split
timestamp.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::define_newtype; use chrono::prelude::*; use lazy_static::lazy_static; use std::env; use std::time; define_newtype!(TimestampSecs, i64); define_newtype!(TimestampMillis, i64); impl TimestampSecs { pub fn now() -> Self { Self(elapsed().as_secs() as i64) } pub fn zero() -> Self { Self(0) } pub fn elapsed_secs(self) -> u64 { (Self::now().0 - self.0).max(0) as u64 } /// YYYY-mm-dd pub(crate) fn date_string(self, offset: FixedOffset) -> String { offset.timestamp(self.0, 0).format("%Y-%m-%d").to_string() } pub fn local_utc_offset(self) -> FixedOffset { *Local.timestamp(self.0, 0).offset() } pub fn datetime(self, utc_offset: FixedOffset) -> DateTime<FixedOffset> { utc_offset.timestamp(self.0, 0) } pub fn adding_secs(self, secs: i64) -> Self { TimestampSecs(self.0 + secs) } } impl TimestampMillis { pub fn now() -> Self { Self(elapsed().as_millis() as i64) } pub fn zero() -> Self { Self(0) } pub fn as_secs(self) -> TimestampSecs { TimestampSecs(self.0 / 1000) } } lazy_static! { pub(crate) static ref TESTING: bool = env::var("ANKI_TEST_MODE").is_ok(); } fn elapsed() -> time::Duration
{ if *TESTING { // shift clock around rollover time to accomodate Python tests that make bad assumptions. // we should update the tests in the future and remove this hack. let mut elap = time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap(); let now = Utc::now(); if now.hour() >= 2 && now.hour() < 4 { elap -= time::Duration::from_secs(60 * 60 * 2); } elap } else { time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap() } }
identifier_body
timestamp.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::define_newtype; use chrono::prelude::*; use lazy_static::lazy_static; use std::env; use std::time; define_newtype!(TimestampSecs, i64); define_newtype!(TimestampMillis, i64); impl TimestampSecs { pub fn now() -> Self { Self(elapsed().as_secs() as i64) } pub fn zero() -> Self { Self(0) } pub fn elapsed_secs(self) -> u64 { (Self::now().0 - self.0).max(0) as u64 } /// YYYY-mm-dd pub(crate) fn date_string(self, offset: FixedOffset) -> String { offset.timestamp(self.0, 0).format("%Y-%m-%d").to_string() } pub fn local_utc_offset(self) -> FixedOffset { *Local.timestamp(self.0, 0).offset() } pub fn datetime(self, utc_offset: FixedOffset) -> DateTime<FixedOffset> { utc_offset.timestamp(self.0, 0) } pub fn adding_secs(self, secs: i64) -> Self { TimestampSecs(self.0 + secs) } } impl TimestampMillis { pub fn now() -> Self { Self(elapsed().as_millis() as i64) } pub fn zero() -> Self { Self(0) } pub fn as_secs(self) -> TimestampSecs { TimestampSecs(self.0 / 1000) } } lazy_static! { pub(crate) static ref TESTING: bool = env::var("ANKI_TEST_MODE").is_ok(); } fn elapsed() -> time::Duration { if *TESTING
else { time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap() } }
{ // shift clock around rollover time to accomodate Python tests that make bad assumptions. // we should update the tests in the future and remove this hack. let mut elap = time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap(); let now = Utc::now(); if now.hour() >= 2 && now.hour() < 4 { elap -= time::Duration::from_secs(60 * 60 * 2); } elap }
conditional_block
timestamp.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::define_newtype; use chrono::prelude::*; use lazy_static::lazy_static; use std::env; use std::time; define_newtype!(TimestampSecs, i64); define_newtype!(TimestampMillis, i64); impl TimestampSecs { pub fn now() -> Self { Self(elapsed().as_secs() as i64) } pub fn
() -> Self { Self(0) } pub fn elapsed_secs(self) -> u64 { (Self::now().0 - self.0).max(0) as u64 } /// YYYY-mm-dd pub(crate) fn date_string(self, offset: FixedOffset) -> String { offset.timestamp(self.0, 0).format("%Y-%m-%d").to_string() } pub fn local_utc_offset(self) -> FixedOffset { *Local.timestamp(self.0, 0).offset() } pub fn datetime(self, utc_offset: FixedOffset) -> DateTime<FixedOffset> { utc_offset.timestamp(self.0, 0) } pub fn adding_secs(self, secs: i64) -> Self { TimestampSecs(self.0 + secs) } } impl TimestampMillis { pub fn now() -> Self { Self(elapsed().as_millis() as i64) } pub fn zero() -> Self { Self(0) } pub fn as_secs(self) -> TimestampSecs { TimestampSecs(self.0 / 1000) } } lazy_static! { pub(crate) static ref TESTING: bool = env::var("ANKI_TEST_MODE").is_ok(); } fn elapsed() -> time::Duration { if *TESTING { // shift clock around rollover time to accomodate Python tests that make bad assumptions. // we should update the tests in the future and remove this hack. let mut elap = time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap(); let now = Utc::now(); if now.hour() >= 2 && now.hour() < 4 { elap -= time::Duration::from_secs(60 * 60 * 2); } elap } else { time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap() } }
zero
identifier_name
comm.rs
// -*- rust -*- // 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
// option. This file may not be copied, modified, or distributed // except according to those terms. use core::comm::*; pub fn main() { let (p, ch) = stream(); let t = task::spawn(|| child(&ch) ); let y = p.recv(); error!("received"); error!(y); assert!((y == 10)); } fn child(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
comm.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::comm::*; pub fn main() { let (p, ch) = stream(); let t = task::spawn(|| child(&ch) ); let y = p.recv(); error!("received"); error!(y); assert!((y == 10)); } fn
(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
child
identifier_name
comm.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::comm::*; pub fn main()
fn child(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
{ let (p, ch) = stream(); let t = task::spawn(|| child(&ch) ); let y = p.recv(); error!("received"); error!(y); assert!((y == 10)); }
identifier_body
shell.rs
ArgsBuilder, Args}; use kernel::collections::{Vec, String}; use kernel::alloc::Box; use core::fmt::{self, Display}; /* const LOGO: &'static str = " . ;' .. '. .cc. x0kk. .Oo .xc c,;: .OO. xO. .Oo 'dkxoc.d. .o'.clccc. ;' ;' kKdodd0k..Oo .kl ,k, 'x;,dc;,'. .. . cXl .o0o.Oo .ko ,k; ;x; ..ld. c:. .:: oO. dx xc cddo, :dolcd' ;lcclc, ;c;,',':c' .cc, :cc. .ccl; cll: 'dl ;o; .. :odxc dxdd; kK0d cOkO .''. ok ... . . ..... ... ,xkO0o k00Ox. .Kx.k0O':O, 'x' 'k:lookol.oxcx;. ;d. ,d',oc.'ll:.'l: .k0KKKd OXKK0k ,Xl l O: xOoccccc ck. ox '' ;d. ,d',o. :l. :l d0KKXXd OXXXKKl ;Xl Oc 'kd; :k ox 'dc 'd',o. :l. :l ;x0KXXO; cKXXKKx, xl. 0c. lcccc :l ox 'cccc' 0 :l. :l .lxOKKXo kXKK0ko. "; */ const HELP: &'static str = "Available Commands: echo [string...] clear eval <lhs> <op> <rhs> blink [rate] stop uptime rocket [timer] uname exit help [cmd]"; const ECHO_HELP: &'static str = "Echo a string to the terminal"; const CLEAR_HELP: &'static str = "Clear the terminal"; const EVAL_HELP: &'static str = "Evaluate an expression of the form x <op> y"; const BLINK_HELP: &'static str = "Blink the LED at the given rate in milliseconds"; const STOP_HELP: &'static str = "Stop blinking the LED"; const UPTIME_HELP: &'static str = "Display how long the system has been running as HH:MM:SS"; //const ROCKET_HELP: &'static str = "Deploys a rocket?"; const UNAME_HELP: &'static str = "Displays system information"; const EXIT_HELP: &'static str = "Exit the shell"; const HELP_HELP: &'static str = "Display available commands or more information about a certain command"; enum ReadError { UnclosedString, } impl Display for ReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let msg = match *self { ReadError::UnclosedString => "unclosed string found", }; write!(f, "{}", msg) } } enum Command<'a> { Echo, Clear, Eval, Blink, Stop, Uptime, //Rocket, Uname, Exit, Help, Invalid(&'a str), } impl<'a> Command<'a> { fn help_msg(&self) -> (&'static str, &str) { match *self { Command::Echo => (ECHO_HELP, ""), Command::Clear => (CLEAR_HELP, ""), Command::Eval => (EVAL_HELP, ""), Command::Blink => (BLINK_HELP, ""), Command::Stop => (STOP_HELP, ""), Command::Uptime => (UPTIME_HELP, ""), //Command::Rocket => (ROCKET_HELP, ""), Command::Uname => (UNAME_HELP, ""), Command::Exit => (EXIT_HELP, ""), Command::Help => (HELP_HELP, ""), Command::Invalid(invalid) => ("Unknown command: ", invalid), } } } impl<'a> From<&'a str> for Command<'a> { fn from(string: &'a str) -> Command<'a> { match string { "echo" => Command::Echo, "clear" => Command::Clear, "eval" => Command::Eval, "blink" => Command::Blink, "stop" => Command::Stop, "uptime" => Command::Uptime, //"rocket" => Command::Rocket, "uname"=> Command::Uname, "exit" => Command::Exit, "help" => Command::Help, invalid => Command::Invalid(invalid), } } } #[derive(Copy, Clone, PartialEq)] enum Token { Number(isize), Op(Operator), LeftParen, RightParen, EOF, } #[derive(Copy, Clone, Debug)] enum LexError { InvalidToken } struct Lexer; impl Lexer { fn lex(string: Vec<&str>) -> Result<Vec<Token>, LexError> { let mut tokens = Vec::new(); for thing in string { match thing { "+" => tokens.push(Token::Op(Operator::Add)), "-" => tokens.push(Token::Op(Operator::Sub)), "*" => tokens.push(Token::Op(Operator::Mul)), "/" => tokens.push(Token::Op(Operator::Div)), "(" => tokens.push(Token::LeftParen), ")" => tokens.push(Token::RightParen), literal => { if let Ok(num) = literal.parse::<isize>() { tokens.push(Token::Number(num)); } else { return Err(LexError::InvalidToken); } } } } tokens.push(Token::EOF); Ok(tokens) } } #[derive(Copy, Clone, Debug)] enum ParseError { UnexpectedToken, UnmatchedParens, InvalidOperator, } // Grammar: // // expression := term // term := factor ( ( "-" | "+" ) factor )* // factor := primary ( ( "*" | "/" ) primary )* // primary := NUMBER | "(" expression ")" struct Parser { tokens: Vec<Token>, current: usize, } impl Parser { fn new(tokens: Vec<Token>) -> Self { Parser { tokens: tokens, current: 0, } } fn matches(&mut self, op: Operator) -> bool { if self.is_at_end() { false } else { match self.peek() { Token::Op(operator) if op == operator => { self.advance(); true }, _ => false } } } fn advance(&mut self) -> Token { if!self.is_at_end() { self.current += 1; } self.previous() } fn is_at_end(&self) -> bool { self.peek() == Token::EOF } fn peek(&self) -> Token
fn previous(&self) -> Token { self.tokens[self.current - 1] } fn parse(&mut self) -> Result<Expr, ParseError> { self.expression() } fn expression(&mut self) -> Result<Expr, ParseError> { self.term() } fn term(&mut self) -> Result<Expr, ParseError> { let mut expr = self.factor()?; while self.matches(Operator::Add) || self.matches(Operator::Sub) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::InvalidOperator); }; let right = self.factor()?; expr = Expr::Op(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn factor(&mut self) -> Result<Expr, ParseError> { let mut expr = self.primary()?; while self.matches(Operator::Mul) || self.matches(Operator::Div) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::InvalidOperator); }; let right = self.primary()?; expr = Expr::Op(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn primary(&mut self) -> Result<Expr, ParseError> { match self.advance() { Token::Number(num) => Ok(Expr::Val(num)), Token::LeftParen => { let expr = self.expression()?; if let Token::RightParen = self.advance() { Ok(expr) } else { Err(ParseError::UnmatchedParens) } }, _ => Err(ParseError::UnexpectedToken), } } } enum Expr { Op(Box<Expr>, Operator, Box<Expr>), Val(isize), } impl Expr { fn eval(&self) -> isize { match *self { Expr::Op(ref lhs, ref op, ref rhs) => op.apply(lhs.eval(), rhs.eval()), Expr::Val(x) => x, } } } #[derive(Copy, Clone, PartialEq)] enum Operator { Add, Sub, Mul, Div, } impl Operator { fn apply(&self, lhs: isize, rhs: isize) -> isize { match *self { Operator::Add => lhs + rhs, Operator::Sub => lhs - rhs, Operator::Mul => lhs * rhs, Operator::Div => lhs / rhs, } } } pub fn shell(_args: &mut Args) { let mut blink_handle: Option<TaskHandle> = None; loop { print!(" > "); let line = match read_line() { Ok(line) => line, Err(err) => { println!("Error: {}", err); continue; }, }; let mut words: Vec<&str> = line.iter().map(|s| s.as_ref()).collect(); //let mut words: Vec<&str> = line.split(' ').collect(); if words.len() > 0 { match Command::from(words.remove(0)) { Command::Echo => { for word in words { print!("{} ", word); } println!(""); }, Command::Clear => { // ANSI ESC sequence to clear screen and put cursor at at top of terminal. print!("\x1b[2J") }, Command::Eval => { eval(words); }, Command::Blink => { let rate: usize = if words.len() > 0 { words[0].parse::<usize>().unwrap_or(100) } else { 100 }; if let Some(mut handle) = blink_handle.take() { handle.destroy(); turn_off_led(); } let mut args = ArgsBuilder::with_capacity(1); args.add_num(rate); blink_handle = Some(kernel::syscall::new_task(blink, args.finalize(), 1024, Priority::Low, "blink")); }, Command::Stop => { if let Some(mut handle) = blink_handle.take() { handle.destroy(); turn_off_led(); } }, Command::Uptime => { let hms = uptime(); println!("{:02}:{:02}:{:02}", hms.0, hms.1, hms.2); }, /* Command::Rocket => { let timer = if words.len() > 0 { words[0].parse::<isize>().unwrap_or(5) } else { 5 }; rocket(timer); }, */ Command::Uname => { //println!("{}\n", LOGO); //Find more info and place it here println!("AltOS Rust"); }, Command::Exit => kernel::syscall::exit(), Command::Help => { if words.len() > 0 { let command = Command::from(words[0]); let msg = command.help_msg(); println!("{}{}", msg.0, msg.1); } else { println!("{}", HELP); } } Command::Invalid(invalid) => println!("Unknown command: '{}'", invalid), } } } } fn eval(args: Vec<&str>) { let tokens = match Lexer::lex(args) { Ok(tokens) => tokens, Err(err) => { println!("Lexing failed: {:?}", err); return; }, }; let mut parser = Parser::new(tokens); match parser.parse() { Ok(expr) => println!("Result: {}", expr.eval()), Err(err) => println!("Parsing failed: {:?}", err), } } fn turn_on_led() { use cortex_m0::peripheral::gpio::{self, Port}; let mut pb3 = Port::new(3, gpio::Group::B); pb3.set(); } fn turn_off_led() { use cortex_m0::peripheral::gpio::{self, Port}; let mut pb3 = Port::new(3, gpio::Group::B); pb3.reset(); } fn blink(args: &mut Args) { let rate = args.pop_num(); loop { turn_on_led(); delay_ms(rate); turn_off_led(); delay_ms(rate); } } fn get_and_echo_char() -> Option<char> { io::poll_char().map(|ch| { print!("{}", ch as char); // 8 is \b, but Rust doesn't recognize \b? if ch == b'\x08' { print!(" "); print!("{}", ch as char); } ch as char }) } fn read_line() -> Result<Vec<String>, ReadError> { let mut line = Vec::new(); let mut word = String::new(); let mut in_string = false; loop { if let Some(ch) = get_and_echo_char() { match ch { '\n' | '\r' => { if in_string { return Err(ReadError::UnclosedString); } line.push(word); return Ok(line.into_iter().filter(|word|!word.is_empty()).map(|word| word.replace("\"", "")).collect()); }, '\x08' => { match word.pop() { Some(ch) if ch == '"' => in_string =!in_string, Some(_) => {}, None => match line.pop() { Some(old_word) => word = old_word, None => print!(" "), }, } }, '' => { if!in_string { line.push(word); word = String::new(); } else { word.push(' '); } }, '"' => { word.push('"'); in_string =!in_string; }, _ => word.push(ch), } } } } fn uptime() -> (usize, usize, usize) { let curr_time = now(); let mut minutes = curr_time.sec / 60; let hours = minutes / 60; let seconds = curr_time.sec % 60; minutes = minutes % 60; (hours, minutes, seconds) } /* fn rocket(mut timer: isize) { let mut offset: isize = 15; let stationary: isize = offset; let counter = timer + offset * 2; let mut k = 0; if timer < 0 { timer = 5; } let mut rocket = String::new(); while k < counter { rocket.clear(); print!("\x1b[2J"); newline_offset(&mut rocket, offset); build_rocket_part(&mut rocket, " /\\\n", offset); build_rocket_part(&mut rocket, " / \\\n", offset+1); build_rocket_part(&mut rocket, " / \\\n", offset+2); build_rocket_part(&mut rocket, " | A |\n", offset+3); build_rocket_part(&mut rocket, " | L |\n", offset+4); build_rocket_part(&mut rocket, " /| T |\\\n", offset+5); build_rocket_part(&mut rocket, " / | O | \\\n", offset+6); build_rocket_part(&mut rocket, " ^^| S |^^\n", offset+7); build_rocket_part(&mut
{ self.tokens[self.current] }
identifier_body
shell.rs
::{ArgsBuilder, Args}; use kernel::collections::{Vec, String}; use kernel::alloc::Box; use core::fmt::{self, Display}; /* const LOGO: &'static str = " . ;' .. '. .cc. x0kk. .Oo .xc c,;: .OO. xO. .Oo 'dkxoc.d. .o'.clccc. ;' ;' kKdodd0k..Oo .kl ,k, 'x;,dc;,'. .. . cXl .o0o.Oo .ko ,k; ;x; ..ld. c:. .:: oO. dx xc cddo, :dolcd' ;lcclc, ;c;,',':c' .cc, :cc. .ccl; cll: 'dl ;o; .. :odxc dxdd; kK0d cOkO .''. ok ... . . ..... ... ,xkO0o k00Ox. .Kx.k0O':O, 'x' 'k:lookol.oxcx;. ;d. ,d',oc.'ll:.'l: .k0KKKd OXKK0k ,Xl l O: xOoccccc ck. ox '' ;d. ,d',o. :l. :l d0KKXXd OXXXKKl ;Xl Oc 'kd; :k ox 'dc 'd',o. :l. :l ;x0KXXO; cKXXKKx, xl. 0c. lcccc :l ox 'cccc' 0 :l. :l .lxOKKXo kXKK0ko. "; */ const HELP: &'static str = "Available Commands: echo [string...] clear eval <lhs> <op> <rhs> blink [rate] stop uptime rocket [timer] uname exit help [cmd]"; const ECHO_HELP: &'static str = "Echo a string to the terminal"; const CLEAR_HELP: &'static str = "Clear the terminal"; const EVAL_HELP: &'static str = "Evaluate an expression of the form x <op> y"; const BLINK_HELP: &'static str = "Blink the LED at the given rate in milliseconds"; const STOP_HELP: &'static str = "Stop blinking the LED"; const UPTIME_HELP: &'static str = "Display how long the system has been running as HH:MM:SS"; //const ROCKET_HELP: &'static str = "Deploys a rocket?";
enum ReadError { UnclosedString, } impl Display for ReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let msg = match *self { ReadError::UnclosedString => "unclosed string found", }; write!(f, "{}", msg) } } enum Command<'a> { Echo, Clear, Eval, Blink, Stop, Uptime, //Rocket, Uname, Exit, Help, Invalid(&'a str), } impl<'a> Command<'a> { fn help_msg(&self) -> (&'static str, &str) { match *self { Command::Echo => (ECHO_HELP, ""), Command::Clear => (CLEAR_HELP, ""), Command::Eval => (EVAL_HELP, ""), Command::Blink => (BLINK_HELP, ""), Command::Stop => (STOP_HELP, ""), Command::Uptime => (UPTIME_HELP, ""), //Command::Rocket => (ROCKET_HELP, ""), Command::Uname => (UNAME_HELP, ""), Command::Exit => (EXIT_HELP, ""), Command::Help => (HELP_HELP, ""), Command::Invalid(invalid) => ("Unknown command: ", invalid), } } } impl<'a> From<&'a str> for Command<'a> { fn from(string: &'a str) -> Command<'a> { match string { "echo" => Command::Echo, "clear" => Command::Clear, "eval" => Command::Eval, "blink" => Command::Blink, "stop" => Command::Stop, "uptime" => Command::Uptime, //"rocket" => Command::Rocket, "uname"=> Command::Uname, "exit" => Command::Exit, "help" => Command::Help, invalid => Command::Invalid(invalid), } } } #[derive(Copy, Clone, PartialEq)] enum Token { Number(isize), Op(Operator), LeftParen, RightParen, EOF, } #[derive(Copy, Clone, Debug)] enum LexError { InvalidToken } struct Lexer; impl Lexer { fn lex(string: Vec<&str>) -> Result<Vec<Token>, LexError> { let mut tokens = Vec::new(); for thing in string { match thing { "+" => tokens.push(Token::Op(Operator::Add)), "-" => tokens.push(Token::Op(Operator::Sub)), "*" => tokens.push(Token::Op(Operator::Mul)), "/" => tokens.push(Token::Op(Operator::Div)), "(" => tokens.push(Token::LeftParen), ")" => tokens.push(Token::RightParen), literal => { if let Ok(num) = literal.parse::<isize>() { tokens.push(Token::Number(num)); } else { return Err(LexError::InvalidToken); } } } } tokens.push(Token::EOF); Ok(tokens) } } #[derive(Copy, Clone, Debug)] enum ParseError { UnexpectedToken, UnmatchedParens, InvalidOperator, } // Grammar: // // expression := term // term := factor ( ( "-" | "+" ) factor )* // factor := primary ( ( "*" | "/" ) primary )* // primary := NUMBER | "(" expression ")" struct Parser { tokens: Vec<Token>, current: usize, } impl Parser { fn new(tokens: Vec<Token>) -> Self { Parser { tokens: tokens, current: 0, } } fn matches(&mut self, op: Operator) -> bool { if self.is_at_end() { false } else { match self.peek() { Token::Op(operator) if op == operator => { self.advance(); true }, _ => false } } } fn advance(&mut self) -> Token { if!self.is_at_end() { self.current += 1; } self.previous() } fn is_at_end(&self) -> bool { self.peek() == Token::EOF } fn peek(&self) -> Token { self.tokens[self.current] } fn previous(&self) -> Token { self.tokens[self.current - 1] } fn parse(&mut self) -> Result<Expr, ParseError> { self.expression() } fn expression(&mut self) -> Result<Expr, ParseError> { self.term() } fn term(&mut self) -> Result<Expr, ParseError> { let mut expr = self.factor()?; while self.matches(Operator::Add) || self.matches(Operator::Sub) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::InvalidOperator); }; let right = self.factor()?; expr = Expr::Op(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn factor(&mut self) -> Result<Expr, ParseError> { let mut expr = self.primary()?; while self.matches(Operator::Mul) || self.matches(Operator::Div) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::InvalidOperator); }; let right = self.primary()?; expr = Expr::Op(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn primary(&mut self) -> Result<Expr, ParseError> { match self.advance() { Token::Number(num) => Ok(Expr::Val(num)), Token::LeftParen => { let expr = self.expression()?; if let Token::RightParen = self.advance() { Ok(expr) } else { Err(ParseError::UnmatchedParens) } }, _ => Err(ParseError::UnexpectedToken), } } } enum Expr { Op(Box<Expr>, Operator, Box<Expr>), Val(isize), } impl Expr { fn eval(&self) -> isize { match *self { Expr::Op(ref lhs, ref op, ref rhs) => op.apply(lhs.eval(), rhs.eval()), Expr::Val(x) => x, } } } #[derive(Copy, Clone, PartialEq)] enum Operator { Add, Sub, Mul, Div, } impl Operator { fn apply(&self, lhs: isize, rhs: isize) -> isize { match *self { Operator::Add => lhs + rhs, Operator::Sub => lhs - rhs, Operator::Mul => lhs * rhs, Operator::Div => lhs / rhs, } } } pub fn shell(_args: &mut Args) { let mut blink_handle: Option<TaskHandle> = None; loop { print!(" > "); let line = match read_line() { Ok(line) => line, Err(err) => { println!("Error: {}", err); continue; }, }; let mut words: Vec<&str> = line.iter().map(|s| s.as_ref()).collect(); //let mut words: Vec<&str> = line.split(' ').collect(); if words.len() > 0 { match Command::from(words.remove(0)) { Command::Echo => { for word in words { print!("{} ", word); } println!(""); }, Command::Clear => { // ANSI ESC sequence to clear screen and put cursor at at top of terminal. print!("\x1b[2J") }, Command::Eval => { eval(words); }, Command::Blink => { let rate: usize = if words.len() > 0 { words[0].parse::<usize>().unwrap_or(100) } else { 100 }; if let Some(mut handle) = blink_handle.take() { handle.destroy(); turn_off_led(); } let mut args = ArgsBuilder::with_capacity(1); args.add_num(rate); blink_handle = Some(kernel::syscall::new_task(blink, args.finalize(), 1024, Priority::Low, "blink")); }, Command::Stop => { if let Some(mut handle) = blink_handle.take() { handle.destroy(); turn_off_led(); } }, Command::Uptime => { let hms = uptime(); println!("{:02}:{:02}:{:02}", hms.0, hms.1, hms.2); }, /* Command::Rocket => { let timer = if words.len() > 0 { words[0].parse::<isize>().unwrap_or(5) } else { 5 }; rocket(timer); }, */ Command::Uname => { //println!("{}\n", LOGO); //Find more info and place it here println!("AltOS Rust"); }, Command::Exit => kernel::syscall::exit(), Command::Help => { if words.len() > 0 { let command = Command::from(words[0]); let msg = command.help_msg(); println!("{}{}", msg.0, msg.1); } else { println!("{}", HELP); } } Command::Invalid(invalid) => println!("Unknown command: '{}'", invalid), } } } } fn eval(args: Vec<&str>) { let tokens = match Lexer::lex(args) { Ok(tokens) => tokens, Err(err) => { println!("Lexing failed: {:?}", err); return; }, }; let mut parser = Parser::new(tokens); match parser.parse() { Ok(expr) => println!("Result: {}", expr.eval()), Err(err) => println!("Parsing failed: {:?}", err), } } fn turn_on_led() { use cortex_m0::peripheral::gpio::{self, Port}; let mut pb3 = Port::new(3, gpio::Group::B); pb3.set(); } fn turn_off_led() { use cortex_m0::peripheral::gpio::{self, Port}; let mut pb3 = Port::new(3, gpio::Group::B); pb3.reset(); } fn blink(args: &mut Args) { let rate = args.pop_num(); loop { turn_on_led(); delay_ms(rate); turn_off_led(); delay_ms(rate); } } fn get_and_echo_char() -> Option<char> { io::poll_char().map(|ch| { print!("{}", ch as char); // 8 is \b, but Rust doesn't recognize \b? if ch == b'\x08' { print!(" "); print!("{}", ch as char); } ch as char }) } fn read_line() -> Result<Vec<String>, ReadError> { let mut line = Vec::new(); let mut word = String::new(); let mut in_string = false; loop { if let Some(ch) = get_and_echo_char() { match ch { '\n' | '\r' => { if in_string { return Err(ReadError::UnclosedString); } line.push(word); return Ok(line.into_iter().filter(|word|!word.is_empty()).map(|word| word.replace("\"", "")).collect()); }, '\x08' => { match word.pop() { Some(ch) if ch == '"' => in_string =!in_string, Some(_) => {}, None => match line.pop() { Some(old_word) => word = old_word, None => print!(" "), }, } }, '' => { if!in_string { line.push(word); word = String::new(); } else { word.push(' '); } }, '"' => { word.push('"'); in_string =!in_string; }, _ => word.push(ch), } } } } fn uptime() -> (usize, usize, usize) { let curr_time = now(); let mut minutes = curr_time.sec / 60; let hours = minutes / 60; let seconds = curr_time.sec % 60; minutes = minutes % 60; (hours, minutes, seconds) } /* fn rocket(mut timer: isize) { let mut offset: isize = 15; let stationary: isize = offset; let counter = timer + offset * 2; let mut k = 0; if timer < 0 { timer = 5; } let mut rocket = String::new(); while k < counter { rocket.clear(); print!("\x1b[2J"); newline_offset(&mut rocket, offset); build_rocket_part(&mut rocket, " /\\\n", offset); build_rocket_part(&mut rocket, " / \\\n", offset+1); build_rocket_part(&mut rocket, " / \\\n", offset+2); build_rocket_part(&mut rocket, " | A |\n", offset+3); build_rocket_part(&mut rocket, " | L |\n", offset+4); build_rocket_part(&mut rocket, " /| T |\\\n", offset+5); build_rocket_part(&mut rocket, " / | O | \\\n", offset+6); build_rocket_part(&mut rocket, " ^^| S |^^\n", offset+7); build_rocket_part(&mut rocket,
const UNAME_HELP: &'static str = "Displays system information"; const EXIT_HELP: &'static str = "Exit the shell"; const HELP_HELP: &'static str = "Display available commands or more information about a certain command";
random_line_split
shell.rs
ArgsBuilder, Args}; use kernel::collections::{Vec, String}; use kernel::alloc::Box; use core::fmt::{self, Display}; /* const LOGO: &'static str = " . ;' .. '. .cc. x0kk. .Oo .xc c,;: .OO. xO. .Oo 'dkxoc.d. .o'.clccc. ;' ;' kKdodd0k..Oo .kl ,k, 'x;,dc;,'. .. . cXl .o0o.Oo .ko ,k; ;x; ..ld. c:. .:: oO. dx xc cddo, :dolcd' ;lcclc, ;c;,',':c' .cc, :cc. .ccl; cll: 'dl ;o; .. :odxc dxdd; kK0d cOkO .''. ok ... . . ..... ... ,xkO0o k00Ox. .Kx.k0O':O, 'x' 'k:lookol.oxcx;. ;d. ,d',oc.'ll:.'l: .k0KKKd OXKK0k ,Xl l O: xOoccccc ck. ox '' ;d. ,d',o. :l. :l d0KKXXd OXXXKKl ;Xl Oc 'kd; :k ox 'dc 'd',o. :l. :l ;x0KXXO; cKXXKKx, xl. 0c. lcccc :l ox 'cccc' 0 :l. :l .lxOKKXo kXKK0ko. "; */ const HELP: &'static str = "Available Commands: echo [string...] clear eval <lhs> <op> <rhs> blink [rate] stop uptime rocket [timer] uname exit help [cmd]"; const ECHO_HELP: &'static str = "Echo a string to the terminal"; const CLEAR_HELP: &'static str = "Clear the terminal"; const EVAL_HELP: &'static str = "Evaluate an expression of the form x <op> y"; const BLINK_HELP: &'static str = "Blink the LED at the given rate in milliseconds"; const STOP_HELP: &'static str = "Stop blinking the LED"; const UPTIME_HELP: &'static str = "Display how long the system has been running as HH:MM:SS"; //const ROCKET_HELP: &'static str = "Deploys a rocket?"; const UNAME_HELP: &'static str = "Displays system information"; const EXIT_HELP: &'static str = "Exit the shell"; const HELP_HELP: &'static str = "Display available commands or more information about a certain command"; enum ReadError { UnclosedString, } impl Display for ReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let msg = match *self { ReadError::UnclosedString => "unclosed string found", }; write!(f, "{}", msg) } } enum Command<'a> { Echo, Clear, Eval, Blink, Stop, Uptime, //Rocket, Uname, Exit, Help, Invalid(&'a str), } impl<'a> Command<'a> { fn help_msg(&self) -> (&'static str, &str) { match *self { Command::Echo => (ECHO_HELP, ""), Command::Clear => (CLEAR_HELP, ""), Command::Eval => (EVAL_HELP, ""), Command::Blink => (BLINK_HELP, ""), Command::Stop => (STOP_HELP, ""), Command::Uptime => (UPTIME_HELP, ""), //Command::Rocket => (ROCKET_HELP, ""), Command::Uname => (UNAME_HELP, ""), Command::Exit => (EXIT_HELP, ""), Command::Help => (HELP_HELP, ""), Command::Invalid(invalid) => ("Unknown command: ", invalid), } } } impl<'a> From<&'a str> for Command<'a> { fn from(string: &'a str) -> Command<'a> { match string { "echo" => Command::Echo, "clear" => Command::Clear, "eval" => Command::Eval, "blink" => Command::Blink, "stop" => Command::Stop, "uptime" => Command::Uptime, //"rocket" => Command::Rocket, "uname"=> Command::Uname, "exit" => Command::Exit, "help" => Command::Help, invalid => Command::Invalid(invalid), } } } #[derive(Copy, Clone, PartialEq)] enum Token { Number(isize), Op(Operator), LeftParen, RightParen, EOF, } #[derive(Copy, Clone, Debug)] enum LexError { InvalidToken } struct Lexer; impl Lexer { fn lex(string: Vec<&str>) -> Result<Vec<Token>, LexError> { let mut tokens = Vec::new(); for thing in string { match thing { "+" => tokens.push(Token::Op(Operator::Add)), "-" => tokens.push(Token::Op(Operator::Sub)), "*" => tokens.push(Token::Op(Operator::Mul)), "/" => tokens.push(Token::Op(Operator::Div)), "(" => tokens.push(Token::LeftParen), ")" => tokens.push(Token::RightParen), literal => { if let Ok(num) = literal.parse::<isize>() { tokens.push(Token::Number(num)); } else { return Err(LexError::InvalidToken); } } } } tokens.push(Token::EOF); Ok(tokens) } } #[derive(Copy, Clone, Debug)] enum ParseError { UnexpectedToken, UnmatchedParens, InvalidOperator, } // Grammar: // // expression := term // term := factor ( ( "-" | "+" ) factor )* // factor := primary ( ( "*" | "/" ) primary )* // primary := NUMBER | "(" expression ")" struct Parser { tokens: Vec<Token>, current: usize, } impl Parser { fn new(tokens: Vec<Token>) -> Self { Parser { tokens: tokens, current: 0, } } fn matches(&mut self, op: Operator) -> bool { if self.is_at_end() { false } else { match self.peek() { Token::Op(operator) if op == operator => { self.advance(); true }, _ => false } } } fn advance(&mut self) -> Token { if!self.is_at_end() { self.current += 1; } self.previous() } fn is_at_end(&self) -> bool { self.peek() == Token::EOF } fn peek(&self) -> Token { self.tokens[self.current] } fn previous(&self) -> Token { self.tokens[self.current - 1] } fn parse(&mut self) -> Result<Expr, ParseError> { self.expression() } fn expression(&mut self) -> Result<Expr, ParseError> { self.term() } fn term(&mut self) -> Result<Expr, ParseError> { let mut expr = self.factor()?; while self.matches(Operator::Add) || self.matches(Operator::Sub) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::InvalidOperator); }; let right = self.factor()?; expr = Expr::Op(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn factor(&mut self) -> Result<Expr, ParseError> { let mut expr = self.primary()?; while self.matches(Operator::Mul) || self.matches(Operator::Div) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::InvalidOperator); }; let right = self.primary()?; expr = Expr::Op(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn primary(&mut self) -> Result<Expr, ParseError> { match self.advance() { Token::Number(num) => Ok(Expr::Val(num)), Token::LeftParen => { let expr = self.expression()?; if let Token::RightParen = self.advance()
else { Err(ParseError::UnmatchedParens) } }, _ => Err(ParseError::UnexpectedToken), } } } enum Expr { Op(Box<Expr>, Operator, Box<Expr>), Val(isize), } impl Expr { fn eval(&self) -> isize { match *self { Expr::Op(ref lhs, ref op, ref rhs) => op.apply(lhs.eval(), rhs.eval()), Expr::Val(x) => x, } } } #[derive(Copy, Clone, PartialEq)] enum Operator { Add, Sub, Mul, Div, } impl Operator { fn apply(&self, lhs: isize, rhs: isize) -> isize { match *self { Operator::Add => lhs + rhs, Operator::Sub => lhs - rhs, Operator::Mul => lhs * rhs, Operator::Div => lhs / rhs, } } } pub fn shell(_args: &mut Args) { let mut blink_handle: Option<TaskHandle> = None; loop { print!(" > "); let line = match read_line() { Ok(line) => line, Err(err) => { println!("Error: {}", err); continue; }, }; let mut words: Vec<&str> = line.iter().map(|s| s.as_ref()).collect(); //let mut words: Vec<&str> = line.split(' ').collect(); if words.len() > 0 { match Command::from(words.remove(0)) { Command::Echo => { for word in words { print!("{} ", word); } println!(""); }, Command::Clear => { // ANSI ESC sequence to clear screen and put cursor at at top of terminal. print!("\x1b[2J") }, Command::Eval => { eval(words); }, Command::Blink => { let rate: usize = if words.len() > 0 { words[0].parse::<usize>().unwrap_or(100) } else { 100 }; if let Some(mut handle) = blink_handle.take() { handle.destroy(); turn_off_led(); } let mut args = ArgsBuilder::with_capacity(1); args.add_num(rate); blink_handle = Some(kernel::syscall::new_task(blink, args.finalize(), 1024, Priority::Low, "blink")); }, Command::Stop => { if let Some(mut handle) = blink_handle.take() { handle.destroy(); turn_off_led(); } }, Command::Uptime => { let hms = uptime(); println!("{:02}:{:02}:{:02}", hms.0, hms.1, hms.2); }, /* Command::Rocket => { let timer = if words.len() > 0 { words[0].parse::<isize>().unwrap_or(5) } else { 5 }; rocket(timer); }, */ Command::Uname => { //println!("{}\n", LOGO); //Find more info and place it here println!("AltOS Rust"); }, Command::Exit => kernel::syscall::exit(), Command::Help => { if words.len() > 0 { let command = Command::from(words[0]); let msg = command.help_msg(); println!("{}{}", msg.0, msg.1); } else { println!("{}", HELP); } } Command::Invalid(invalid) => println!("Unknown command: '{}'", invalid), } } } } fn eval(args: Vec<&str>) { let tokens = match Lexer::lex(args) { Ok(tokens) => tokens, Err(err) => { println!("Lexing failed: {:?}", err); return; }, }; let mut parser = Parser::new(tokens); match parser.parse() { Ok(expr) => println!("Result: {}", expr.eval()), Err(err) => println!("Parsing failed: {:?}", err), } } fn turn_on_led() { use cortex_m0::peripheral::gpio::{self, Port}; let mut pb3 = Port::new(3, gpio::Group::B); pb3.set(); } fn turn_off_led() { use cortex_m0::peripheral::gpio::{self, Port}; let mut pb3 = Port::new(3, gpio::Group::B); pb3.reset(); } fn blink(args: &mut Args) { let rate = args.pop_num(); loop { turn_on_led(); delay_ms(rate); turn_off_led(); delay_ms(rate); } } fn get_and_echo_char() -> Option<char> { io::poll_char().map(|ch| { print!("{}", ch as char); // 8 is \b, but Rust doesn't recognize \b? if ch == b'\x08' { print!(" "); print!("{}", ch as char); } ch as char }) } fn read_line() -> Result<Vec<String>, ReadError> { let mut line = Vec::new(); let mut word = String::new(); let mut in_string = false; loop { if let Some(ch) = get_and_echo_char() { match ch { '\n' | '\r' => { if in_string { return Err(ReadError::UnclosedString); } line.push(word); return Ok(line.into_iter().filter(|word|!word.is_empty()).map(|word| word.replace("\"", "")).collect()); }, '\x08' => { match word.pop() { Some(ch) if ch == '"' => in_string =!in_string, Some(_) => {}, None => match line.pop() { Some(old_word) => word = old_word, None => print!(" "), }, } }, '' => { if!in_string { line.push(word); word = String::new(); } else { word.push(' '); } }, '"' => { word.push('"'); in_string =!in_string; }, _ => word.push(ch), } } } } fn uptime() -> (usize, usize, usize) { let curr_time = now(); let mut minutes = curr_time.sec / 60; let hours = minutes / 60; let seconds = curr_time.sec % 60; minutes = minutes % 60; (hours, minutes, seconds) } /* fn rocket(mut timer: isize) { let mut offset: isize = 15; let stationary: isize = offset; let counter = timer + offset * 2; let mut k = 0; if timer < 0 { timer = 5; } let mut rocket = String::new(); while k < counter { rocket.clear(); print!("\x1b[2J"); newline_offset(&mut rocket, offset); build_rocket_part(&mut rocket, " /\\\n", offset); build_rocket_part(&mut rocket, " / \\\n", offset+1); build_rocket_part(&mut rocket, " / \\\n", offset+2); build_rocket_part(&mut rocket, " | A |\n", offset+3); build_rocket_part(&mut rocket, " | L |\n", offset+4); build_rocket_part(&mut rocket, " /| T |\\\n", offset+5); build_rocket_part(&mut rocket, " / | O | \\\n", offset+6); build_rocket_part(&mut rocket, " ^^| S |^^\n", offset+7); build_rocket_part(&mut
{ Ok(expr) }
conditional_block
shell.rs
ArgsBuilder, Args}; use kernel::collections::{Vec, String}; use kernel::alloc::Box; use core::fmt::{self, Display}; /* const LOGO: &'static str = " . ;' .. '. .cc. x0kk. .Oo .xc c,;: .OO. xO. .Oo 'dkxoc.d. .o'.clccc. ;' ;' kKdodd0k..Oo .kl ,k, 'x;,dc;,'. .. . cXl .o0o.Oo .ko ,k; ;x; ..ld. c:. .:: oO. dx xc cddo, :dolcd' ;lcclc, ;c;,',':c' .cc, :cc. .ccl; cll: 'dl ;o; .. :odxc dxdd; kK0d cOkO .''. ok ... . . ..... ... ,xkO0o k00Ox. .Kx.k0O':O, 'x' 'k:lookol.oxcx;. ;d. ,d',oc.'ll:.'l: .k0KKKd OXKK0k ,Xl l O: xOoccccc ck. ox '' ;d. ,d',o. :l. :l d0KKXXd OXXXKKl ;Xl Oc 'kd; :k ox 'dc 'd',o. :l. :l ;x0KXXO; cKXXKKx, xl. 0c. lcccc :l ox 'cccc' 0 :l. :l .lxOKKXo kXKK0ko. "; */ const HELP: &'static str = "Available Commands: echo [string...] clear eval <lhs> <op> <rhs> blink [rate] stop uptime rocket [timer] uname exit help [cmd]"; const ECHO_HELP: &'static str = "Echo a string to the terminal"; const CLEAR_HELP: &'static str = "Clear the terminal"; const EVAL_HELP: &'static str = "Evaluate an expression of the form x <op> y"; const BLINK_HELP: &'static str = "Blink the LED at the given rate in milliseconds"; const STOP_HELP: &'static str = "Stop blinking the LED"; const UPTIME_HELP: &'static str = "Display how long the system has been running as HH:MM:SS"; //const ROCKET_HELP: &'static str = "Deploys a rocket?"; const UNAME_HELP: &'static str = "Displays system information"; const EXIT_HELP: &'static str = "Exit the shell"; const HELP_HELP: &'static str = "Display available commands or more information about a certain command"; enum ReadError { UnclosedString, } impl Display for ReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let msg = match *self { ReadError::UnclosedString => "unclosed string found", }; write!(f, "{}", msg) } } enum Command<'a> { Echo, Clear, Eval, Blink, Stop, Uptime, //Rocket, Uname, Exit, Help, Invalid(&'a str), } impl<'a> Command<'a> { fn help_msg(&self) -> (&'static str, &str) { match *self { Command::Echo => (ECHO_HELP, ""), Command::Clear => (CLEAR_HELP, ""), Command::Eval => (EVAL_HELP, ""), Command::Blink => (BLINK_HELP, ""), Command::Stop => (STOP_HELP, ""), Command::Uptime => (UPTIME_HELP, ""), //Command::Rocket => (ROCKET_HELP, ""), Command::Uname => (UNAME_HELP, ""), Command::Exit => (EXIT_HELP, ""), Command::Help => (HELP_HELP, ""), Command::Invalid(invalid) => ("Unknown command: ", invalid), } } } impl<'a> From<&'a str> for Command<'a> { fn from(string: &'a str) -> Command<'a> { match string { "echo" => Command::Echo, "clear" => Command::Clear, "eval" => Command::Eval, "blink" => Command::Blink, "stop" => Command::Stop, "uptime" => Command::Uptime, //"rocket" => Command::Rocket, "uname"=> Command::Uname, "exit" => Command::Exit, "help" => Command::Help, invalid => Command::Invalid(invalid), } } } #[derive(Copy, Clone, PartialEq)] enum Token { Number(isize), Op(Operator), LeftParen, RightParen, EOF, } #[derive(Copy, Clone, Debug)] enum LexError { InvalidToken } struct Lexer; impl Lexer { fn lex(string: Vec<&str>) -> Result<Vec<Token>, LexError> { let mut tokens = Vec::new(); for thing in string { match thing { "+" => tokens.push(Token::Op(Operator::Add)), "-" => tokens.push(Token::Op(Operator::Sub)), "*" => tokens.push(Token::Op(Operator::Mul)), "/" => tokens.push(Token::Op(Operator::Div)), "(" => tokens.push(Token::LeftParen), ")" => tokens.push(Token::RightParen), literal => { if let Ok(num) = literal.parse::<isize>() { tokens.push(Token::Number(num)); } else { return Err(LexError::InvalidToken); } } } } tokens.push(Token::EOF); Ok(tokens) } } #[derive(Copy, Clone, Debug)] enum ParseError { UnexpectedToken, UnmatchedParens, InvalidOperator, } // Grammar: // // expression := term // term := factor ( ( "-" | "+" ) factor )* // factor := primary ( ( "*" | "/" ) primary )* // primary := NUMBER | "(" expression ")" struct Parser { tokens: Vec<Token>, current: usize, } impl Parser { fn new(tokens: Vec<Token>) -> Self { Parser { tokens: tokens, current: 0, } } fn matches(&mut self, op: Operator) -> bool { if self.is_at_end() { false } else { match self.peek() { Token::Op(operator) if op == operator => { self.advance(); true }, _ => false } } } fn advance(&mut self) -> Token { if!self.is_at_end() { self.current += 1; } self.previous() } fn is_at_end(&self) -> bool { self.peek() == Token::EOF } fn peek(&self) -> Token { self.tokens[self.current] } fn previous(&self) -> Token { self.tokens[self.current - 1] } fn parse(&mut self) -> Result<Expr, ParseError> { self.expression() } fn expression(&mut self) -> Result<Expr, ParseError> { self.term() } fn term(&mut self) -> Result<Expr, ParseError> { let mut expr = self.factor()?; while self.matches(Operator::Add) || self.matches(Operator::Sub) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::InvalidOperator); }; let right = self.factor()?; expr = Expr::Op(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn
(&mut self) -> Result<Expr, ParseError> { let mut expr = self.primary()?; while self.matches(Operator::Mul) || self.matches(Operator::Div) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::InvalidOperator); }; let right = self.primary()?; expr = Expr::Op(Box::new(expr), operator, Box::new(right)); } Ok(expr) } fn primary(&mut self) -> Result<Expr, ParseError> { match self.advance() { Token::Number(num) => Ok(Expr::Val(num)), Token::LeftParen => { let expr = self.expression()?; if let Token::RightParen = self.advance() { Ok(expr) } else { Err(ParseError::UnmatchedParens) } }, _ => Err(ParseError::UnexpectedToken), } } } enum Expr { Op(Box<Expr>, Operator, Box<Expr>), Val(isize), } impl Expr { fn eval(&self) -> isize { match *self { Expr::Op(ref lhs, ref op, ref rhs) => op.apply(lhs.eval(), rhs.eval()), Expr::Val(x) => x, } } } #[derive(Copy, Clone, PartialEq)] enum Operator { Add, Sub, Mul, Div, } impl Operator { fn apply(&self, lhs: isize, rhs: isize) -> isize { match *self { Operator::Add => lhs + rhs, Operator::Sub => lhs - rhs, Operator::Mul => lhs * rhs, Operator::Div => lhs / rhs, } } } pub fn shell(_args: &mut Args) { let mut blink_handle: Option<TaskHandle> = None; loop { print!(" > "); let line = match read_line() { Ok(line) => line, Err(err) => { println!("Error: {}", err); continue; }, }; let mut words: Vec<&str> = line.iter().map(|s| s.as_ref()).collect(); //let mut words: Vec<&str> = line.split(' ').collect(); if words.len() > 0 { match Command::from(words.remove(0)) { Command::Echo => { for word in words { print!("{} ", word); } println!(""); }, Command::Clear => { // ANSI ESC sequence to clear screen and put cursor at at top of terminal. print!("\x1b[2J") }, Command::Eval => { eval(words); }, Command::Blink => { let rate: usize = if words.len() > 0 { words[0].parse::<usize>().unwrap_or(100) } else { 100 }; if let Some(mut handle) = blink_handle.take() { handle.destroy(); turn_off_led(); } let mut args = ArgsBuilder::with_capacity(1); args.add_num(rate); blink_handle = Some(kernel::syscall::new_task(blink, args.finalize(), 1024, Priority::Low, "blink")); }, Command::Stop => { if let Some(mut handle) = blink_handle.take() { handle.destroy(); turn_off_led(); } }, Command::Uptime => { let hms = uptime(); println!("{:02}:{:02}:{:02}", hms.0, hms.1, hms.2); }, /* Command::Rocket => { let timer = if words.len() > 0 { words[0].parse::<isize>().unwrap_or(5) } else { 5 }; rocket(timer); }, */ Command::Uname => { //println!("{}\n", LOGO); //Find more info and place it here println!("AltOS Rust"); }, Command::Exit => kernel::syscall::exit(), Command::Help => { if words.len() > 0 { let command = Command::from(words[0]); let msg = command.help_msg(); println!("{}{}", msg.0, msg.1); } else { println!("{}", HELP); } } Command::Invalid(invalid) => println!("Unknown command: '{}'", invalid), } } } } fn eval(args: Vec<&str>) { let tokens = match Lexer::lex(args) { Ok(tokens) => tokens, Err(err) => { println!("Lexing failed: {:?}", err); return; }, }; let mut parser = Parser::new(tokens); match parser.parse() { Ok(expr) => println!("Result: {}", expr.eval()), Err(err) => println!("Parsing failed: {:?}", err), } } fn turn_on_led() { use cortex_m0::peripheral::gpio::{self, Port}; let mut pb3 = Port::new(3, gpio::Group::B); pb3.set(); } fn turn_off_led() { use cortex_m0::peripheral::gpio::{self, Port}; let mut pb3 = Port::new(3, gpio::Group::B); pb3.reset(); } fn blink(args: &mut Args) { let rate = args.pop_num(); loop { turn_on_led(); delay_ms(rate); turn_off_led(); delay_ms(rate); } } fn get_and_echo_char() -> Option<char> { io::poll_char().map(|ch| { print!("{}", ch as char); // 8 is \b, but Rust doesn't recognize \b? if ch == b'\x08' { print!(" "); print!("{}", ch as char); } ch as char }) } fn read_line() -> Result<Vec<String>, ReadError> { let mut line = Vec::new(); let mut word = String::new(); let mut in_string = false; loop { if let Some(ch) = get_and_echo_char() { match ch { '\n' | '\r' => { if in_string { return Err(ReadError::UnclosedString); } line.push(word); return Ok(line.into_iter().filter(|word|!word.is_empty()).map(|word| word.replace("\"", "")).collect()); }, '\x08' => { match word.pop() { Some(ch) if ch == '"' => in_string =!in_string, Some(_) => {}, None => match line.pop() { Some(old_word) => word = old_word, None => print!(" "), }, } }, '' => { if!in_string { line.push(word); word = String::new(); } else { word.push(' '); } }, '"' => { word.push('"'); in_string =!in_string; }, _ => word.push(ch), } } } } fn uptime() -> (usize, usize, usize) { let curr_time = now(); let mut minutes = curr_time.sec / 60; let hours = minutes / 60; let seconds = curr_time.sec % 60; minutes = minutes % 60; (hours, minutes, seconds) } /* fn rocket(mut timer: isize) { let mut offset: isize = 15; let stationary: isize = offset; let counter = timer + offset * 2; let mut k = 0; if timer < 0 { timer = 5; } let mut rocket = String::new(); while k < counter { rocket.clear(); print!("\x1b[2J"); newline_offset(&mut rocket, offset); build_rocket_part(&mut rocket, " /\\\n", offset); build_rocket_part(&mut rocket, " / \\\n", offset+1); build_rocket_part(&mut rocket, " / \\\n", offset+2); build_rocket_part(&mut rocket, " | A |\n", offset+3); build_rocket_part(&mut rocket, " | L |\n", offset+4); build_rocket_part(&mut rocket, " /| T |\\\n", offset+5); build_rocket_part(&mut rocket, " / | O | \\\n", offset+6); build_rocket_part(&mut rocket, " ^^| S |^^\n", offset+7); build_rocket_part(&mut
factor
identifier_name
transaction.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Transaction data structure. use std::ops::Deref; use rlp::*; use util::sha3::Hashable; use util::{H256, Address, U256, Bytes, HeapSizeOf}; use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError}; use error::*; use evm::Schedule; use header::BlockNumber; use ethjson; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] /// Transaction action type. pub enum Action { /// Create creates new contract. Create, /// Calls contract at given address. /// In the case of a transfer, this is the receiver's address.' Call(Address), } impl Default for Action { fn default() -> Action { Action::Create } } impl Decodable for Action { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let rlp = decoder.as_rlp(); if rlp.is_empty() { Ok(Action::Create) } else { Ok(Action::Call(rlp.as_val()?)) } } } /// Transaction activation condition. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub enum Condition { /// Valid at this block number or later. Number(BlockNumber), /// Valid at this unix time or later. Timestamp(u64), } /// A set of information describing an externally-originating message call /// or contract creation operation. #[derive(Default, Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct Transaction { /// Nonce. pub nonce: U256, /// Gas price. pub gas_price: U256, /// Gas paid up front for transaction execution. pub gas: U256, /// Action, can be either call or contract create. pub action: Action, /// Transfered value. pub value: U256, /// Transaction data. pub data: Bytes, } impl Transaction { /// Append object with a without signature into RLP stream pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream, network_id: Option<u64>) { s.begin_list(if network_id.is_none() { 6 } else { 9 }); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); if let Some(n) = network_id { s.append(&n); s.append(&0u8); s.append(&0u8); } } } impl HeapSizeOf for Transaction { fn heap_size_of_children(&self) -> usize { self.data.heap_size_of_children() } } impl From<ethjson::state::Transaction> for SignedTransaction { fn from(t: ethjson::state::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); let secret = Secret::from_slice(&t.secret.0).expect("Valid secret expected."); Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }.sign(&secret, None) } } impl From<ethjson::transaction::Transaction> for UnverifiedTransaction { fn from(t: ethjson::transaction::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); UnverifiedTransaction { unsigned: Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }, r: t.r.into(), s: t.s.into(), v: t.v.into(), hash: 0.into(), }.compute_hash() } } impl Transaction { /// The message hash of the transaction. pub fn hash(&self, network_id: Option<u64>) -> H256 { let mut stream = RlpStream::new(); self.rlp_append_unsigned_transaction(&mut stream, network_id); stream.as_raw().sha3() } /// Signs the transaction as coming from `sender`. pub fn sign(self, secret: &Secret, network_id: Option<u64>) -> SignedTransaction { let sig = ::ethkey::sign(secret, &self.hash(network_id)) .expect("data is valid and context has signing capabilities; qed"); SignedTransaction::new(self.with_signature(sig, network_id)) .expect("secret is valid so it's recoverable") } /// Signs the transaction with signature. pub fn with_signature(self, sig: Signature, network_id: Option<u64>) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: sig.r().into(), s: sig.s().into(), v: sig.v() as u64 + if let Some(n) = network_id { 35 + n * 2 } else { 27 }, hash: 0.into(), }.compute_hash() } /// Useful for test incorrectly signed transactions. #[cfg(test)] pub fn invalid_sign(self) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash() } /// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned. pub fn fake_sign(self, from: Address) -> SignedTransaction { SignedTransaction { transaction: UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash(), sender: from, public: Public::default(), } } /// Get the transaction cost in gas for the given params. pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 { data.iter().fold( (if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64, |g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64 ) } /// Get the transaction cost in gas for this transaction. pub fn gas_required(&self, schedule: &Schedule) -> u64
} /// Signed transaction information. #[derive(Debug, Clone, Eq, PartialEq)] #[cfg_attr(feature = "ipc", binary)] pub struct UnverifiedTransaction { /// Plain Transaction. unsigned: Transaction, /// The V field of the signature; the LS bit described which half of the curve our point falls /// in. The MS bits describe which network this transaction is for. If 27/28, its for all networks. v: u64, /// The R field of the signature; helps describe the point on the curve. r: U256, /// The S field of the signature; helps describe the point on the curve. s: U256, /// Hash of the transaction hash: H256, } impl Deref for UnverifiedTransaction { type Target = Transaction; fn deref(&self) -> &Self::Target { &self.unsigned } } impl Decodable for UnverifiedTransaction { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); if d.item_count()!= 9 { return Err(DecoderError::RlpIncorrectListLen); } let hash = decoder.as_raw().sha3(); Ok(UnverifiedTransaction { unsigned: Transaction { nonce: d.val_at(0)?, gas_price: d.val_at(1)?, gas: d.val_at(2)?, action: d.val_at(3)?, value: d.val_at(4)?, data: d.val_at(5)?, }, v: d.val_at(6)?, r: d.val_at(7)?, s: d.val_at(8)?, hash: hash, }) } } impl Encodable for UnverifiedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) } } impl UnverifiedTransaction { /// Used to compute hash of created transactions fn compute_hash(mut self) -> UnverifiedTransaction { let hash = (&*self.rlp_bytes()).sha3(); self.hash = hash; self } /// Append object with a signature into RLP stream fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { s.begin_list(9); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); s.append(&self.v); s.append(&self.r); s.append(&self.s); } /// Reference to unsigned part of this transaction. pub fn as_unsigned(&self) -> &Transaction { &self.unsigned } /// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid. pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } } /// The `v` value that appears in the RLP. pub fn original_v(&self) -> u64 { self.v } /// The network ID, or `None` if this is a global transaction. pub fn network_id(&self) -> Option<u64> { match self.v { v if v > 36 => Some((v - 35) / 2), _ => None, } } /// Construct a signature object from the sig. pub fn signature(&self) -> Signature { Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v()) } /// Checks whether the signature has a low's' value. pub fn check_low_s(&self) -> Result<(), Error> { if!self.signature().is_low_s() { Err(EthkeyError::InvalidSignature.into()) } else { Ok(()) } } /// Get the hash of this header (sha3 of the RLP). pub fn hash(&self) -> H256 { self.hash } /// Recovers the public key of the sender. pub fn recover_public(&self) -> Result<Public, Error> { Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?) } /// Do basic validation, checking for valid signature and minimum gas, // TODO: consider use in block validation. #[cfg(test)] #[cfg(feature = "json-tests")] pub fn validate(self, schedule: &Schedule, require_low: bool, allow_network_id_of_one: bool) -> Result<UnverifiedTransaction, Error> { if require_low &&!self.signature().is_low_s() { return Err(EthkeyError::InvalidSignature.into()) } match self.network_id() { None => {}, Some(1) if allow_network_id_of_one => {}, _ => return Err(TransactionError::InvalidNetworkId.into()), } self.recover_public()?; if self.gas < U256::from(self.gas_required(&schedule)) { Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into()) } else { Ok(self) } } } /// A `UnverifiedTransaction` with successfully recovered `sender`. #[derive(Debug, Clone, Eq, PartialEq)] pub struct SignedTransaction { transaction: UnverifiedTransaction, sender: Address, public: Public, } impl HeapSizeOf for SignedTransaction { fn heap_size_of_children(&self) -> usize { self.transaction.unsigned.heap_size_of_children() } } impl Encodable for SignedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.transaction.rlp_append_sealed_transaction(s) } } impl Deref for SignedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.transaction } } impl From<SignedTransaction> for UnverifiedTransaction { fn from(tx: SignedTransaction) -> Self { tx.transaction } } impl SignedTransaction { /// Try to verify transaction and recover sender. pub fn new(transaction: UnverifiedTransaction) -> Result<Self, Error> { let public = transaction.recover_public()?; let sender = public_to_address(&public); Ok(SignedTransaction { transaction: transaction, sender: sender, public: public, }) } /// Returns transaction sender. pub fn sender(&self) -> Address { self.sender } /// Returns a public key of the sender. pub fn public_key(&self) -> Public { self.public } } /// Signed Transaction that is a part of canon blockchain. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct LocalizedTransaction { /// Signed part. pub signed: UnverifiedTransaction, /// Block number. pub block_number: BlockNumber, /// Block hash. pub block_hash: H256, /// Transaction index within block. pub transaction_index: usize, /// Cached sender pub cached_sender: Option<Address>, } impl LocalizedTransaction { /// Returns transaction sender. /// Panics if `LocalizedTransaction` is constructed using invalid `UnverifiedTransaction`. pub fn sender(&mut self) -> Address { if let Some(sender) = self.cached_sender { return sender; } let sender = public_to_address(&self.recover_public() .expect("LocalizedTransaction is always constructed from transaction from blockchain; Blockchain only stores verified transactions; qed")); self.cached_sender = Some(sender); sender } } impl Deref for LocalizedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.signed } } /// Queued transaction with additional information. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct PendingTransaction { /// Signed transaction data. pub transaction: SignedTransaction, /// To be activated at this condition. `None` for immediately. pub condition: Option<Condition>, } impl PendingTransaction { /// Create a new pending transaction from signed transaction. pub fn new(signed: SignedTransaction, condition: Option<Condition>) -> Self { PendingTransaction { transaction: signed, condition: condition, } } } impl Deref for PendingTransaction { type Target = SignedTransaction; fn deref(&self) -> &SignedTransaction { &self.transaction } } impl From<SignedTransaction> for PendingTransaction { fn from(t: SignedTransaction) -> Self { PendingTransaction { transaction: t, condition: None, } } } #[test] fn sender_test() { let t: UnverifiedTransaction = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(t.data, b""); assert_eq!(t.gas, U256::from(0x5208u64)); assert_eq!(t.gas_price, U256::from(0x01u64)); assert_eq!(t.nonce, U256::from(0x00u64)); if let Action::Call(ref to) = t.action { assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into()); } else { panic!(); } assert_eq!(t.value, U256::from(0x0au64)); assert_eq!(public_to_address(&t.recover_public().unwrap()), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into()); assert_eq!(t.network_id(), None); } #[test] fn signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), None); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn fake_signing() { let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.fake_sign(Address::from(0x69)); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); let t = t.clone(); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn should_recover_from_network_specific_signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), Some(69)); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), Some(69)); } #[test] fn should_agree_with_vitalik() { use rustc_serialize::hex::FromHex; let test_vector = |tx_data: &str, address: &'static str| { let signed = decode(&FromHex::from_hex(tx_data).unwrap()); let signed = SignedTransaction::new(signed).unwrap(); assert_eq!(signed.sender(), address.into()); flushln!("networkid: {:?}", signed.network_id()); }; test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce"); test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112"); test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be"); test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0"); test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554"); test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4"); test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35"); test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332"); test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029"); test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f"); }
{ Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule) }
identifier_body
transaction.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Transaction data structure. use std::ops::Deref; use rlp::*; use util::sha3::Hashable; use util::{H256, Address, U256, Bytes, HeapSizeOf}; use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError}; use error::*; use evm::Schedule; use header::BlockNumber; use ethjson; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] /// Transaction action type. pub enum Action { /// Create creates new contract. Create, /// Calls contract at given address. /// In the case of a transfer, this is the receiver's address.' Call(Address), } impl Default for Action { fn default() -> Action { Action::Create } } impl Decodable for Action { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let rlp = decoder.as_rlp(); if rlp.is_empty() { Ok(Action::Create) } else { Ok(Action::Call(rlp.as_val()?)) } } } /// Transaction activation condition. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub enum Condition { /// Valid at this block number or later. Number(BlockNumber), /// Valid at this unix time or later. Timestamp(u64), } /// A set of information describing an externally-originating message call /// or contract creation operation. #[derive(Default, Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct Transaction { /// Nonce. pub nonce: U256, /// Gas price. pub gas_price: U256, /// Gas paid up front for transaction execution. pub gas: U256, /// Action, can be either call or contract create. pub action: Action, /// Transfered value. pub value: U256, /// Transaction data. pub data: Bytes, } impl Transaction { /// Append object with a without signature into RLP stream pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream, network_id: Option<u64>) { s.begin_list(if network_id.is_none() { 6 } else { 9 }); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); if let Some(n) = network_id { s.append(&n); s.append(&0u8); s.append(&0u8); } } } impl HeapSizeOf for Transaction { fn heap_size_of_children(&self) -> usize { self.data.heap_size_of_children() } } impl From<ethjson::state::Transaction> for SignedTransaction { fn from(t: ethjson::state::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); let secret = Secret::from_slice(&t.secret.0).expect("Valid secret expected."); Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }.sign(&secret, None) } } impl From<ethjson::transaction::Transaction> for UnverifiedTransaction { fn from(t: ethjson::transaction::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); UnverifiedTransaction { unsigned: Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }, r: t.r.into(), s: t.s.into(), v: t.v.into(), hash: 0.into(), }.compute_hash() } } impl Transaction { /// The message hash of the transaction. pub fn hash(&self, network_id: Option<u64>) -> H256 { let mut stream = RlpStream::new(); self.rlp_append_unsigned_transaction(&mut stream, network_id); stream.as_raw().sha3() } /// Signs the transaction as coming from `sender`. pub fn sign(self, secret: &Secret, network_id: Option<u64>) -> SignedTransaction { let sig = ::ethkey::sign(secret, &self.hash(network_id)) .expect("data is valid and context has signing capabilities; qed"); SignedTransaction::new(self.with_signature(sig, network_id)) .expect("secret is valid so it's recoverable") } /// Signs the transaction with signature. pub fn with_signature(self, sig: Signature, network_id: Option<u64>) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: sig.r().into(), s: sig.s().into(), v: sig.v() as u64 + if let Some(n) = network_id { 35 + n * 2 } else { 27 }, hash: 0.into(), }.compute_hash() } /// Useful for test incorrectly signed transactions. #[cfg(test)] pub fn invalid_sign(self) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash() } /// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned. pub fn fake_sign(self, from: Address) -> SignedTransaction { SignedTransaction { transaction: UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash(), sender: from, public: Public::default(), } } /// Get the transaction cost in gas for the given params. pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 { data.iter().fold( (if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64, |g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64 ) } /// Get the transaction cost in gas for this transaction. pub fn gas_required(&self, schedule: &Schedule) -> u64 { Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule) } } /// Signed transaction information. #[derive(Debug, Clone, Eq, PartialEq)] #[cfg_attr(feature = "ipc", binary)] pub struct UnverifiedTransaction { /// Plain Transaction. unsigned: Transaction, /// The V field of the signature; the LS bit described which half of the curve our point falls /// in. The MS bits describe which network this transaction is for. If 27/28, its for all networks. v: u64, /// The R field of the signature; helps describe the point on the curve. r: U256, /// The S field of the signature; helps describe the point on the curve. s: U256, /// Hash of the transaction hash: H256, } impl Deref for UnverifiedTransaction { type Target = Transaction; fn deref(&self) -> &Self::Target { &self.unsigned } } impl Decodable for UnverifiedTransaction { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); if d.item_count()!= 9 { return Err(DecoderError::RlpIncorrectListLen); } let hash = decoder.as_raw().sha3(); Ok(UnverifiedTransaction { unsigned: Transaction { nonce: d.val_at(0)?, gas_price: d.val_at(1)?, gas: d.val_at(2)?, action: d.val_at(3)?, value: d.val_at(4)?, data: d.val_at(5)?, }, v: d.val_at(6)?, r: d.val_at(7)?, s: d.val_at(8)?, hash: hash, }) } } impl Encodable for UnverifiedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) } } impl UnverifiedTransaction { /// Used to compute hash of created transactions fn compute_hash(mut self) -> UnverifiedTransaction { let hash = (&*self.rlp_bytes()).sha3(); self.hash = hash; self } /// Append object with a signature into RLP stream fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { s.begin_list(9); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); s.append(&self.v); s.append(&self.r); s.append(&self.s); } /// Reference to unsigned part of this transaction. pub fn as_unsigned(&self) -> &Transaction { &self.unsigned } /// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid. pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } } /// The `v` value that appears in the RLP. pub fn original_v(&self) -> u64 { self.v } /// The network ID, or `None` if this is a global transaction. pub fn network_id(&self) -> Option<u64> { match self.v { v if v > 36 => Some((v - 35) / 2), _ => None, } } /// Construct a signature object from the sig. pub fn signature(&self) -> Signature { Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v()) } /// Checks whether the signature has a low's' value. pub fn check_low_s(&self) -> Result<(), Error> { if!self.signature().is_low_s() { Err(EthkeyError::InvalidSignature.into()) } else { Ok(()) } } /// Get the hash of this header (sha3 of the RLP). pub fn hash(&self) -> H256 { self.hash } /// Recovers the public key of the sender. pub fn recover_public(&self) -> Result<Public, Error> { Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?) } /// Do basic validation, checking for valid signature and minimum gas, // TODO: consider use in block validation. #[cfg(test)] #[cfg(feature = "json-tests")] pub fn validate(self, schedule: &Schedule, require_low: bool, allow_network_id_of_one: bool) -> Result<UnverifiedTransaction, Error> { if require_low &&!self.signature().is_low_s() { return Err(EthkeyError::InvalidSignature.into()) } match self.network_id() { None => {}, Some(1) if allow_network_id_of_one => {}, _ => return Err(TransactionError::InvalidNetworkId.into()), } self.recover_public()?; if self.gas < U256::from(self.gas_required(&schedule)) { Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into()) } else { Ok(self) } } } /// A `UnverifiedTransaction` with successfully recovered `sender`. #[derive(Debug, Clone, Eq, PartialEq)] pub struct SignedTransaction { transaction: UnverifiedTransaction, sender: Address, public: Public, } impl HeapSizeOf for SignedTransaction { fn heap_size_of_children(&self) -> usize { self.transaction.unsigned.heap_size_of_children() } } impl Encodable for SignedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.transaction.rlp_append_sealed_transaction(s) } } impl Deref for SignedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.transaction } } impl From<SignedTransaction> for UnverifiedTransaction { fn from(tx: SignedTransaction) -> Self { tx.transaction } } impl SignedTransaction { /// Try to verify transaction and recover sender. pub fn new(transaction: UnverifiedTransaction) -> Result<Self, Error> { let public = transaction.recover_public()?; let sender = public_to_address(&public); Ok(SignedTransaction { transaction: transaction, sender: sender, public: public, }) } /// Returns transaction sender. pub fn sender(&self) -> Address { self.sender } /// Returns a public key of the sender. pub fn public_key(&self) -> Public { self.public } } /// Signed Transaction that is a part of canon blockchain. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct LocalizedTransaction { /// Signed part. pub signed: UnverifiedTransaction, /// Block number. pub block_number: BlockNumber, /// Block hash. pub block_hash: H256, /// Transaction index within block. pub transaction_index: usize, /// Cached sender pub cached_sender: Option<Address>, } impl LocalizedTransaction { /// Returns transaction sender. /// Panics if `LocalizedTransaction` is constructed using invalid `UnverifiedTransaction`. pub fn sender(&mut self) -> Address { if let Some(sender) = self.cached_sender { return sender; } let sender = public_to_address(&self.recover_public() .expect("LocalizedTransaction is always constructed from transaction from blockchain; Blockchain only stores verified transactions; qed")); self.cached_sender = Some(sender); sender } } impl Deref for LocalizedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.signed } } /// Queued transaction with additional information. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct PendingTransaction { /// Signed transaction data. pub transaction: SignedTransaction, /// To be activated at this condition. `None` for immediately. pub condition: Option<Condition>, } impl PendingTransaction { /// Create a new pending transaction from signed transaction. pub fn new(signed: SignedTransaction, condition: Option<Condition>) -> Self { PendingTransaction { transaction: signed, condition: condition, } } } impl Deref for PendingTransaction { type Target = SignedTransaction; fn deref(&self) -> &SignedTransaction { &self.transaction } } impl From<SignedTransaction> for PendingTransaction { fn from(t: SignedTransaction) -> Self { PendingTransaction { transaction: t, condition: None, } } } #[test] fn sender_test() { let t: UnverifiedTransaction = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(t.data, b""); assert_eq!(t.gas, U256::from(0x5208u64)); assert_eq!(t.gas_price, U256::from(0x01u64)); assert_eq!(t.nonce, U256::from(0x00u64)); if let Action::Call(ref to) = t.action { assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into()); } else { panic!(); } assert_eq!(t.value, U256::from(0x0au64)); assert_eq!(public_to_address(&t.recover_public().unwrap()), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into()); assert_eq!(t.network_id(), None); } #[test] fn signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), None); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn fake_signing() { let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.fake_sign(Address::from(0x69)); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); let t = t.clone(); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn
() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), Some(69)); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), Some(69)); } #[test] fn should_agree_with_vitalik() { use rustc_serialize::hex::FromHex; let test_vector = |tx_data: &str, address: &'static str| { let signed = decode(&FromHex::from_hex(tx_data).unwrap()); let signed = SignedTransaction::new(signed).unwrap(); assert_eq!(signed.sender(), address.into()); flushln!("networkid: {:?}", signed.network_id()); }; test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce"); test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112"); test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be"); test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0"); test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554"); test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4"); test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35"); test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332"); test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029"); test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f"); }
should_recover_from_network_specific_signing
identifier_name
transaction.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Transaction data structure. use std::ops::Deref;
use rlp::*; use util::sha3::Hashable; use util::{H256, Address, U256, Bytes, HeapSizeOf}; use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError}; use error::*; use evm::Schedule; use header::BlockNumber; use ethjson; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] /// Transaction action type. pub enum Action { /// Create creates new contract. Create, /// Calls contract at given address. /// In the case of a transfer, this is the receiver's address.' Call(Address), } impl Default for Action { fn default() -> Action { Action::Create } } impl Decodable for Action { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let rlp = decoder.as_rlp(); if rlp.is_empty() { Ok(Action::Create) } else { Ok(Action::Call(rlp.as_val()?)) } } } /// Transaction activation condition. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub enum Condition { /// Valid at this block number or later. Number(BlockNumber), /// Valid at this unix time or later. Timestamp(u64), } /// A set of information describing an externally-originating message call /// or contract creation operation. #[derive(Default, Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct Transaction { /// Nonce. pub nonce: U256, /// Gas price. pub gas_price: U256, /// Gas paid up front for transaction execution. pub gas: U256, /// Action, can be either call or contract create. pub action: Action, /// Transfered value. pub value: U256, /// Transaction data. pub data: Bytes, } impl Transaction { /// Append object with a without signature into RLP stream pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream, network_id: Option<u64>) { s.begin_list(if network_id.is_none() { 6 } else { 9 }); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); if let Some(n) = network_id { s.append(&n); s.append(&0u8); s.append(&0u8); } } } impl HeapSizeOf for Transaction { fn heap_size_of_children(&self) -> usize { self.data.heap_size_of_children() } } impl From<ethjson::state::Transaction> for SignedTransaction { fn from(t: ethjson::state::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); let secret = Secret::from_slice(&t.secret.0).expect("Valid secret expected."); Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }.sign(&secret, None) } } impl From<ethjson::transaction::Transaction> for UnverifiedTransaction { fn from(t: ethjson::transaction::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); UnverifiedTransaction { unsigned: Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }, r: t.r.into(), s: t.s.into(), v: t.v.into(), hash: 0.into(), }.compute_hash() } } impl Transaction { /// The message hash of the transaction. pub fn hash(&self, network_id: Option<u64>) -> H256 { let mut stream = RlpStream::new(); self.rlp_append_unsigned_transaction(&mut stream, network_id); stream.as_raw().sha3() } /// Signs the transaction as coming from `sender`. pub fn sign(self, secret: &Secret, network_id: Option<u64>) -> SignedTransaction { let sig = ::ethkey::sign(secret, &self.hash(network_id)) .expect("data is valid and context has signing capabilities; qed"); SignedTransaction::new(self.with_signature(sig, network_id)) .expect("secret is valid so it's recoverable") } /// Signs the transaction with signature. pub fn with_signature(self, sig: Signature, network_id: Option<u64>) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: sig.r().into(), s: sig.s().into(), v: sig.v() as u64 + if let Some(n) = network_id { 35 + n * 2 } else { 27 }, hash: 0.into(), }.compute_hash() } /// Useful for test incorrectly signed transactions. #[cfg(test)] pub fn invalid_sign(self) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash() } /// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned. pub fn fake_sign(self, from: Address) -> SignedTransaction { SignedTransaction { transaction: UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash(), sender: from, public: Public::default(), } } /// Get the transaction cost in gas for the given params. pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 { data.iter().fold( (if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64, |g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64 ) } /// Get the transaction cost in gas for this transaction. pub fn gas_required(&self, schedule: &Schedule) -> u64 { Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule) } } /// Signed transaction information. #[derive(Debug, Clone, Eq, PartialEq)] #[cfg_attr(feature = "ipc", binary)] pub struct UnverifiedTransaction { /// Plain Transaction. unsigned: Transaction, /// The V field of the signature; the LS bit described which half of the curve our point falls /// in. The MS bits describe which network this transaction is for. If 27/28, its for all networks. v: u64, /// The R field of the signature; helps describe the point on the curve. r: U256, /// The S field of the signature; helps describe the point on the curve. s: U256, /// Hash of the transaction hash: H256, } impl Deref for UnverifiedTransaction { type Target = Transaction; fn deref(&self) -> &Self::Target { &self.unsigned } } impl Decodable for UnverifiedTransaction { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); if d.item_count()!= 9 { return Err(DecoderError::RlpIncorrectListLen); } let hash = decoder.as_raw().sha3(); Ok(UnverifiedTransaction { unsigned: Transaction { nonce: d.val_at(0)?, gas_price: d.val_at(1)?, gas: d.val_at(2)?, action: d.val_at(3)?, value: d.val_at(4)?, data: d.val_at(5)?, }, v: d.val_at(6)?, r: d.val_at(7)?, s: d.val_at(8)?, hash: hash, }) } } impl Encodable for UnverifiedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) } } impl UnverifiedTransaction { /// Used to compute hash of created transactions fn compute_hash(mut self) -> UnverifiedTransaction { let hash = (&*self.rlp_bytes()).sha3(); self.hash = hash; self } /// Append object with a signature into RLP stream fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { s.begin_list(9); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); s.append(&self.v); s.append(&self.r); s.append(&self.s); } /// Reference to unsigned part of this transaction. pub fn as_unsigned(&self) -> &Transaction { &self.unsigned } /// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid. pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } } /// The `v` value that appears in the RLP. pub fn original_v(&self) -> u64 { self.v } /// The network ID, or `None` if this is a global transaction. pub fn network_id(&self) -> Option<u64> { match self.v { v if v > 36 => Some((v - 35) / 2), _ => None, } } /// Construct a signature object from the sig. pub fn signature(&self) -> Signature { Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v()) } /// Checks whether the signature has a low's' value. pub fn check_low_s(&self) -> Result<(), Error> { if!self.signature().is_low_s() { Err(EthkeyError::InvalidSignature.into()) } else { Ok(()) } } /// Get the hash of this header (sha3 of the RLP). pub fn hash(&self) -> H256 { self.hash } /// Recovers the public key of the sender. pub fn recover_public(&self) -> Result<Public, Error> { Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?) } /// Do basic validation, checking for valid signature and minimum gas, // TODO: consider use in block validation. #[cfg(test)] #[cfg(feature = "json-tests")] pub fn validate(self, schedule: &Schedule, require_low: bool, allow_network_id_of_one: bool) -> Result<UnverifiedTransaction, Error> { if require_low &&!self.signature().is_low_s() { return Err(EthkeyError::InvalidSignature.into()) } match self.network_id() { None => {}, Some(1) if allow_network_id_of_one => {}, _ => return Err(TransactionError::InvalidNetworkId.into()), } self.recover_public()?; if self.gas < U256::from(self.gas_required(&schedule)) { Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into()) } else { Ok(self) } } } /// A `UnverifiedTransaction` with successfully recovered `sender`. #[derive(Debug, Clone, Eq, PartialEq)] pub struct SignedTransaction { transaction: UnverifiedTransaction, sender: Address, public: Public, } impl HeapSizeOf for SignedTransaction { fn heap_size_of_children(&self) -> usize { self.transaction.unsigned.heap_size_of_children() } } impl Encodable for SignedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.transaction.rlp_append_sealed_transaction(s) } } impl Deref for SignedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.transaction } } impl From<SignedTransaction> for UnverifiedTransaction { fn from(tx: SignedTransaction) -> Self { tx.transaction } } impl SignedTransaction { /// Try to verify transaction and recover sender. pub fn new(transaction: UnverifiedTransaction) -> Result<Self, Error> { let public = transaction.recover_public()?; let sender = public_to_address(&public); Ok(SignedTransaction { transaction: transaction, sender: sender, public: public, }) } /// Returns transaction sender. pub fn sender(&self) -> Address { self.sender } /// Returns a public key of the sender. pub fn public_key(&self) -> Public { self.public } } /// Signed Transaction that is a part of canon blockchain. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct LocalizedTransaction { /// Signed part. pub signed: UnverifiedTransaction, /// Block number. pub block_number: BlockNumber, /// Block hash. pub block_hash: H256, /// Transaction index within block. pub transaction_index: usize, /// Cached sender pub cached_sender: Option<Address>, } impl LocalizedTransaction { /// Returns transaction sender. /// Panics if `LocalizedTransaction` is constructed using invalid `UnverifiedTransaction`. pub fn sender(&mut self) -> Address { if let Some(sender) = self.cached_sender { return sender; } let sender = public_to_address(&self.recover_public() .expect("LocalizedTransaction is always constructed from transaction from blockchain; Blockchain only stores verified transactions; qed")); self.cached_sender = Some(sender); sender } } impl Deref for LocalizedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.signed } } /// Queued transaction with additional information. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct PendingTransaction { /// Signed transaction data. pub transaction: SignedTransaction, /// To be activated at this condition. `None` for immediately. pub condition: Option<Condition>, } impl PendingTransaction { /// Create a new pending transaction from signed transaction. pub fn new(signed: SignedTransaction, condition: Option<Condition>) -> Self { PendingTransaction { transaction: signed, condition: condition, } } } impl Deref for PendingTransaction { type Target = SignedTransaction; fn deref(&self) -> &SignedTransaction { &self.transaction } } impl From<SignedTransaction> for PendingTransaction { fn from(t: SignedTransaction) -> Self { PendingTransaction { transaction: t, condition: None, } } } #[test] fn sender_test() { let t: UnverifiedTransaction = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(t.data, b""); assert_eq!(t.gas, U256::from(0x5208u64)); assert_eq!(t.gas_price, U256::from(0x01u64)); assert_eq!(t.nonce, U256::from(0x00u64)); if let Action::Call(ref to) = t.action { assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into()); } else { panic!(); } assert_eq!(t.value, U256::from(0x0au64)); assert_eq!(public_to_address(&t.recover_public().unwrap()), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into()); assert_eq!(t.network_id(), None); } #[test] fn signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), None); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn fake_signing() { let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.fake_sign(Address::from(0x69)); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); let t = t.clone(); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn should_recover_from_network_specific_signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), Some(69)); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), Some(69)); } #[test] fn should_agree_with_vitalik() { use rustc_serialize::hex::FromHex; let test_vector = |tx_data: &str, address: &'static str| { let signed = decode(&FromHex::from_hex(tx_data).unwrap()); let signed = SignedTransaction::new(signed).unwrap(); assert_eq!(signed.sender(), address.into()); flushln!("networkid: {:?}", signed.network_id()); }; test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce"); test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112"); test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be"); test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0"); test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554"); test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4"); test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35"); test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332"); test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029"); test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f"); }
random_line_split
transaction.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Transaction data structure. use std::ops::Deref; use rlp::*; use util::sha3::Hashable; use util::{H256, Address, U256, Bytes, HeapSizeOf}; use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError}; use error::*; use evm::Schedule; use header::BlockNumber; use ethjson; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] /// Transaction action type. pub enum Action { /// Create creates new contract. Create, /// Calls contract at given address. /// In the case of a transfer, this is the receiver's address.' Call(Address), } impl Default for Action { fn default() -> Action { Action::Create } } impl Decodable for Action { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let rlp = decoder.as_rlp(); if rlp.is_empty() { Ok(Action::Create) } else { Ok(Action::Call(rlp.as_val()?)) } } } /// Transaction activation condition. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub enum Condition { /// Valid at this block number or later. Number(BlockNumber), /// Valid at this unix time or later. Timestamp(u64), } /// A set of information describing an externally-originating message call /// or contract creation operation. #[derive(Default, Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct Transaction { /// Nonce. pub nonce: U256, /// Gas price. pub gas_price: U256, /// Gas paid up front for transaction execution. pub gas: U256, /// Action, can be either call or contract create. pub action: Action, /// Transfered value. pub value: U256, /// Transaction data. pub data: Bytes, } impl Transaction { /// Append object with a without signature into RLP stream pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream, network_id: Option<u64>) { s.begin_list(if network_id.is_none() { 6 } else { 9 }); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); if let Some(n) = network_id { s.append(&n); s.append(&0u8); s.append(&0u8); } } } impl HeapSizeOf for Transaction { fn heap_size_of_children(&self) -> usize { self.data.heap_size_of_children() } } impl From<ethjson::state::Transaction> for SignedTransaction { fn from(t: ethjson::state::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); let secret = Secret::from_slice(&t.secret.0).expect("Valid secret expected."); Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }.sign(&secret, None) } } impl From<ethjson::transaction::Transaction> for UnverifiedTransaction { fn from(t: ethjson::transaction::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); UnverifiedTransaction { unsigned: Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }, r: t.r.into(), s: t.s.into(), v: t.v.into(), hash: 0.into(), }.compute_hash() } } impl Transaction { /// The message hash of the transaction. pub fn hash(&self, network_id: Option<u64>) -> H256 { let mut stream = RlpStream::new(); self.rlp_append_unsigned_transaction(&mut stream, network_id); stream.as_raw().sha3() } /// Signs the transaction as coming from `sender`. pub fn sign(self, secret: &Secret, network_id: Option<u64>) -> SignedTransaction { let sig = ::ethkey::sign(secret, &self.hash(network_id)) .expect("data is valid and context has signing capabilities; qed"); SignedTransaction::new(self.with_signature(sig, network_id)) .expect("secret is valid so it's recoverable") } /// Signs the transaction with signature. pub fn with_signature(self, sig: Signature, network_id: Option<u64>) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: sig.r().into(), s: sig.s().into(), v: sig.v() as u64 + if let Some(n) = network_id { 35 + n * 2 } else { 27 }, hash: 0.into(), }.compute_hash() } /// Useful for test incorrectly signed transactions. #[cfg(test)] pub fn invalid_sign(self) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash() } /// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned. pub fn fake_sign(self, from: Address) -> SignedTransaction { SignedTransaction { transaction: UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash(), sender: from, public: Public::default(), } } /// Get the transaction cost in gas for the given params. pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 { data.iter().fold( (if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64, |g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64 ) } /// Get the transaction cost in gas for this transaction. pub fn gas_required(&self, schedule: &Schedule) -> u64 { Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule) } } /// Signed transaction information. #[derive(Debug, Clone, Eq, PartialEq)] #[cfg_attr(feature = "ipc", binary)] pub struct UnverifiedTransaction { /// Plain Transaction. unsigned: Transaction, /// The V field of the signature; the LS bit described which half of the curve our point falls /// in. The MS bits describe which network this transaction is for. If 27/28, its for all networks. v: u64, /// The R field of the signature; helps describe the point on the curve. r: U256, /// The S field of the signature; helps describe the point on the curve. s: U256, /// Hash of the transaction hash: H256, } impl Deref for UnverifiedTransaction { type Target = Transaction; fn deref(&self) -> &Self::Target { &self.unsigned } } impl Decodable for UnverifiedTransaction { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); if d.item_count()!= 9 { return Err(DecoderError::RlpIncorrectListLen); } let hash = decoder.as_raw().sha3(); Ok(UnverifiedTransaction { unsigned: Transaction { nonce: d.val_at(0)?, gas_price: d.val_at(1)?, gas: d.val_at(2)?, action: d.val_at(3)?, value: d.val_at(4)?, data: d.val_at(5)?, }, v: d.val_at(6)?, r: d.val_at(7)?, s: d.val_at(8)?, hash: hash, }) } } impl Encodable for UnverifiedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) } } impl UnverifiedTransaction { /// Used to compute hash of created transactions fn compute_hash(mut self) -> UnverifiedTransaction { let hash = (&*self.rlp_bytes()).sha3(); self.hash = hash; self } /// Append object with a signature into RLP stream fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { s.begin_list(9); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); s.append(&self.v); s.append(&self.r); s.append(&self.s); } /// Reference to unsigned part of this transaction. pub fn as_unsigned(&self) -> &Transaction { &self.unsigned } /// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid. pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } } /// The `v` value that appears in the RLP. pub fn original_v(&self) -> u64 { self.v } /// The network ID, or `None` if this is a global transaction. pub fn network_id(&self) -> Option<u64> { match self.v { v if v > 36 => Some((v - 35) / 2), _ => None, } } /// Construct a signature object from the sig. pub fn signature(&self) -> Signature { Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v()) } /// Checks whether the signature has a low's' value. pub fn check_low_s(&self) -> Result<(), Error> { if!self.signature().is_low_s()
else { Ok(()) } } /// Get the hash of this header (sha3 of the RLP). pub fn hash(&self) -> H256 { self.hash } /// Recovers the public key of the sender. pub fn recover_public(&self) -> Result<Public, Error> { Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?) } /// Do basic validation, checking for valid signature and minimum gas, // TODO: consider use in block validation. #[cfg(test)] #[cfg(feature = "json-tests")] pub fn validate(self, schedule: &Schedule, require_low: bool, allow_network_id_of_one: bool) -> Result<UnverifiedTransaction, Error> { if require_low &&!self.signature().is_low_s() { return Err(EthkeyError::InvalidSignature.into()) } match self.network_id() { None => {}, Some(1) if allow_network_id_of_one => {}, _ => return Err(TransactionError::InvalidNetworkId.into()), } self.recover_public()?; if self.gas < U256::from(self.gas_required(&schedule)) { Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into()) } else { Ok(self) } } } /// A `UnverifiedTransaction` with successfully recovered `sender`. #[derive(Debug, Clone, Eq, PartialEq)] pub struct SignedTransaction { transaction: UnverifiedTransaction, sender: Address, public: Public, } impl HeapSizeOf for SignedTransaction { fn heap_size_of_children(&self) -> usize { self.transaction.unsigned.heap_size_of_children() } } impl Encodable for SignedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.transaction.rlp_append_sealed_transaction(s) } } impl Deref for SignedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.transaction } } impl From<SignedTransaction> for UnverifiedTransaction { fn from(tx: SignedTransaction) -> Self { tx.transaction } } impl SignedTransaction { /// Try to verify transaction and recover sender. pub fn new(transaction: UnverifiedTransaction) -> Result<Self, Error> { let public = transaction.recover_public()?; let sender = public_to_address(&public); Ok(SignedTransaction { transaction: transaction, sender: sender, public: public, }) } /// Returns transaction sender. pub fn sender(&self) -> Address { self.sender } /// Returns a public key of the sender. pub fn public_key(&self) -> Public { self.public } } /// Signed Transaction that is a part of canon blockchain. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct LocalizedTransaction { /// Signed part. pub signed: UnverifiedTransaction, /// Block number. pub block_number: BlockNumber, /// Block hash. pub block_hash: H256, /// Transaction index within block. pub transaction_index: usize, /// Cached sender pub cached_sender: Option<Address>, } impl LocalizedTransaction { /// Returns transaction sender. /// Panics if `LocalizedTransaction` is constructed using invalid `UnverifiedTransaction`. pub fn sender(&mut self) -> Address { if let Some(sender) = self.cached_sender { return sender; } let sender = public_to_address(&self.recover_public() .expect("LocalizedTransaction is always constructed from transaction from blockchain; Blockchain only stores verified transactions; qed")); self.cached_sender = Some(sender); sender } } impl Deref for LocalizedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.signed } } /// Queued transaction with additional information. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct PendingTransaction { /// Signed transaction data. pub transaction: SignedTransaction, /// To be activated at this condition. `None` for immediately. pub condition: Option<Condition>, } impl PendingTransaction { /// Create a new pending transaction from signed transaction. pub fn new(signed: SignedTransaction, condition: Option<Condition>) -> Self { PendingTransaction { transaction: signed, condition: condition, } } } impl Deref for PendingTransaction { type Target = SignedTransaction; fn deref(&self) -> &SignedTransaction { &self.transaction } } impl From<SignedTransaction> for PendingTransaction { fn from(t: SignedTransaction) -> Self { PendingTransaction { transaction: t, condition: None, } } } #[test] fn sender_test() { let t: UnverifiedTransaction = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(t.data, b""); assert_eq!(t.gas, U256::from(0x5208u64)); assert_eq!(t.gas_price, U256::from(0x01u64)); assert_eq!(t.nonce, U256::from(0x00u64)); if let Action::Call(ref to) = t.action { assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into()); } else { panic!(); } assert_eq!(t.value, U256::from(0x0au64)); assert_eq!(public_to_address(&t.recover_public().unwrap()), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into()); assert_eq!(t.network_id(), None); } #[test] fn signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), None); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn fake_signing() { let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.fake_sign(Address::from(0x69)); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); let t = t.clone(); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn should_recover_from_network_specific_signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), Some(69)); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), Some(69)); } #[test] fn should_agree_with_vitalik() { use rustc_serialize::hex::FromHex; let test_vector = |tx_data: &str, address: &'static str| { let signed = decode(&FromHex::from_hex(tx_data).unwrap()); let signed = SignedTransaction::new(signed).unwrap(); assert_eq!(signed.sender(), address.into()); flushln!("networkid: {:?}", signed.network_id()); }; test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce"); test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112"); test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be"); test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0"); test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554"); test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4"); test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35"); test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332"); test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029"); test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f"); }
{ Err(EthkeyError::InvalidSignature.into()) }
conditional_block
be_true.rs
use matchers::matcher::Matcher; #[derive(Copy, Clone)] pub struct BeTrue { file_line: (&'static str, u32) } impl Matcher<bool> for BeTrue { #[allow(unused_variables)] fn assert_check(&self, expected: bool) -> bool { expected == true } #[allow(unused_variables)] fn msg(&self, expected: bool) -> String { format!("Expected {} to be true but it was not.", stringify!(expected)) } #[allow(unused_variables)] fn
(&self, expected: bool) -> String { format!("Expected {} NOT to be true but it was.", stringify!(expected)) } fn get_file_line(&self) -> (&'static str, u32) { self.file_line } } pub fn be_true(file_line: (&'static str, u32)) -> Box<BeTrue> { Box::new(BeTrue { file_line: file_line }) } #[macro_export] macro_rules! be_true( () => ( be_true((file!(), expand_line!())) ); );
negated_msg
identifier_name
be_true.rs
use matchers::matcher::Matcher; #[derive(Copy, Clone)] pub struct BeTrue { file_line: (&'static str, u32) }
#[allow(unused_variables)] fn assert_check(&self, expected: bool) -> bool { expected == true } #[allow(unused_variables)] fn msg(&self, expected: bool) -> String { format!("Expected {} to be true but it was not.", stringify!(expected)) } #[allow(unused_variables)] fn negated_msg(&self, expected: bool) -> String { format!("Expected {} NOT to be true but it was.", stringify!(expected)) } fn get_file_line(&self) -> (&'static str, u32) { self.file_line } } pub fn be_true(file_line: (&'static str, u32)) -> Box<BeTrue> { Box::new(BeTrue { file_line: file_line }) } #[macro_export] macro_rules! be_true( () => ( be_true((file!(), expand_line!())) ); );
impl Matcher<bool> for BeTrue {
random_line_split
be_true.rs
use matchers::matcher::Matcher; #[derive(Copy, Clone)] pub struct BeTrue { file_line: (&'static str, u32) } impl Matcher<bool> for BeTrue { #[allow(unused_variables)] fn assert_check(&self, expected: bool) -> bool { expected == true } #[allow(unused_variables)] fn msg(&self, expected: bool) -> String { format!("Expected {} to be true but it was not.", stringify!(expected)) } #[allow(unused_variables)] fn negated_msg(&self, expected: bool) -> String
fn get_file_line(&self) -> (&'static str, u32) { self.file_line } } pub fn be_true(file_line: (&'static str, u32)) -> Box<BeTrue> { Box::new(BeTrue { file_line: file_line }) } #[macro_export] macro_rules! be_true( () => ( be_true((file!(), expand_line!())) ); );
{ format!("Expected {} NOT to be true but it was.", stringify!(expected)) }
identifier_body
recent_data.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use libc::c_char; use glib::translate::{ToGlib, ToGlibPtr, Stash}; pub struct RecentData { display_name: String, description: String, mime_type: String, app_name: String, app_exec: String, groups: Vec<String>, is_private: bool } impl<'a> ToGlibPtr<'a, *mut ffi::GtkRecentData> for &'a RecentData { type Storage = (Box<ffi::GtkRecentData>, [Stash<'a, *const c_char, String>; 5], Stash<'a, *mut *const c_char, &'a [String]>); fn
(&self) -> Stash<'a, *mut ffi::GtkRecentData, &'a RecentData> { let display_name = self.display_name.to_glib_none(); let description = self.description.to_glib_none(); let mime_type = self.mime_type.to_glib_none(); let app_name = self.app_name.to_glib_none(); let app_exec = self.app_exec.to_glib_none(); let groups = (&*self.groups).to_glib_none(); let mut data = Box::new(ffi::GtkRecentData { display_name: display_name.0 as *mut c_char, description: description.0 as *mut c_char, mime_type: mime_type.0 as *mut c_char, app_name: app_name.0 as *mut c_char, app_exec: app_exec.0 as *mut c_char, groups: groups.0 as *mut *mut c_char, is_private: self.is_private.to_glib(), }); Stash(&mut *data, (data, [display_name, description, mime_type, app_name, app_exec], groups)) } }
to_glib_none
identifier_name
recent_data.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use libc::c_char; use glib::translate::{ToGlib, ToGlibPtr, Stash}; pub struct RecentData { display_name: String, description: String, mime_type: String, app_name: String, app_exec: String, groups: Vec<String>, is_private: bool } impl<'a> ToGlibPtr<'a, *mut ffi::GtkRecentData> for &'a RecentData { type Storage = (Box<ffi::GtkRecentData>, [Stash<'a, *const c_char, String>; 5], Stash<'a, *mut *const c_char, &'a [String]>); fn to_glib_none(&self) -> Stash<'a, *mut ffi::GtkRecentData, &'a RecentData>
} }
{ let display_name = self.display_name.to_glib_none(); let description = self.description.to_glib_none(); let mime_type = self.mime_type.to_glib_none(); let app_name = self.app_name.to_glib_none(); let app_exec = self.app_exec.to_glib_none(); let groups = (&*self.groups).to_glib_none(); let mut data = Box::new(ffi::GtkRecentData { display_name: display_name.0 as *mut c_char, description: description.0 as *mut c_char, mime_type: mime_type.0 as *mut c_char, app_name: app_name.0 as *mut c_char, app_exec: app_exec.0 as *mut c_char, groups: groups.0 as *mut *mut c_char, is_private: self.is_private.to_glib(), }); Stash(&mut *data, (data, [display_name, description, mime_type, app_name, app_exec], groups))
identifier_body
recent_data.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use libc::c_char; use glib::translate::{ToGlib, ToGlibPtr, Stash}; pub struct RecentData { display_name: String, description: String, mime_type: String, app_name: String, app_exec: String, groups: Vec<String>, is_private: bool } impl<'a> ToGlibPtr<'a, *mut ffi::GtkRecentData> for &'a RecentData { type Storage = (Box<ffi::GtkRecentData>, [Stash<'a, *const c_char, String>; 5], Stash<'a, *mut *const c_char, &'a [String]>); fn to_glib_none(&self) -> Stash<'a, *mut ffi::GtkRecentData, &'a RecentData> { let display_name = self.display_name.to_glib_none(); let description = self.description.to_glib_none(); let mime_type = self.mime_type.to_glib_none(); let app_name = self.app_name.to_glib_none(); let app_exec = self.app_exec.to_glib_none();
mime_type: mime_type.0 as *mut c_char, app_name: app_name.0 as *mut c_char, app_exec: app_exec.0 as *mut c_char, groups: groups.0 as *mut *mut c_char, is_private: self.is_private.to_glib(), }); Stash(&mut *data, (data, [display_name, description, mime_type, app_name, app_exec], groups)) } }
let groups = (&*self.groups).to_glib_none(); let mut data = Box::new(ffi::GtkRecentData { display_name: display_name.0 as *mut c_char, description: description.0 as *mut c_char,
random_line_split
rustoleum.rs
use std::io::{stdin, File}; use std::io::buffered::BufferedReader; use std::str::{from_utf8}; use std::os;
println("Usage: rustoleum [arguments] path/to/input/file"); println("-i (I)nteractive mode"); println("-wpm N Display N words per (m)inute (default: 300)"); println("-wpl N Display N words per (l)ine (default: 1)"); println("-h Display this (h)elp"); } fn get_args_interactive () -> (uint, uint, Path) { let mut reader = BufferedReader::new(stdin()); println("Input path to file to read: "); let input = reader.read_line().unwrap_or(~"data/example.txt"); let p = Path::new(input.trim()); println("Input WPM: "); let input = reader.read_line().unwrap(); let WPM = from_str::<uint>(input.trim()).unwrap_or(300); println("Input the number of words to view at a time: "); let input = reader.read_line().unwrap(); let WPL = from_str::<uint>(input.trim()).unwrap_or(1); (WPM, WPL, p) } fn get_vals (args: ~[~str]) -> (uint, uint, Path){ if args.contains(&~"-i"){ get_args_interactive() } else { let fallbackfile = &~"data/example.txt"; let path = args.tail().last_opt().unwrap_or(fallbackfile); let p = Path::new(path.as_slice()); let WPM = get_arg(&args, &~"-wpm", 300); let WPL = get_arg(&args, &~"-wpl", 300); (WPM,WPL,p) } } fn get_arg (args: &~[~str], flag: &~str, default: uint) -> uint { from_str::<uint>(args[1 + args.position_elem(flag).unwrap_or(-1)]).unwrap_or(default) } fn print_file(WPM: uint, WPL: uint, p: Path){ if p.exists(){ let contents = File::open(&p).read_to_end(); let mut string_iter = from_utf8(contents).words(); let string_vec = string_iter.to_owned_vec(); let sleep_time = (60000 / WPM * WPL) as u64; for words in string_vec.chunks(WPL) { println("\x1bc".into_owned().append(words.connect(" "))); std::io::timer::sleep(sleep_time); } } else { println("The path specified does not exist. Please specify a valid path, or run rustoleum -h for help."); println("Calling rustoleum with no arguments will display data/example.txt at 300 WPM, with 1 word per line."); } } fn main () { if os::args().contains(&~"-h"){ print_usage(); } else { let (WPM, WPL, p) = get_vals(os::args()); print_file(WPM, WPL, p); } }
fn print_usage () { println("A tool to keep your reading skills bright and shiny.");
random_line_split
rustoleum.rs
use std::io::{stdin, File}; use std::io::buffered::BufferedReader; use std::str::{from_utf8}; use std::os; fn print_usage () { println("A tool to keep your reading skills bright and shiny."); println("Usage: rustoleum [arguments] path/to/input/file"); println("-i (I)nteractive mode"); println("-wpm N Display N words per (m)inute (default: 300)"); println("-wpl N Display N words per (l)ine (default: 1)"); println("-h Display this (h)elp"); } fn get_args_interactive () -> (uint, uint, Path) { let mut reader = BufferedReader::new(stdin()); println("Input path to file to read: "); let input = reader.read_line().unwrap_or(~"data/example.txt"); let p = Path::new(input.trim()); println("Input WPM: "); let input = reader.read_line().unwrap(); let WPM = from_str::<uint>(input.trim()).unwrap_or(300); println("Input the number of words to view at a time: "); let input = reader.read_line().unwrap(); let WPL = from_str::<uint>(input.trim()).unwrap_or(1); (WPM, WPL, p) } fn get_vals (args: ~[~str]) -> (uint, uint, Path){ if args.contains(&~"-i"){ get_args_interactive() } else { let fallbackfile = &~"data/example.txt"; let path = args.tail().last_opt().unwrap_or(fallbackfile); let p = Path::new(path.as_slice()); let WPM = get_arg(&args, &~"-wpm", 300); let WPL = get_arg(&args, &~"-wpl", 300); (WPM,WPL,p) } } fn get_arg (args: &~[~str], flag: &~str, default: uint) -> uint { from_str::<uint>(args[1 + args.position_elem(flag).unwrap_or(-1)]).unwrap_or(default) } fn print_file(WPM: uint, WPL: uint, p: Path)
fn main () { if os::args().contains(&~"-h"){ print_usage(); } else { let (WPM, WPL, p) = get_vals(os::args()); print_file(WPM, WPL, p); } }
{ if p.exists(){ let contents = File::open(&p).read_to_end(); let mut string_iter = from_utf8(contents).words(); let string_vec = string_iter.to_owned_vec(); let sleep_time = (60000 / WPM * WPL) as u64; for words in string_vec.chunks(WPL) { println("\x1bc".into_owned().append(words.connect(" "))); std::io::timer::sleep(sleep_time); } } else { println("The path specified does not exist. Please specify a valid path, or run rustoleum -h for help."); println("Calling rustoleum with no arguments will display data/example.txt at 300 WPM, with 1 word per line."); } }
identifier_body
rustoleum.rs
use std::io::{stdin, File}; use std::io::buffered::BufferedReader; use std::str::{from_utf8}; use std::os; fn print_usage () { println("A tool to keep your reading skills bright and shiny."); println("Usage: rustoleum [arguments] path/to/input/file"); println("-i (I)nteractive mode"); println("-wpm N Display N words per (m)inute (default: 300)"); println("-wpl N Display N words per (l)ine (default: 1)"); println("-h Display this (h)elp"); } fn get_args_interactive () -> (uint, uint, Path) { let mut reader = BufferedReader::new(stdin()); println("Input path to file to read: "); let input = reader.read_line().unwrap_or(~"data/example.txt"); let p = Path::new(input.trim()); println("Input WPM: "); let input = reader.read_line().unwrap(); let WPM = from_str::<uint>(input.trim()).unwrap_or(300); println("Input the number of words to view at a time: "); let input = reader.read_line().unwrap(); let WPL = from_str::<uint>(input.trim()).unwrap_or(1); (WPM, WPL, p) } fn get_vals (args: ~[~str]) -> (uint, uint, Path){ if args.contains(&~"-i"){ get_args_interactive() } else { let fallbackfile = &~"data/example.txt"; let path = args.tail().last_opt().unwrap_or(fallbackfile); let p = Path::new(path.as_slice()); let WPM = get_arg(&args, &~"-wpm", 300); let WPL = get_arg(&args, &~"-wpl", 300); (WPM,WPL,p) } } fn
(args: &~[~str], flag: &~str, default: uint) -> uint { from_str::<uint>(args[1 + args.position_elem(flag).unwrap_or(-1)]).unwrap_or(default) } fn print_file(WPM: uint, WPL: uint, p: Path){ if p.exists(){ let contents = File::open(&p).read_to_end(); let mut string_iter = from_utf8(contents).words(); let string_vec = string_iter.to_owned_vec(); let sleep_time = (60000 / WPM * WPL) as u64; for words in string_vec.chunks(WPL) { println("\x1bc".into_owned().append(words.connect(" "))); std::io::timer::sleep(sleep_time); } } else { println("The path specified does not exist. Please specify a valid path, or run rustoleum -h for help."); println("Calling rustoleum with no arguments will display data/example.txt at 300 WPM, with 1 word per line."); } } fn main () { if os::args().contains(&~"-h"){ print_usage(); } else { let (WPM, WPL, p) = get_vals(os::args()); print_file(WPM, WPL, p); } }
get_arg
identifier_name
rustoleum.rs
use std::io::{stdin, File}; use std::io::buffered::BufferedReader; use std::str::{from_utf8}; use std::os; fn print_usage () { println("A tool to keep your reading skills bright and shiny."); println("Usage: rustoleum [arguments] path/to/input/file"); println("-i (I)nteractive mode"); println("-wpm N Display N words per (m)inute (default: 300)"); println("-wpl N Display N words per (l)ine (default: 1)"); println("-h Display this (h)elp"); } fn get_args_interactive () -> (uint, uint, Path) { let mut reader = BufferedReader::new(stdin()); println("Input path to file to read: "); let input = reader.read_line().unwrap_or(~"data/example.txt"); let p = Path::new(input.trim()); println("Input WPM: "); let input = reader.read_line().unwrap(); let WPM = from_str::<uint>(input.trim()).unwrap_or(300); println("Input the number of words to view at a time: "); let input = reader.read_line().unwrap(); let WPL = from_str::<uint>(input.trim()).unwrap_or(1); (WPM, WPL, p) } fn get_vals (args: ~[~str]) -> (uint, uint, Path){ if args.contains(&~"-i"){ get_args_interactive() } else
} fn get_arg (args: &~[~str], flag: &~str, default: uint) -> uint { from_str::<uint>(args[1 + args.position_elem(flag).unwrap_or(-1)]).unwrap_or(default) } fn print_file(WPM: uint, WPL: uint, p: Path){ if p.exists(){ let contents = File::open(&p).read_to_end(); let mut string_iter = from_utf8(contents).words(); let string_vec = string_iter.to_owned_vec(); let sleep_time = (60000 / WPM * WPL) as u64; for words in string_vec.chunks(WPL) { println("\x1bc".into_owned().append(words.connect(" "))); std::io::timer::sleep(sleep_time); } } else { println("The path specified does not exist. Please specify a valid path, or run rustoleum -h for help."); println("Calling rustoleum with no arguments will display data/example.txt at 300 WPM, with 1 word per line."); } } fn main () { if os::args().contains(&~"-h"){ print_usage(); } else { let (WPM, WPL, p) = get_vals(os::args()); print_file(WPM, WPL, p); } }
{ let fallbackfile = &~"data/example.txt"; let path = args.tail().last_opt().unwrap_or(fallbackfile); let p = Path::new(path.as_slice()); let WPM = get_arg(&args, &~"-wpm", 300); let WPL = get_arg(&args, &~"-wpl", 300); (WPM,WPL,p) }
conditional_block
local_image_cache.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/. */ /*! An adapter for ImageCacheTask that does local caching to avoid extra message traffic, it also avoids waiting on the same image multiple times and thus triggering reflows multiple times. */ use image_cache_task::{Decode, GetImage, ImageCacheTask, ImageFailed, ImageNotReady, ImageReady}; use image_cache_task::{ImageResponseMsg, Prefetch, WaitForImage}; use std::comm; use std::comm::Port; use std::task; use servo_util::url::{UrlMap, url_map}; use extra::url::Url; pub fn LocalImageCache(image_cache_task: ImageCacheTask) -> LocalImageCache { LocalImageCache { image_cache_task: image_cache_task, round_number: 1, on_image_available: None, state_map: url_map() } } pub struct LocalImageCache { priv image_cache_task: ImageCacheTask, priv round_number: uint, priv on_image_available: Option<~fn() -> ~fn(ImageResponseMsg)>, priv state_map: UrlMap<@mut ImageState> } struct ImageState { prefetched: bool, decoded: bool, last_request_round: uint, last_response: ImageResponseMsg } impl LocalImageCache { /// The local cache will only do a single remote request for a given /// URL in each 'round'. Layout should call this each time it begins pub fn next_round(&mut self, on_image_available: ~fn() -> ~fn(ImageResponseMsg)) { self.round_number += 1; self.on_image_available = Some(on_image_available); } pub fn prefetch(&self, url: &Url) { let state = self.get_state(url); if!state.prefetched { self.image_cache_task.send(Prefetch((*url).clone())); state.prefetched = true; } } pub fn
(&self, url: &Url) { let state = self.get_state(url); if!state.decoded { self.image_cache_task.send(Decode((*url).clone())); state.decoded = true; } } // FIXME: Should return a Future pub fn get_image(&self, url: &Url) -> Port<ImageResponseMsg> { let state = self.get_state(url); // Save the previous round number for comparison let last_round = state.last_request_round; // Set the current round number for this image state.last_request_round = self.round_number; match state.last_response { ImageReady(ref image) => { let (port, chan) = comm::stream(); chan.send(ImageReady(image.clone())); return port; } ImageNotReady => { if last_round == self.round_number { let (port, chan) = comm::stream(); chan.send(ImageNotReady); return port; } else { // We haven't requested the image from the // remote cache this round } } ImageFailed => { let (port, chan) = comm::stream(); chan.send(ImageFailed); return port; } } let (response_port, response_chan) = comm::stream(); self.image_cache_task.send(GetImage((*url).clone(), response_chan)); let response = response_port.recv(); match response { ImageNotReady => { // Need to reflow when the image is available // FIXME: Instead we should be just passing a Future // to the caller, then to the display list. Finally, // the compositor should be resonsible for waiting // on the image to load and triggering layout let image_cache_task = self.image_cache_task.clone(); assert!(self.on_image_available.is_some()); let on_image_available = (*self.on_image_available.get_ref())(); let url = (*url).clone(); do task::spawn { let (response_port, response_chan) = comm::stream(); image_cache_task.send(WaitForImage(url.clone(), response_chan)); on_image_available(response_port.recv()); } } _ => () } // Put a copy of the response in the cache let response_copy = match response { ImageReady(ref image) => ImageReady(image.clone()), ImageNotReady => ImageNotReady, ImageFailed => ImageFailed }; state.last_response = response_copy; let (port, chan) = comm::stream(); chan.send(response); return port; } fn get_state(&self, url: &Url) -> @mut ImageState { let state = do self.state_map.find_or_insert_with(url.clone()) |_| { let new_state = @mut ImageState { prefetched: false, decoded: false, last_request_round: 0, last_response: ImageNotReady }; new_state }; *state // Unborrowing the state } }
decode
identifier_name
local_image_cache.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/. */ /*! An adapter for ImageCacheTask that does local caching to avoid extra message traffic, it also avoids waiting on the same image multiple times and thus triggering reflows multiple times. */ use image_cache_task::{Decode, GetImage, ImageCacheTask, ImageFailed, ImageNotReady, ImageReady}; use image_cache_task::{ImageResponseMsg, Prefetch, WaitForImage}; use std::comm; use std::comm::Port; use std::task; use servo_util::url::{UrlMap, url_map}; use extra::url::Url; pub fn LocalImageCache(image_cache_task: ImageCacheTask) -> LocalImageCache { LocalImageCache { image_cache_task: image_cache_task, round_number: 1, on_image_available: None, state_map: url_map() } }
} struct ImageState { prefetched: bool, decoded: bool, last_request_round: uint, last_response: ImageResponseMsg } impl LocalImageCache { /// The local cache will only do a single remote request for a given /// URL in each 'round'. Layout should call this each time it begins pub fn next_round(&mut self, on_image_available: ~fn() -> ~fn(ImageResponseMsg)) { self.round_number += 1; self.on_image_available = Some(on_image_available); } pub fn prefetch(&self, url: &Url) { let state = self.get_state(url); if!state.prefetched { self.image_cache_task.send(Prefetch((*url).clone())); state.prefetched = true; } } pub fn decode(&self, url: &Url) { let state = self.get_state(url); if!state.decoded { self.image_cache_task.send(Decode((*url).clone())); state.decoded = true; } } // FIXME: Should return a Future pub fn get_image(&self, url: &Url) -> Port<ImageResponseMsg> { let state = self.get_state(url); // Save the previous round number for comparison let last_round = state.last_request_round; // Set the current round number for this image state.last_request_round = self.round_number; match state.last_response { ImageReady(ref image) => { let (port, chan) = comm::stream(); chan.send(ImageReady(image.clone())); return port; } ImageNotReady => { if last_round == self.round_number { let (port, chan) = comm::stream(); chan.send(ImageNotReady); return port; } else { // We haven't requested the image from the // remote cache this round } } ImageFailed => { let (port, chan) = comm::stream(); chan.send(ImageFailed); return port; } } let (response_port, response_chan) = comm::stream(); self.image_cache_task.send(GetImage((*url).clone(), response_chan)); let response = response_port.recv(); match response { ImageNotReady => { // Need to reflow when the image is available // FIXME: Instead we should be just passing a Future // to the caller, then to the display list. Finally, // the compositor should be resonsible for waiting // on the image to load and triggering layout let image_cache_task = self.image_cache_task.clone(); assert!(self.on_image_available.is_some()); let on_image_available = (*self.on_image_available.get_ref())(); let url = (*url).clone(); do task::spawn { let (response_port, response_chan) = comm::stream(); image_cache_task.send(WaitForImage(url.clone(), response_chan)); on_image_available(response_port.recv()); } } _ => () } // Put a copy of the response in the cache let response_copy = match response { ImageReady(ref image) => ImageReady(image.clone()), ImageNotReady => ImageNotReady, ImageFailed => ImageFailed }; state.last_response = response_copy; let (port, chan) = comm::stream(); chan.send(response); return port; } fn get_state(&self, url: &Url) -> @mut ImageState { let state = do self.state_map.find_or_insert_with(url.clone()) |_| { let new_state = @mut ImageState { prefetched: false, decoded: false, last_request_round: 0, last_response: ImageNotReady }; new_state }; *state // Unborrowing the state } }
pub struct LocalImageCache { priv image_cache_task: ImageCacheTask, priv round_number: uint, priv on_image_available: Option<~fn() -> ~fn(ImageResponseMsg)>, priv state_map: UrlMap<@mut ImageState>
random_line_split
mod.rs
macro_rules! os_required { () => { panic!("mio must be compiled with `os-poll` to run.") }; } mod selector; pub(crate) use self::selector::{event, Event, Events, Selector}; mod waker; pub(crate) use self::waker::Waker; cfg_net! { pub(crate) mod tcp; pub(crate) mod udp; #[cfg(unix)] pub(crate) mod uds; } cfg_io_source! { use std::io; #[cfg(windows)] use std::os::windows::io::RawSocket; #[cfg(windows)]
pub(crate) struct IoSourceState; impl IoSourceState { pub fn new() -> IoSourceState { IoSourceState } pub fn do_io<T, F, R>(&self, f: F, io: &T) -> io::Result<R> where F: FnOnce(&T) -> io::Result<R>, { // We don't hold state, so we can just call the function and // return. f(io) } } #[cfg(windows)] impl IoSourceState { pub fn register( &mut self, _: &Registry, _: Token, _: Interest, _: RawSocket, ) -> io::Result<()> { os_required!() } pub fn reregister( &mut self, _: &Registry, _: Token, _: Interest, ) -> io::Result<()> { os_required!() } pub fn deregister(&mut self) -> io::Result<()> { os_required!() } } }
use crate::{Registry, Token, Interest};
random_line_split
utils.rs
// Copyright 2019 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::mem; use std::sync::Arc; use super::error::*; use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState}; use crate::utils::AsyncJobQueue; use crate::utils::FailHandle; use base::{error, warn}; use usb_util::{Device, Transfer, TransferStatus}; /// Helper function to update xhci_transfer state. pub fn update_transfer_state( xhci_transfer: &Arc<XhciTransfer>, usb_transfer: &Transfer, ) -> Result<()> { let status = usb_transfer.status(); let mut state = xhci_transfer.state().lock(); if status == TransferStatus::Cancelled { *state = XhciTransferState::Cancelled; return Ok(()); } match *state { XhciTransferState::Cancelling => { *state = XhciTransferState::Cancelled; } XhciTransferState::Submitted {.. } => { *state = XhciTransferState::Completed; } _ => { error!("xhci trasfer state is invalid"); *state = XhciTransferState::Completed; return Err(Error::BadXhciTransferState); } } Ok(()) } /// Helper function to submit usb_transfer to device handle. pub fn submit_transfer( fail_handle: Arc<dyn FailHandle>, job_queue: &Arc<AsyncJobQueue>, xhci_transfer: Arc<XhciTransfer>, device: &mut Device, usb_transfer: Transfer, ) -> Result<()> { let transfer_status = { // We need to hold the lock to avoid race condition. // While we are trying to submit the transfer, another thread might want to cancel the same // transfer. Holding the lock here makes sure one of them is cancelled. let mut state = xhci_transfer.state().lock(); match mem::replace(&mut *state, XhciTransferState::Cancelled) { XhciTransferState::Created => { match device.submit_transfer(usb_transfer) { Err(e) => { error!("fail to submit transfer {:?}", e); *state = XhciTransferState::Completed; TransferStatus::NoDevice } // If it's submitted, we don't need to send on_transfer_complete now. Ok(canceller) => { let cancel_callback = Box::new(move || match canceller.cancel() { Ok(()) => { usb_debug!("cancel issued to kernel"); } Err(e) =>
}); *state = XhciTransferState::Submitted { cancel_callback }; return Ok(()); } } } XhciTransferState::Cancelled => { warn!("Transfer is already cancelled"); TransferStatus::Cancelled } _ => { // The transfer could not be in the following states: // Submitted: A transfer should only be submitted once. // Cancelling: Transfer is cancelling only when it's submitted and someone is // trying to cancel it. // Completed: A completed transfer should not be submitted again. error!("xhci trasfer state is invalid"); return Err(Error::BadXhciTransferState); } } }; // We are holding locks to of backends, we want to call on_transfer_complete // without any lock. job_queue .queue_job( move || match xhci_transfer.on_transfer_complete(&transfer_status, 0) { Ok(_) => {} Err(e) => { error!("transfer complete failed: {:?}", e); fail_handle.fail(); } }, ) .map_err(Error::QueueAsyncJob) }
{ usb_debug!("fail to cancel: {}", e); }
conditional_block
utils.rs
// Copyright 2019 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::mem; use std::sync::Arc; use super::error::*; use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState}; use crate::utils::AsyncJobQueue; use crate::utils::FailHandle; use base::{error, warn}; use usb_util::{Device, Transfer, TransferStatus}; /// Helper function to update xhci_transfer state. pub fn update_transfer_state( xhci_transfer: &Arc<XhciTransfer>, usb_transfer: &Transfer, ) -> Result<()>
} } Ok(()) } /// Helper function to submit usb_transfer to device handle. pub fn submit_transfer( fail_handle: Arc<dyn FailHandle>, job_queue: &Arc<AsyncJobQueue>, xhci_transfer: Arc<XhciTransfer>, device: &mut Device, usb_transfer: Transfer, ) -> Result<()> { let transfer_status = { // We need to hold the lock to avoid race condition. // While we are trying to submit the transfer, another thread might want to cancel the same // transfer. Holding the lock here makes sure one of them is cancelled. let mut state = xhci_transfer.state().lock(); match mem::replace(&mut *state, XhciTransferState::Cancelled) { XhciTransferState::Created => { match device.submit_transfer(usb_transfer) { Err(e) => { error!("fail to submit transfer {:?}", e); *state = XhciTransferState::Completed; TransferStatus::NoDevice } // If it's submitted, we don't need to send on_transfer_complete now. Ok(canceller) => { let cancel_callback = Box::new(move || match canceller.cancel() { Ok(()) => { usb_debug!("cancel issued to kernel"); } Err(e) => { usb_debug!("fail to cancel: {}", e); } }); *state = XhciTransferState::Submitted { cancel_callback }; return Ok(()); } } } XhciTransferState::Cancelled => { warn!("Transfer is already cancelled"); TransferStatus::Cancelled } _ => { // The transfer could not be in the following states: // Submitted: A transfer should only be submitted once. // Cancelling: Transfer is cancelling only when it's submitted and someone is // trying to cancel it. // Completed: A completed transfer should not be submitted again. error!("xhci trasfer state is invalid"); return Err(Error::BadXhciTransferState); } } }; // We are holding locks to of backends, we want to call on_transfer_complete // without any lock. job_queue .queue_job( move || match xhci_transfer.on_transfer_complete(&transfer_status, 0) { Ok(_) => {} Err(e) => { error!("transfer complete failed: {:?}", e); fail_handle.fail(); } }, ) .map_err(Error::QueueAsyncJob) }
{ let status = usb_transfer.status(); let mut state = xhci_transfer.state().lock(); if status == TransferStatus::Cancelled { *state = XhciTransferState::Cancelled; return Ok(()); } match *state { XhciTransferState::Cancelling => { *state = XhciTransferState::Cancelled; } XhciTransferState::Submitted { .. } => { *state = XhciTransferState::Completed; } _ => { error!("xhci trasfer state is invalid"); *state = XhciTransferState::Completed; return Err(Error::BadXhciTransferState);
identifier_body
utils.rs
// Copyright 2019 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::mem; use std::sync::Arc; use super::error::*; use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState}; use crate::utils::AsyncJobQueue; use crate::utils::FailHandle; use base::{error, warn}; use usb_util::{Device, Transfer, TransferStatus}; /// Helper function to update xhci_transfer state. pub fn update_transfer_state( xhci_transfer: &Arc<XhciTransfer>, usb_transfer: &Transfer, ) -> Result<()> { let status = usb_transfer.status(); let mut state = xhci_transfer.state().lock(); if status == TransferStatus::Cancelled { *state = XhciTransferState::Cancelled; return Ok(()); } match *state { XhciTransferState::Cancelling => { *state = XhciTransferState::Cancelled; } XhciTransferState::Submitted {.. } => { *state = XhciTransferState::Completed; } _ => { error!("xhci trasfer state is invalid"); *state = XhciTransferState::Completed; return Err(Error::BadXhciTransferState); } } Ok(()) } /// Helper function to submit usb_transfer to device handle. pub fn
( fail_handle: Arc<dyn FailHandle>, job_queue: &Arc<AsyncJobQueue>, xhci_transfer: Arc<XhciTransfer>, device: &mut Device, usb_transfer: Transfer, ) -> Result<()> { let transfer_status = { // We need to hold the lock to avoid race condition. // While we are trying to submit the transfer, another thread might want to cancel the same // transfer. Holding the lock here makes sure one of them is cancelled. let mut state = xhci_transfer.state().lock(); match mem::replace(&mut *state, XhciTransferState::Cancelled) { XhciTransferState::Created => { match device.submit_transfer(usb_transfer) { Err(e) => { error!("fail to submit transfer {:?}", e); *state = XhciTransferState::Completed; TransferStatus::NoDevice } // If it's submitted, we don't need to send on_transfer_complete now. Ok(canceller) => { let cancel_callback = Box::new(move || match canceller.cancel() { Ok(()) => { usb_debug!("cancel issued to kernel"); } Err(e) => { usb_debug!("fail to cancel: {}", e); } }); *state = XhciTransferState::Submitted { cancel_callback }; return Ok(()); } } } XhciTransferState::Cancelled => { warn!("Transfer is already cancelled"); TransferStatus::Cancelled } _ => { // The transfer could not be in the following states: // Submitted: A transfer should only be submitted once. // Cancelling: Transfer is cancelling only when it's submitted and someone is // trying to cancel it. // Completed: A completed transfer should not be submitted again. error!("xhci trasfer state is invalid"); return Err(Error::BadXhciTransferState); } } }; // We are holding locks to of backends, we want to call on_transfer_complete // without any lock. job_queue .queue_job( move || match xhci_transfer.on_transfer_complete(&transfer_status, 0) { Ok(_) => {} Err(e) => { error!("transfer complete failed: {:?}", e); fail_handle.fail(); } }, ) .map_err(Error::QueueAsyncJob) }
submit_transfer
identifier_name
utils.rs
// Copyright 2019 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::mem; use std::sync::Arc; use super::error::*; use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState}; use crate::utils::AsyncJobQueue; use crate::utils::FailHandle; use base::{error, warn}; use usb_util::{Device, Transfer, TransferStatus}; /// Helper function to update xhci_transfer state. pub fn update_transfer_state( xhci_transfer: &Arc<XhciTransfer>, usb_transfer: &Transfer, ) -> Result<()> { let status = usb_transfer.status(); let mut state = xhci_transfer.state().lock(); if status == TransferStatus::Cancelled { *state = XhciTransferState::Cancelled; return Ok(()); } match *state { XhciTransferState::Cancelling => { *state = XhciTransferState::Cancelled; } XhciTransferState::Submitted {.. } => { *state = XhciTransferState::Completed; } _ => { error!("xhci trasfer state is invalid"); *state = XhciTransferState::Completed; return Err(Error::BadXhciTransferState); } } Ok(()) } /// Helper function to submit usb_transfer to device handle. pub fn submit_transfer( fail_handle: Arc<dyn FailHandle>, job_queue: &Arc<AsyncJobQueue>, xhci_transfer: Arc<XhciTransfer>, device: &mut Device, usb_transfer: Transfer, ) -> Result<()> { let transfer_status = { // We need to hold the lock to avoid race condition. // While we are trying to submit the transfer, another thread might want to cancel the same // transfer. Holding the lock here makes sure one of them is cancelled. let mut state = xhci_transfer.state().lock(); match mem::replace(&mut *state, XhciTransferState::Cancelled) { XhciTransferState::Created => { match device.submit_transfer(usb_transfer) { Err(e) => { error!("fail to submit transfer {:?}", e); *state = XhciTransferState::Completed; TransferStatus::NoDevice } // If it's submitted, we don't need to send on_transfer_complete now. Ok(canceller) => { let cancel_callback = Box::new(move || match canceller.cancel() { Ok(()) => { usb_debug!("cancel issued to kernel"); } Err(e) => { usb_debug!("fail to cancel: {}", e); } }); *state = XhciTransferState::Submitted { cancel_callback }; return Ok(()); } } } XhciTransferState::Cancelled => { warn!("Transfer is already cancelled"); TransferStatus::Cancelled
// trying to cancel it. // Completed: A completed transfer should not be submitted again. error!("xhci trasfer state is invalid"); return Err(Error::BadXhciTransferState); } } }; // We are holding locks to of backends, we want to call on_transfer_complete // without any lock. job_queue .queue_job( move || match xhci_transfer.on_transfer_complete(&transfer_status, 0) { Ok(_) => {} Err(e) => { error!("transfer complete failed: {:?}", e); fail_handle.fail(); } }, ) .map_err(Error::QueueAsyncJob) }
} _ => { // The transfer could not be in the following states: // Submitted: A transfer should only be submitted once. // Cancelling: Transfer is cancelling only when it's submitted and someone is
random_line_split
xcore.rs
//! Contains xcore-specific types use core::convert::From; use core::{cmp, fmt, slice}; // XXX todo(tmfink): create rusty versions pub use capstone_sys::xcore_insn_group as XcoreInsnGroup; pub use capstone_sys::xcore_insn as XcoreInsn; pub use capstone_sys::xcore_reg as XcoreReg; use capstone_sys::{cs_xcore, cs_xcore_op, xcore_op_mem, xcore_op_type}; pub use crate::arch::arch_builder::xcore::*; use crate::arch::DetailsArchInsn; use crate::instruction::{RegId, RegIdInt}; /// Contains XCORE-specific details for an instruction pub struct XcoreInsnDetail<'a>(pub(crate) &'a cs_xcore); impl_PartialEq_repr_fields!(XcoreInsnDetail<'a> [ 'a ]; operands ); /// XCORE operand #[derive(Clone, Debug, Eq, PartialEq)] pub enum XcoreOperand { /// Register Reg(RegId), /// Immediate Imm(i32), /// Memory Mem(XcoreOpMem), /// Invalid Invalid, } impl Default for XcoreOperand { fn default() -> Self { XcoreOperand::Invalid } } /// XCORE memory operand #[derive(Debug, Copy, Clone)] pub struct XcoreOpMem(pub(crate) xcore_op_mem); impl XcoreOpMem { /// Base register pub fn base(&self) -> RegId
/// Index register pub fn index(&self) -> RegId { RegId(RegIdInt::from(self.0.index)) } /// Disp value pub fn disp(&self) -> i32 { self.0.disp } /// Direct value pub fn direct(&self) -> i32 { self.0.direct } } impl_PartialEq_repr_fields!(XcoreOpMem; base, index, disp, direct ); impl cmp::Eq for XcoreOpMem {} impl<'a> From<&'a cs_xcore_op> for XcoreOperand { fn from(insn: &cs_xcore_op) -> XcoreOperand { match insn.type_ { xcore_op_type::XCORE_OP_REG => { XcoreOperand::Reg(RegId(unsafe { insn.__bindgen_anon_1.reg } as RegIdInt)) } xcore_op_type::XCORE_OP_IMM => XcoreOperand::Imm(unsafe { insn.__bindgen_anon_1.imm }), xcore_op_type::XCORE_OP_MEM => { XcoreOperand::Mem(XcoreOpMem(unsafe { insn.__bindgen_anon_1.mem })) } xcore_op_type::XCORE_OP_INVALID => XcoreOperand::Invalid, } } } def_arch_details_struct!( InsnDetail = XcoreInsnDetail; Operand = XcoreOperand; OperandIterator = XcoreOperandIterator; OperandIteratorLife = XcoreOperandIterator<'a>; [ pub struct XcoreOperandIterator<'a>(slice::Iter<'a, cs_xcore_op>); ] cs_arch_op = cs_xcore_op; cs_arch = cs_xcore; );
{ RegId(RegIdInt::from(self.0.base)) }
identifier_body
xcore.rs
//! Contains xcore-specific types use core::convert::From; use core::{cmp, fmt, slice}; // XXX todo(tmfink): create rusty versions pub use capstone_sys::xcore_insn_group as XcoreInsnGroup; pub use capstone_sys::xcore_insn as XcoreInsn; pub use capstone_sys::xcore_reg as XcoreReg; use capstone_sys::{cs_xcore, cs_xcore_op, xcore_op_mem, xcore_op_type}; pub use crate::arch::arch_builder::xcore::*; use crate::arch::DetailsArchInsn; use crate::instruction::{RegId, RegIdInt}; /// Contains XCORE-specific details for an instruction pub struct XcoreInsnDetail<'a>(pub(crate) &'a cs_xcore); impl_PartialEq_repr_fields!(XcoreInsnDetail<'a> [ 'a ]; operands ); /// XCORE operand #[derive(Clone, Debug, Eq, PartialEq)] pub enum XcoreOperand { /// Register Reg(RegId), /// Immediate Imm(i32), /// Memory Mem(XcoreOpMem),
/// Invalid Invalid, } impl Default for XcoreOperand { fn default() -> Self { XcoreOperand::Invalid } } /// XCORE memory operand #[derive(Debug, Copy, Clone)] pub struct XcoreOpMem(pub(crate) xcore_op_mem); impl XcoreOpMem { /// Base register pub fn base(&self) -> RegId { RegId(RegIdInt::from(self.0.base)) } /// Index register pub fn index(&self) -> RegId { RegId(RegIdInt::from(self.0.index)) } /// Disp value pub fn disp(&self) -> i32 { self.0.disp } /// Direct value pub fn direct(&self) -> i32 { self.0.direct } } impl_PartialEq_repr_fields!(XcoreOpMem; base, index, disp, direct ); impl cmp::Eq for XcoreOpMem {} impl<'a> From<&'a cs_xcore_op> for XcoreOperand { fn from(insn: &cs_xcore_op) -> XcoreOperand { match insn.type_ { xcore_op_type::XCORE_OP_REG => { XcoreOperand::Reg(RegId(unsafe { insn.__bindgen_anon_1.reg } as RegIdInt)) } xcore_op_type::XCORE_OP_IMM => XcoreOperand::Imm(unsafe { insn.__bindgen_anon_1.imm }), xcore_op_type::XCORE_OP_MEM => { XcoreOperand::Mem(XcoreOpMem(unsafe { insn.__bindgen_anon_1.mem })) } xcore_op_type::XCORE_OP_INVALID => XcoreOperand::Invalid, } } } def_arch_details_struct!( InsnDetail = XcoreInsnDetail; Operand = XcoreOperand; OperandIterator = XcoreOperandIterator; OperandIteratorLife = XcoreOperandIterator<'a>; [ pub struct XcoreOperandIterator<'a>(slice::Iter<'a, cs_xcore_op>); ] cs_arch_op = cs_xcore_op; cs_arch = cs_xcore; );
random_line_split
xcore.rs
//! Contains xcore-specific types use core::convert::From; use core::{cmp, fmt, slice}; // XXX todo(tmfink): create rusty versions pub use capstone_sys::xcore_insn_group as XcoreInsnGroup; pub use capstone_sys::xcore_insn as XcoreInsn; pub use capstone_sys::xcore_reg as XcoreReg; use capstone_sys::{cs_xcore, cs_xcore_op, xcore_op_mem, xcore_op_type}; pub use crate::arch::arch_builder::xcore::*; use crate::arch::DetailsArchInsn; use crate::instruction::{RegId, RegIdInt}; /// Contains XCORE-specific details for an instruction pub struct XcoreInsnDetail<'a>(pub(crate) &'a cs_xcore); impl_PartialEq_repr_fields!(XcoreInsnDetail<'a> [ 'a ]; operands ); /// XCORE operand #[derive(Clone, Debug, Eq, PartialEq)] pub enum XcoreOperand { /// Register Reg(RegId), /// Immediate Imm(i32), /// Memory Mem(XcoreOpMem), /// Invalid Invalid, } impl Default for XcoreOperand { fn default() -> Self { XcoreOperand::Invalid } } /// XCORE memory operand #[derive(Debug, Copy, Clone)] pub struct
(pub(crate) xcore_op_mem); impl XcoreOpMem { /// Base register pub fn base(&self) -> RegId { RegId(RegIdInt::from(self.0.base)) } /// Index register pub fn index(&self) -> RegId { RegId(RegIdInt::from(self.0.index)) } /// Disp value pub fn disp(&self) -> i32 { self.0.disp } /// Direct value pub fn direct(&self) -> i32 { self.0.direct } } impl_PartialEq_repr_fields!(XcoreOpMem; base, index, disp, direct ); impl cmp::Eq for XcoreOpMem {} impl<'a> From<&'a cs_xcore_op> for XcoreOperand { fn from(insn: &cs_xcore_op) -> XcoreOperand { match insn.type_ { xcore_op_type::XCORE_OP_REG => { XcoreOperand::Reg(RegId(unsafe { insn.__bindgen_anon_1.reg } as RegIdInt)) } xcore_op_type::XCORE_OP_IMM => XcoreOperand::Imm(unsafe { insn.__bindgen_anon_1.imm }), xcore_op_type::XCORE_OP_MEM => { XcoreOperand::Mem(XcoreOpMem(unsafe { insn.__bindgen_anon_1.mem })) } xcore_op_type::XCORE_OP_INVALID => XcoreOperand::Invalid, } } } def_arch_details_struct!( InsnDetail = XcoreInsnDetail; Operand = XcoreOperand; OperandIterator = XcoreOperandIterator; OperandIteratorLife = XcoreOperandIterator<'a>; [ pub struct XcoreOperandIterator<'a>(slice::Iter<'a, cs_xcore_op>); ] cs_arch_op = cs_xcore_op; cs_arch = cs_xcore; );
XcoreOpMem
identifier_name
deriving-via-extension-struct.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. // run-pass #[derive(PartialEq, Debug)] struct
{ x: isize, y: isize, z: isize, } pub fn main() { let a = Foo { x: 1, y: 2, z: 3 }; let b = Foo { x: 1, y: 2, z: 3 }; assert_eq!(a, b); assert!(!(a!= b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); }
Foo
identifier_name
deriving-via-extension-struct.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. // run-pass #[derive(PartialEq, Debug)] struct Foo { x: isize, y: isize, z: isize, }
assert_eq!(a, b); assert!(!(a!= b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); }
pub fn main() { let a = Foo { x: 1, y: 2, z: 3 }; let b = Foo { x: 1, y: 2, z: 3 };
random_line_split
dynamic_lib.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Dynamic library facilities. //! //! A simple wrapper over the platform's dynamic library facilities #![unstable(feature = "std_misc")] #![allow(missing_docs)] use prelude::v1::*; use env; use ffi::{CString, OsString}; use mem; use path::{Path, PathBuf}; pub struct DynamicLibrary { handle: *mut u8 } impl Drop for DynamicLibrary { fn
(&mut self) { match dl::check_for_errors_in(|| { unsafe { dl::close(self.handle) } }) { Ok(()) => {}, Err(str) => panic!("{}", str) } } } impl DynamicLibrary { // FIXME (#12938): Until DST lands, we cannot decompose &str into // & and str, so we cannot usefully take ToCStr arguments by // reference (without forcing an additional & around &str). So we // are instead temporarily adding an instance for &Path, so that // we can take ToCStr as owned. When DST lands, the &Path instance // should be removed, and arguments bound by ToCStr should be // passed by reference. (Here: in the `open` method.) /// Lazily open a dynamic library. When passed None it gives a /// handle to the calling process pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> { let maybe_library = dl::open(filename.map(|path| path.as_os_str())); // The dynamic library must not be constructed if there is // an error opening the library so the destructor does not // run. match maybe_library { Err(err) => Err(err), Ok(handle) => Ok(DynamicLibrary { handle: handle }) } } /// Prepends a path to this process's search path for dynamic libraries pub fn prepend_search_path(path: &Path) { let mut search_path = DynamicLibrary::search_path(); search_path.insert(0, path.to_path_buf()); env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path)); } /// From a slice of paths, create a new vector which is suitable to be an /// environment variable for this platforms dylib search path. pub fn create_path(path: &[PathBuf]) -> OsString { let mut newvar = OsString::new(); for (i, path) in path.iter().enumerate() { if i > 0 { newvar.push(DynamicLibrary::separator()); } newvar.push(path); } return newvar; } /// Returns the environment variable for this process's dynamic library /// search path pub fn envvar() -> &'static str { if cfg!(windows) { "PATH" } else if cfg!(target_os = "macos") { "DYLD_LIBRARY_PATH" } else { "LD_LIBRARY_PATH" } } fn separator() -> &'static str { if cfg!(windows) { ";" } else { ":" } } /// Returns the current search path for dynamic libraries being used by this /// process pub fn search_path() -> Vec<PathBuf> { match env::var_os(DynamicLibrary::envvar()) { Some(var) => env::split_paths(&var).collect(), None => Vec::new(), } } /// Access the value at the symbol of the dynamic library pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented let raw_string = CString::new(symbol).unwrap(); let maybe_symbol_value = dl::check_for_errors_in(|| { dl::symbol(self.handle, raw_string.as_ptr()) }); // The value must not be constructed if there is an error so // the destructor does not run. match maybe_symbol_value { Err(err) => Err(err), Ok(symbol_value) => Ok(mem::transmute(symbol_value)) } } } #[cfg(all(test, not(target_os = "ios")))] mod test { use super::*; use prelude::v1::*; use libc; use mem; use path::Path; #[test] #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379 fn test_loading_cosine() { // The math library does not need to be loaded since it is already // statically linked in let libm = match DynamicLibrary::open(None) { Err(error) => panic!("Could not load self as module: {}", error), Ok(libm) => libm }; let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe { match libm.symbol("cos") { Err(error) => panic!("Could not load function cos: {}", error), Ok(cosine) => mem::transmute::<*mut u8, _>(cosine) } }; let argument = 0.0; let expected_result = 1.0; let result = cosine(argument); if result!= expected_result { panic!("cos({})!= {} but equaled {} instead", argument, expected_result, result) } } #[test] #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd"))] fn test_errors_do_not_crash() { // Open /dev/null as a library to get an error, and make sure // that only causes an error, and not a crash. let path = Path::new("/dev/null"); match DynamicLibrary::open(Some(&path)) { Err(_) => {} Ok(_) => panic!("Successfully opened the empty library.") } } } #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd"))] mod dl { use prelude::v1::*; use ffi::{CStr, OsStr}; use str; use libc; use ptr; pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { check_for_errors_in(|| { unsafe { match filename { Some(filename) => open_external(filename), None => open_internal(), } } }) } const LAZY: libc::c_int = 1; unsafe fn open_external(filename: &OsStr) -> *mut u8 { let s = filename.to_cstring().unwrap(); dlopen(s.as_ptr(), LAZY) as *mut u8 } unsafe fn open_internal() -> *mut u8 { dlopen(ptr::null(), LAZY) as *mut u8 } pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where F: FnOnce() -> T, { use sync::{StaticMutex, MUTEX_INIT}; static LOCK: StaticMutex = MUTEX_INIT; unsafe { // dlerror isn't thread safe, so we need to lock around this entire // sequence let _guard = LOCK.lock(); let _old_error = dlerror(); let result = f(); let last_error = dlerror() as *const _; let ret = if ptr::null() == last_error { Ok(result) } else { let s = CStr::from_ptr(last_error).to_bytes(); Err(str::from_utf8(s).unwrap().to_string()) }; ret } } pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 { dlsym(handle as *mut libc::c_void, symbol) as *mut u8 } pub unsafe fn close(handle: *mut u8) { dlclose(handle as *mut libc::c_void); () } extern { fn dlopen(filename: *const libc::c_char, flag: libc::c_int) -> *mut libc::c_void; fn dlerror() -> *mut libc::c_char; fn dlsym(handle: *mut libc::c_void, symbol: *const libc::c_char) -> *mut libc::c_void; fn dlclose(handle: *mut libc::c_void) -> libc::c_int; } } #[cfg(target_os = "windows")] mod dl { use ffi::OsStr; use iter::Iterator; use libc; use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED; use ops::FnOnce; use sys::os; use os::windows::prelude::*; use option::Option::{self, Some, None}; use ptr; use result::Result; use result::Result::{Ok, Err}; use string::String; use vec::Vec; use sys::c::compat::kernel32::SetThreadErrorMode; pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { // disable "dll load failed" error dialog. let mut use_thread_mode = true; let prev_error_mode = unsafe { // SEM_FAILCRITICALERRORS 0x01 let new_error_mode = 1; let mut prev_error_mode = 0; // Windows >= 7 supports thread error mode. let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode); if result == 0 { let err = os::errno(); if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED { use_thread_mode = false; // SetThreadErrorMode not found. use fallback solution: // SetErrorMode() Note that SetErrorMode is process-wide so // this can cause race condition! However, since even // Windows APIs do not care of such problem (#20650), we // just assume SetErrorMode race is not a great deal. prev_error_mode = SetErrorMode(new_error_mode); } } prev_error_mode }; unsafe { SetLastError(0); } let result = match filename { Some(filename) => { let filename_str: Vec<_> = filename.encode_wide().chain(Some(0).into_iter()).collect(); let result = unsafe { LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) }; // beware: Vec/String may change errno during drop! // so we get error here. if result == ptr::null_mut() { let errno = os::errno(); Err(os::error_string(errno)) } else { Ok(result as *mut u8) } } None => { let mut handle = ptr::null_mut(); let succeeded = unsafe { GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle) }; if succeeded == libc::FALSE { let errno = os::errno(); Err(os::error_string(errno)) } else { Ok(handle as *mut u8) } } }; unsafe { if use_thread_mode { SetThreadErrorMode(prev_error_mode, ptr::null_mut()); } else { SetErrorMode(prev_error_mode); } } result } pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where F: FnOnce() -> T, { unsafe { SetLastError(0); let result = f(); let error = os::errno(); if 0 == error { Ok(result) } else { Err(format!("Error code {}", error)) } } } pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 { GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8 } pub unsafe fn close(handle: *mut u8) { FreeLibrary(handle as *mut libc::c_void); () } #[allow(non_snake_case)] extern "system" { fn SetLastError(error: libc::size_t); fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void; fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16, handle: *mut *mut libc::c_void) -> libc::BOOL; fn GetProcAddress(handle: *mut libc::c_void, name: *const libc::c_char) -> *mut libc::c_void; fn FreeLibrary(handle: *mut libc::c_void); fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint; } }
drop
identifier_name
dynamic_lib.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Dynamic library facilities. //! //! A simple wrapper over the platform's dynamic library facilities #![unstable(feature = "std_misc")] #![allow(missing_docs)] use prelude::v1::*; use env; use ffi::{CString, OsString}; use mem; use path::{Path, PathBuf}; pub struct DynamicLibrary { handle: *mut u8 } impl Drop for DynamicLibrary { fn drop(&mut self) { match dl::check_for_errors_in(|| { unsafe { dl::close(self.handle) } }) { Ok(()) => {}, Err(str) => panic!("{}", str) } } } impl DynamicLibrary { // FIXME (#12938): Until DST lands, we cannot decompose &str into // & and str, so we cannot usefully take ToCStr arguments by // reference (without forcing an additional & around &str). So we // are instead temporarily adding an instance for &Path, so that // we can take ToCStr as owned. When DST lands, the &Path instance // should be removed, and arguments bound by ToCStr should be // passed by reference. (Here: in the `open` method.) /// Lazily open a dynamic library. When passed None it gives a /// handle to the calling process pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> { let maybe_library = dl::open(filename.map(|path| path.as_os_str())); // The dynamic library must not be constructed if there is // an error opening the library so the destructor does not // run. match maybe_library { Err(err) => Err(err), Ok(handle) => Ok(DynamicLibrary { handle: handle }) } } /// Prepends a path to this process's search path for dynamic libraries pub fn prepend_search_path(path: &Path) { let mut search_path = DynamicLibrary::search_path(); search_path.insert(0, path.to_path_buf()); env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path)); } /// From a slice of paths, create a new vector which is suitable to be an /// environment variable for this platforms dylib search path. pub fn create_path(path: &[PathBuf]) -> OsString { let mut newvar = OsString::new(); for (i, path) in path.iter().enumerate() { if i > 0 { newvar.push(DynamicLibrary::separator()); } newvar.push(path); } return newvar; } /// Returns the environment variable for this process's dynamic library /// search path pub fn envvar() -> &'static str { if cfg!(windows) { "PATH" } else if cfg!(target_os = "macos") { "DYLD_LIBRARY_PATH" } else { "LD_LIBRARY_PATH" } } fn separator() -> &'static str { if cfg!(windows) { ";" } else { ":" } } /// Returns the current search path for dynamic libraries being used by this /// process pub fn search_path() -> Vec<PathBuf> { match env::var_os(DynamicLibrary::envvar()) { Some(var) => env::split_paths(&var).collect(), None => Vec::new(), } } /// Access the value at the symbol of the dynamic library pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented let raw_string = CString::new(symbol).unwrap(); let maybe_symbol_value = dl::check_for_errors_in(|| { dl::symbol(self.handle, raw_string.as_ptr()) }); // The value must not be constructed if there is an error so // the destructor does not run. match maybe_symbol_value { Err(err) => Err(err), Ok(symbol_value) => Ok(mem::transmute(symbol_value)) } } } #[cfg(all(test, not(target_os = "ios")))] mod test { use super::*; use prelude::v1::*; use libc; use mem; use path::Path; #[test] #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379 fn test_loading_cosine() { // The math library does not need to be loaded since it is already // statically linked in let libm = match DynamicLibrary::open(None) { Err(error) => panic!("Could not load self as module: {}", error), Ok(libm) => libm }; let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe { match libm.symbol("cos") { Err(error) => panic!("Could not load function cos: {}", error), Ok(cosine) => mem::transmute::<*mut u8, _>(cosine) } }; let argument = 0.0; let expected_result = 1.0; let result = cosine(argument); if result!= expected_result { panic!("cos({})!= {} but equaled {} instead", argument, expected_result, result) } } #[test] #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd"))] fn test_errors_do_not_crash() { // Open /dev/null as a library to get an error, and make sure // that only causes an error, and not a crash. let path = Path::new("/dev/null"); match DynamicLibrary::open(Some(&path)) { Err(_) => {} Ok(_) => panic!("Successfully opened the empty library.") } } } #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd"))] mod dl { use prelude::v1::*; use ffi::{CStr, OsStr}; use str; use libc; use ptr; pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { check_for_errors_in(|| { unsafe { match filename { Some(filename) => open_external(filename), None => open_internal(), } } }) } const LAZY: libc::c_int = 1; unsafe fn open_external(filename: &OsStr) -> *mut u8 { let s = filename.to_cstring().unwrap(); dlopen(s.as_ptr(), LAZY) as *mut u8 } unsafe fn open_internal() -> *mut u8 { dlopen(ptr::null(), LAZY) as *mut u8 } pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where F: FnOnce() -> T, { use sync::{StaticMutex, MUTEX_INIT}; static LOCK: StaticMutex = MUTEX_INIT; unsafe { // dlerror isn't thread safe, so we need to lock around this entire // sequence let _guard = LOCK.lock(); let _old_error = dlerror(); let result = f(); let last_error = dlerror() as *const _; let ret = if ptr::null() == last_error { Ok(result) } else { let s = CStr::from_ptr(last_error).to_bytes(); Err(str::from_utf8(s).unwrap().to_string()) }; ret } } pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 { dlsym(handle as *mut libc::c_void, symbol) as *mut u8 } pub unsafe fn close(handle: *mut u8) { dlclose(handle as *mut libc::c_void); () } extern { fn dlopen(filename: *const libc::c_char, flag: libc::c_int) -> *mut libc::c_void; fn dlerror() -> *mut libc::c_char; fn dlsym(handle: *mut libc::c_void, symbol: *const libc::c_char) -> *mut libc::c_void; fn dlclose(handle: *mut libc::c_void) -> libc::c_int; } } #[cfg(target_os = "windows")] mod dl { use ffi::OsStr; use iter::Iterator; use libc; use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED; use ops::FnOnce; use sys::os; use os::windows::prelude::*; use option::Option::{self, Some, None}; use ptr; use result::Result; use result::Result::{Ok, Err}; use string::String; use vec::Vec; use sys::c::compat::kernel32::SetThreadErrorMode; pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { // disable "dll load failed" error dialog. let mut use_thread_mode = true; let prev_error_mode = unsafe { // SEM_FAILCRITICALERRORS 0x01 let new_error_mode = 1; let mut prev_error_mode = 0; // Windows >= 7 supports thread error mode. let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode); if result == 0 { let err = os::errno(); if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED { use_thread_mode = false; // SetThreadErrorMode not found. use fallback solution: // SetErrorMode() Note that SetErrorMode is process-wide so // this can cause race condition! However, since even // Windows APIs do not care of such problem (#20650), we // just assume SetErrorMode race is not a great deal. prev_error_mode = SetErrorMode(new_error_mode); } } prev_error_mode }; unsafe { SetLastError(0); } let result = match filename { Some(filename) => { let filename_str: Vec<_> = filename.encode_wide().chain(Some(0).into_iter()).collect(); let result = unsafe { LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) }; // beware: Vec/String may change errno during drop! // so we get error here. if result == ptr::null_mut() { let errno = os::errno(); Err(os::error_string(errno)) } else { Ok(result as *mut u8) } } None => { let mut handle = ptr::null_mut(); let succeeded = unsafe { GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle) }; if succeeded == libc::FALSE { let errno = os::errno(); Err(os::error_string(errno)) } else { Ok(handle as *mut u8) } } };
} } result } pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where F: FnOnce() -> T, { unsafe { SetLastError(0); let result = f(); let error = os::errno(); if 0 == error { Ok(result) } else { Err(format!("Error code {}", error)) } } } pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 { GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8 } pub unsafe fn close(handle: *mut u8) { FreeLibrary(handle as *mut libc::c_void); () } #[allow(non_snake_case)] extern "system" { fn SetLastError(error: libc::size_t); fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void; fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16, handle: *mut *mut libc::c_void) -> libc::BOOL; fn GetProcAddress(handle: *mut libc::c_void, name: *const libc::c_char) -> *mut libc::c_void; fn FreeLibrary(handle: *mut libc::c_void); fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint; } }
unsafe { if use_thread_mode { SetThreadErrorMode(prev_error_mode, ptr::null_mut()); } else { SetErrorMode(prev_error_mode);
random_line_split
dynamic_lib.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Dynamic library facilities. //! //! A simple wrapper over the platform's dynamic library facilities #![unstable(feature = "std_misc")] #![allow(missing_docs)] use prelude::v1::*; use env; use ffi::{CString, OsString}; use mem; use path::{Path, PathBuf}; pub struct DynamicLibrary { handle: *mut u8 } impl Drop for DynamicLibrary { fn drop(&mut self) { match dl::check_for_errors_in(|| { unsafe { dl::close(self.handle) } }) { Ok(()) => {}, Err(str) => panic!("{}", str) } } } impl DynamicLibrary { // FIXME (#12938): Until DST lands, we cannot decompose &str into // & and str, so we cannot usefully take ToCStr arguments by // reference (without forcing an additional & around &str). So we // are instead temporarily adding an instance for &Path, so that // we can take ToCStr as owned. When DST lands, the &Path instance // should be removed, and arguments bound by ToCStr should be // passed by reference. (Here: in the `open` method.) /// Lazily open a dynamic library. When passed None it gives a /// handle to the calling process pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> { let maybe_library = dl::open(filename.map(|path| path.as_os_str())); // The dynamic library must not be constructed if there is // an error opening the library so the destructor does not // run. match maybe_library { Err(err) => Err(err), Ok(handle) => Ok(DynamicLibrary { handle: handle }) } } /// Prepends a path to this process's search path for dynamic libraries pub fn prepend_search_path(path: &Path) { let mut search_path = DynamicLibrary::search_path(); search_path.insert(0, path.to_path_buf()); env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path)); } /// From a slice of paths, create a new vector which is suitable to be an /// environment variable for this platforms dylib search path. pub fn create_path(path: &[PathBuf]) -> OsString { let mut newvar = OsString::new(); for (i, path) in path.iter().enumerate() { if i > 0 { newvar.push(DynamicLibrary::separator()); } newvar.push(path); } return newvar; } /// Returns the environment variable for this process's dynamic library /// search path pub fn envvar() -> &'static str { if cfg!(windows) { "PATH" } else if cfg!(target_os = "macos") { "DYLD_LIBRARY_PATH" } else { "LD_LIBRARY_PATH" } } fn separator() -> &'static str { if cfg!(windows) { ";" } else { ":" } } /// Returns the current search path for dynamic libraries being used by this /// process pub fn search_path() -> Vec<PathBuf> { match env::var_os(DynamicLibrary::envvar()) { Some(var) => env::split_paths(&var).collect(), None => Vec::new(), } } /// Access the value at the symbol of the dynamic library pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented let raw_string = CString::new(symbol).unwrap(); let maybe_symbol_value = dl::check_for_errors_in(|| { dl::symbol(self.handle, raw_string.as_ptr()) }); // The value must not be constructed if there is an error so // the destructor does not run. match maybe_symbol_value { Err(err) => Err(err), Ok(symbol_value) => Ok(mem::transmute(symbol_value)) } } } #[cfg(all(test, not(target_os = "ios")))] mod test { use super::*; use prelude::v1::*; use libc; use mem; use path::Path; #[test] #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379 fn test_loading_cosine() { // The math library does not need to be loaded since it is already // statically linked in let libm = match DynamicLibrary::open(None) { Err(error) => panic!("Could not load self as module: {}", error), Ok(libm) => libm }; let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe { match libm.symbol("cos") { Err(error) => panic!("Could not load function cos: {}", error), Ok(cosine) => mem::transmute::<*mut u8, _>(cosine) } }; let argument = 0.0; let expected_result = 1.0; let result = cosine(argument); if result!= expected_result { panic!("cos({})!= {} but equaled {} instead", argument, expected_result, result) } } #[test] #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd"))] fn test_errors_do_not_crash() { // Open /dev/null as a library to get an error, and make sure // that only causes an error, and not a crash. let path = Path::new("/dev/null"); match DynamicLibrary::open(Some(&path)) { Err(_) => {} Ok(_) => panic!("Successfully opened the empty library.") } } } #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd"))] mod dl { use prelude::v1::*; use ffi::{CStr, OsStr}; use str; use libc; use ptr; pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { check_for_errors_in(|| { unsafe { match filename { Some(filename) => open_external(filename), None => open_internal(), } } }) } const LAZY: libc::c_int = 1; unsafe fn open_external(filename: &OsStr) -> *mut u8 { let s = filename.to_cstring().unwrap(); dlopen(s.as_ptr(), LAZY) as *mut u8 } unsafe fn open_internal() -> *mut u8 { dlopen(ptr::null(), LAZY) as *mut u8 } pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where F: FnOnce() -> T, { use sync::{StaticMutex, MUTEX_INIT}; static LOCK: StaticMutex = MUTEX_INIT; unsafe { // dlerror isn't thread safe, so we need to lock around this entire // sequence let _guard = LOCK.lock(); let _old_error = dlerror(); let result = f(); let last_error = dlerror() as *const _; let ret = if ptr::null() == last_error { Ok(result) } else { let s = CStr::from_ptr(last_error).to_bytes(); Err(str::from_utf8(s).unwrap().to_string()) }; ret } } pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 { dlsym(handle as *mut libc::c_void, symbol) as *mut u8 } pub unsafe fn close(handle: *mut u8) { dlclose(handle as *mut libc::c_void); () } extern { fn dlopen(filename: *const libc::c_char, flag: libc::c_int) -> *mut libc::c_void; fn dlerror() -> *mut libc::c_char; fn dlsym(handle: *mut libc::c_void, symbol: *const libc::c_char) -> *mut libc::c_void; fn dlclose(handle: *mut libc::c_void) -> libc::c_int; } } #[cfg(target_os = "windows")] mod dl { use ffi::OsStr; use iter::Iterator; use libc; use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED; use ops::FnOnce; use sys::os; use os::windows::prelude::*; use option::Option::{self, Some, None}; use ptr; use result::Result; use result::Result::{Ok, Err}; use string::String; use vec::Vec; use sys::c::compat::kernel32::SetThreadErrorMode; pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { // disable "dll load failed" error dialog. let mut use_thread_mode = true; let prev_error_mode = unsafe { // SEM_FAILCRITICALERRORS 0x01 let new_error_mode = 1; let mut prev_error_mode = 0; // Windows >= 7 supports thread error mode. let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode); if result == 0 { let err = os::errno(); if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED { use_thread_mode = false; // SetThreadErrorMode not found. use fallback solution: // SetErrorMode() Note that SetErrorMode is process-wide so // this can cause race condition! However, since even // Windows APIs do not care of such problem (#20650), we // just assume SetErrorMode race is not a great deal. prev_error_mode = SetErrorMode(new_error_mode); } } prev_error_mode }; unsafe { SetLastError(0); } let result = match filename { Some(filename) => { let filename_str: Vec<_> = filename.encode_wide().chain(Some(0).into_iter()).collect(); let result = unsafe { LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) }; // beware: Vec/String may change errno during drop! // so we get error here. if result == ptr::null_mut() { let errno = os::errno(); Err(os::error_string(errno)) } else { Ok(result as *mut u8) } } None =>
}; unsafe { if use_thread_mode { SetThreadErrorMode(prev_error_mode, ptr::null_mut()); } else { SetErrorMode(prev_error_mode); } } result } pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where F: FnOnce() -> T, { unsafe { SetLastError(0); let result = f(); let error = os::errno(); if 0 == error { Ok(result) } else { Err(format!("Error code {}", error)) } } } pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 { GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8 } pub unsafe fn close(handle: *mut u8) { FreeLibrary(handle as *mut libc::c_void); () } #[allow(non_snake_case)] extern "system" { fn SetLastError(error: libc::size_t); fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void; fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16, handle: *mut *mut libc::c_void) -> libc::BOOL; fn GetProcAddress(handle: *mut libc::c_void, name: *const libc::c_char) -> *mut libc::c_void; fn FreeLibrary(handle: *mut libc::c_void); fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint; } }
{ let mut handle = ptr::null_mut(); let succeeded = unsafe { GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle) }; if succeeded == libc::FALSE { let errno = os::errno(); Err(os::error_string(errno)) } else { Ok(handle as *mut u8) } }
conditional_block
multiset.rs
string of length `len` pub fn new(len: usize) -> Subset { let mut sb = SubsetBuilder::new(); sb.pad_to_len(len); sb.build() } /// Mostly for testing. pub fn delete_from_string(&self, s: &str) -> String { let mut result = String::new(); for (b, e) in self.range_iter(CountMatcher::Zero) { result.push_str(&s[b..e]); } result } // Maybe Subset should be a pure data structure and this method should // be a method of Node. /// Builds a version of `s` with all the elements in this `Subset` deleted from it. pub fn delete_from<N: NodeInfo>(&self, s: &Node<N>) -> Node<N> { let mut b = TreeBuilder::new(); for (beg, end) in self.range_iter(CountMatcher::Zero) { s.push_subseq(&mut b, Interval::new(beg, end)); } b.build() } /// The length of the resulting sequence after deleting this subset. A /// convenience alias for `self.count(CountMatcher::Zero)` to reduce /// thinking about what that means in the cases where the length after /// delete is what you want to know. /// /// `self.delete_from_string(s).len() = self.len(s.len())` pub fn len_after_delete(&self) -> usize { self.count(CountMatcher::Zero) } /// Count the total length of all the segments matching `matcher`. pub fn count(&self, matcher: CountMatcher) -> usize { self.segments.iter().filter(|seg| matcher.matches(seg)).map(|seg| seg.len).sum() } /// Convenience alias for `self.count(CountMatcher::All)` pub fn len(&self) -> usize { self.count(CountMatcher::All) } /// Determine whether the subset is empty. /// In this case deleting it would do nothing. pub fn is_empty(&self) -> bool { (self.segments.is_empty()) || ((self.segments.len() == 1) && (self.segments[0].count == 0)) } /// Compute the union of two subsets. The count of an element in the /// result is the sum of the counts in the inputs. pub fn union(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count + zseg.b_count); } sb.build() } /// Compute the difference of two subsets. The count of an element in the /// result is the subtraction of the counts of other from self. pub fn subtract(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { assert!( zseg.a_count >= zseg.b_count, "can't subtract {} from {}", zseg.a_count, zseg.b_count ); sb.push_segment(zseg.len, zseg.a_count - zseg.b_count); } sb.build() } /// Compute the bitwise xor of two subsets, useful as a reversible /// difference. The count of an element in the result is the bitwise xor /// of the counts of the inputs. Unchanged segments will be 0. /// /// This works like set symmetric difference when all counts are 0 or 1 /// but it extends nicely to the case of larger counts. pub fn bitxor(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count ^ zseg.b_count); } sb.build() } /// Map the contents of `self` into the 0-regions of `other`. /// Precondition: `self.count(CountMatcher::All) == other.count(CountMatcher::Zero)` fn transform(&self, other: &Subset, union: bool) -> Subset { let mut sb = SubsetBuilder::new(); let mut seg_iter = self.segments.iter(); let mut cur_seg = Segment { len: 0, count: 0 }; for oseg in &other.segments { if oseg.count > 0 { sb.push_segment(oseg.len, if union { oseg.count } else { 0 }); } else { // fill 0-region with segments from self. let mut to_be_consumed = oseg.len; while to_be_consumed > 0 { if cur_seg.len == 0 { cur_seg = seg_iter .next() .expect("self must cover all 0-regions of other") .clone(); } // consume as much of the segment as possible and necessary let to_consume = cmp::min(cur_seg.len, to_be_consumed); sb.push_segment(to_consume, cur_seg.count); to_be_consumed -= to_consume; cur_seg.len -= to_consume; } } } assert_eq!(cur_seg.len, 0, "the 0-regions of other must be the size of self"); assert_eq!(seg_iter.next(), None, "the 0-regions of other must be the size of self"); sb.build() } /// Transform through coordinate transform represented by other. /// The equation satisfied is as follows: /// /// s1 = other.delete_from_string(s0) /// /// s2 = self.delete_from_string(s1) /// /// element in self.transform_expand(other).delete_from_string(s0) if (not in s1) or in s2 pub fn transform_expand(&self, other: &Subset) -> Subset { self.transform(other, false) } /// The same as taking transform_expand and then unioning with `other`. pub fn transform_union(&self, other: &Subset) -> Subset { self.transform(other, true) } /// Transform subset through other coordinate transform, shrinking. /// The following equation is satisfied: /// /// C = A.transform_expand(B) /// /// B.transform_shrink(C).delete_from_string(C.delete_from_string(s)) = /// A.delete_from_string(B.delete_from_string(s)) pub fn transform_shrink(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); // discard ZipSegments where the shrinking set has positive count for zseg in self.zip(other) { // TODO: should this actually do something like subtract counts? if zseg.b_count == 0 { sb.push_segment(zseg.len, zseg.a_count); } } sb.build() } /// Return an iterator over the ranges with a count matching the `matcher`. /// These will often be easier to work with than raw segments. pub fn range_iter(&self, matcher: CountMatcher) -> RangeIter { RangeIter { seg_iter: self.segments.iter(), consumed: 0, matcher } } /// Convenience alias for `self.range_iter(CountMatcher::Zero)`. /// Semantically iterates the ranges of the complement of this `Subset`. pub fn complement_iter(&self) -> RangeIter { self.range_iter(CountMatcher::Zero) } /// Return an iterator over `ZipSegment`s where each `ZipSegment` contains /// the count for both self and other in that range. The two `Subset`s /// must have the same total length. /// /// Each returned `ZipSegment` will differ in at least one count. pub fn zip<'a>(&'a self, other: &'a Subset) -> ZipIter<'a> { ZipIter { a_segs: self.segments.as_slice(), b_segs: other.segments.as_slice(), a_i: 0, b_i: 0, a_consumed: 0, b_consumed: 0, consumed: 0, } } /// Find the complement of this Subset. Every 0-count element will have a /// count of 1 and every non-zero element will have a count of 0. pub fn complement(&self) -> Subset { let mut sb = SubsetBuilder::new(); for seg in &self.segments { if seg.count == 0 { sb.push_segment(seg.len, 1); } else { sb.push_segment(seg.len, 0); } } sb.build() } /// Return a `Mapper` that can be use to map coordinates in the document to coordinates /// in this `Subset`, but only in non-decreasing order for performance reasons. pub fn mapper(&self, matcher: CountMatcher) -> Mapper { Mapper { range_iter: self.range_iter(matcher), last_i: 0, // indices only need to be in non-decreasing order, not increasing cur_range: (0, 0), // will immediately try to consume next range subset_amount_consumed: 0, } } } impl fmt::Debug for Subset { /// Use the alternate flag (`#`) to print a more compact representation /// where each character represents the count of one element: /// '-' is 0, '#' is 1, 2-9 are digits, `+` is >9 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if f.alternate() { for s in &self.segments { let chr = if s.count == 0 { '-' } else if s.count == 1 { '#' } else if s.count <= 9 { ((s.count as u8) + b'0') as char } else { '+' }; for _ in 0..s.len { write!(f, "{}", chr)?; } } Ok(()) } else { f.debug_tuple("Subset").field(&self.segments).finish() } } } pub struct RangeIter<'a> { seg_iter: slice::Iter<'a, Segment>, pub consumed: usize, matcher: CountMatcher, } impl<'a> Iterator for RangeIter<'a> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { while let Some(seg) = self.seg_iter.next() { self.consumed += seg.len; if self.matcher.matches(seg) { return Some((self.consumed - seg.len, self.consumed)); } } None } } /// See `Subset::zip` pub struct ZipIter<'a> { a_segs: &'a [Segment], b_segs: &'a [Segment], a_i: usize, b_i: usize, a_consumed: usize, b_consumed: usize, pub consumed: usize, } /// See `Subset::zip` #[derive(Clone, Debug)] pub struct ZipSegment { len: usize, a_count: usize, b_count: usize, } impl<'a> Iterator for ZipIter<'a> { type Item = ZipSegment; /// Consume as far as possible from `self.consumed` until reaching a /// segment boundary in either `Subset`, and return the resulting /// `ZipSegment`. Will panic if it reaches the end of one `Subset` before /// the other, that is when they have different total length. fn next(&mut self) -> Option<ZipSegment> { match (self.a_segs.get(self.a_i), self.b_segs.get(self.b_i)) { (None, None) => None, (None, Some(_)) | (Some(_), None) => { panic!("can't zip Subsets of different base lengths.") } ( Some(&Segment { len: a_len, count: a_count }), Some(&Segment { len: b_len, count: b_count }), ) => { let len = match (a_len + self.a_consumed).cmp(&(b_len + self.b_consumed)) { cmp::Ordering::Equal => { self.a_consumed += a_len; self.a_i += 1; self.b_consumed += b_len; self.b_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Less => { self.a_consumed += a_len; self.a_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Greater => { self.b_consumed += b_len; self.b_i += 1; self.b_consumed - self.consumed } }; self.consumed += len; Some(ZipSegment { len, a_count, b_count }) } } } } pub struct Mapper<'a> { range_iter: RangeIter<'a>, // Not actually necessary for computation, just for dynamic checking of invariant last_i: usize, cur_range: (usize, usize), pub subset_amount_consumed: usize, } impl<'a> Mapper<'a> { /// Map a coordinate in the document this subset corresponds to, to a /// coordinate in the subset matched by the `CountMatcher`. For example, /// if the Subset is a set of deletions and the matcher is /// `CountMatcher::NonZero`, this would map indices in the union string to /// indices in the tombstones string. /// /// Will return the closest coordinate in the subset if the index is not /// in the subset. If the coordinate is past the end of the subset it will /// return one more than the largest index in the subset (i.e the length). /// This behaviour is suitable for mapping closed-open intervals in a /// string to intervals in a subset of the string. /// /// In order to guarantee good performance, this method must be called /// with `i` values in non-decreasing order or it will panic. This allows /// the total cost to be O(n) where `n = max(calls,ranges)` over all times /// called on a single `Mapper`. pub fn doc_index_to_subset(&mut self, i: usize) -> usize { assert!( i >= self.last_i, "method must be called with i in non-decreasing order. i={}<{}=last_i", i, self.last_i ); self.last_i = i; while i >= self.cur_range.1 { self.subset_amount_consumed += self.cur_range.1 - self.cur_range.0; self.cur_range = match self.range_iter.next() { Some(range) => range, // past the end of the subset None => { // ensure we don't try to consume any more self.cur_range = (usize::max_value(), usize::max_value()); return self.subset_amount_consumed; } } } if i >= self.cur_range.0 { let dist_in_range = i - self.cur_range.0; dist_in_range + self.subset_amount_consumed } else { // not in the subset self.subset_amount_consumed } } } #[cfg(test)] mod tests { use crate::multiset::*; use crate::test_helpers::find_deletions; const TEST_STR: &'static str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; #[test] fn test_apply() { let mut sb = SubsetBuilder::new(); for &(b, e) in &[ (0, 1), (2, 4), (6, 11), (13, 14), (15, 18), (19, 23), (24, 26), (31, 32), (33, 35), (36, 37), (40, 44), (45, 48), (49, 51), (52, 57), (58, 59), ] { sb.add_range(b, e, 1); } sb.pad_to_len(TEST_STR.len()); let s = sb.build(); println!("{:?}", s); assert_eq!("145BCEINQRSTUWZbcdimpvxyz", s.delete_from_string(TEST_STR)); } #[test] fn trivial() { let s = SubsetBuilder::new().build(); assert!(s.is_empty()); } #[test] fn test_find_deletions() { let substr = "015ABDFHJOPQVYdfgloprsuvz"; let s = find_deletions(substr, TEST_STR); assert_eq!(substr, s.delete_from_string(TEST_STR)); assert!(!s.is_empty()) } #[test] fn test_complement() { let substr = "0456789DEFGHIJKLMNOPQRSTUVWXYZdefghijklmnopqrstuvw"; let s = find_deletions(substr, TEST_STR); let c = s.complement(); // deleting the complement of the deletions we found should yield the deletions assert_eq!("123ABCabcxyz", c.delete_from_string(TEST_STR)); } #[test] fn test_mapper() { let substr = "469ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwz"; let s = find_deletions(substr, TEST_STR); let mut m = s.mapper(CountMatcher::NonZero); // subset is {0123 5 78 xy} assert_eq!(0, m.doc_index_to_subset(0)); assert_eq!(2, m.doc_index_to_subset(2)); assert_eq!(2, m.doc_index_to_subset(2)); assert_eq!(3, m.doc_index_to_subset(3)); assert_eq!(4, m.doc_index_to_subset(4)); // not in subset assert_eq!(4, m.doc_index_to_subset(5)); assert_eq!(5, m.doc_index_to_subset(7)); assert_eq!(6, m.doc_index_to_subset(8)); assert_eq!(6, m.doc_index_to_subset(8)); assert_eq!(8, m.doc_index_to_subset(60)); assert_eq!(9, m.doc_index_to_subset(61)); // not in subset assert_eq!(9, m.doc_index_to_subset(62)); // not in subset } #[test] #[should_panic(expected = "non-decreasing")] fn test_mapper_requires_non_decreasing() { let substr = "469ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw"; let s = find_deletions(substr, TEST_STR); let mut m = s.mapper(CountMatcher::NonZero); m.doc_index_to_subset(0); m.doc_index_to_subset(2); m.doc_index_to_subset(1); } #[test] fn union() { let s1 = find_deletions("024AEGHJKNQTUWXYZabcfgikqrvy", TEST_STR); let s2 = find_deletions("14589DEFGIKMOPQRUXZabcdefglnpsuxyz", TEST_STR); assert_eq!("4EGKQUXZabcfgy", s1.union(&s2).delete_from_string(TEST_STR)); } fn transform_case(str1: &str, str2: &str, result: &str) { let s1 = find_deletions(str1, TEST_STR); let s2 = find_deletions(str2, str1); let s3 = s2.transform_expand(&s1); let str3 = s3.delete_from_string(TEST_STR); assert_eq!(result, str3); assert_eq!(str2, s1.transform_shrink(&s3).delete_from_string(&str3)); assert_eq!(str2, s2.transform_union(&s1).delete_from_string(TEST_STR)); } #[test] fn
transform
identifier_name
multiset.rs
self.push_segment(total_len - cur_len, 0); } } /// Sets the count for a given range. This method must be called with a /// non-empty range with `begin` not before the largest range or segment added /// so far. Gaps will be filled with a 0-count segment. pub fn add_range(&mut self, begin: usize, end: usize, count: usize) { assert!(begin >= self.total_len, "ranges must be added in non-decreasing order"); // assert!(begin < end, "ranges added must be non-empty: [{},{})", begin, end); if begin >= end { return; } let len = end - begin; let cur_total_len = self.total_len; // add 0-count segment to fill any gap if begin > self.total_len { self.push_segment(begin - cur_total_len, 0); } self.push_segment(len, count); } /// Assign `count` to the next `len` elements in the string. /// Will panic if called with `len==0`. pub fn push_segment(&mut self, len: usize, count: usize) { assert!(len > 0, "can't push empty segment"); self.total_len += len; // merge into previous segment if possible if let Some(last) = self.segments.last_mut() { if last.count == count { last.len += len; return; } } self.segments.push(Segment { len, count }); } pub fn build(self) -> Subset { Subset { segments: self.segments } } } /// Determines which elements of a `Subset` a method applies to /// based on the count of the element. #[derive(Clone, Copy, Debug)] pub enum CountMatcher { Zero, NonZero, All, } impl CountMatcher { fn matches(self, seg: &Segment) -> bool { match self { CountMatcher::Zero => (seg.count == 0), CountMatcher::NonZero => (seg.count!= 0), CountMatcher::All => true, } } } impl Subset { /// Creates an empty `Subset` of a string of length `len` pub fn new(len: usize) -> Subset { let mut sb = SubsetBuilder::new(); sb.pad_to_len(len); sb.build() } /// Mostly for testing. pub fn delete_from_string(&self, s: &str) -> String { let mut result = String::new(); for (b, e) in self.range_iter(CountMatcher::Zero) { result.push_str(&s[b..e]); } result } // Maybe Subset should be a pure data structure and this method should // be a method of Node. /// Builds a version of `s` with all the elements in this `Subset` deleted from it. pub fn delete_from<N: NodeInfo>(&self, s: &Node<N>) -> Node<N> { let mut b = TreeBuilder::new(); for (beg, end) in self.range_iter(CountMatcher::Zero) { s.push_subseq(&mut b, Interval::new(beg, end)); } b.build() } /// The length of the resulting sequence after deleting this subset. A /// convenience alias for `self.count(CountMatcher::Zero)` to reduce /// thinking about what that means in the cases where the length after /// delete is what you want to know. /// /// `self.delete_from_string(s).len() = self.len(s.len())` pub fn len_after_delete(&self) -> usize
/// Count the total length of all the segments matching `matcher`. pub fn count(&self, matcher: CountMatcher) -> usize { self.segments.iter().filter(|seg| matcher.matches(seg)).map(|seg| seg.len).sum() } /// Convenience alias for `self.count(CountMatcher::All)` pub fn len(&self) -> usize { self.count(CountMatcher::All) } /// Determine whether the subset is empty. /// In this case deleting it would do nothing. pub fn is_empty(&self) -> bool { (self.segments.is_empty()) || ((self.segments.len() == 1) && (self.segments[0].count == 0)) } /// Compute the union of two subsets. The count of an element in the /// result is the sum of the counts in the inputs. pub fn union(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count + zseg.b_count); } sb.build() } /// Compute the difference of two subsets. The count of an element in the /// result is the subtraction of the counts of other from self. pub fn subtract(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { assert!( zseg.a_count >= zseg.b_count, "can't subtract {} from {}", zseg.a_count, zseg.b_count ); sb.push_segment(zseg.len, zseg.a_count - zseg.b_count); } sb.build() } /// Compute the bitwise xor of two subsets, useful as a reversible /// difference. The count of an element in the result is the bitwise xor /// of the counts of the inputs. Unchanged segments will be 0. /// /// This works like set symmetric difference when all counts are 0 or 1 /// but it extends nicely to the case of larger counts. pub fn bitxor(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count ^ zseg.b_count); } sb.build() } /// Map the contents of `self` into the 0-regions of `other`. /// Precondition: `self.count(CountMatcher::All) == other.count(CountMatcher::Zero)` fn transform(&self, other: &Subset, union: bool) -> Subset { let mut sb = SubsetBuilder::new(); let mut seg_iter = self.segments.iter(); let mut cur_seg = Segment { len: 0, count: 0 }; for oseg in &other.segments { if oseg.count > 0 { sb.push_segment(oseg.len, if union { oseg.count } else { 0 }); } else { // fill 0-region with segments from self. let mut to_be_consumed = oseg.len; while to_be_consumed > 0 { if cur_seg.len == 0 { cur_seg = seg_iter .next() .expect("self must cover all 0-regions of other") .clone(); } // consume as much of the segment as possible and necessary let to_consume = cmp::min(cur_seg.len, to_be_consumed); sb.push_segment(to_consume, cur_seg.count); to_be_consumed -= to_consume; cur_seg.len -= to_consume; } } } assert_eq!(cur_seg.len, 0, "the 0-regions of other must be the size of self"); assert_eq!(seg_iter.next(), None, "the 0-regions of other must be the size of self"); sb.build() } /// Transform through coordinate transform represented by other. /// The equation satisfied is as follows: /// /// s1 = other.delete_from_string(s0) /// /// s2 = self.delete_from_string(s1) /// /// element in self.transform_expand(other).delete_from_string(s0) if (not in s1) or in s2 pub fn transform_expand(&self, other: &Subset) -> Subset { self.transform(other, false) } /// The same as taking transform_expand and then unioning with `other`. pub fn transform_union(&self, other: &Subset) -> Subset { self.transform(other, true) } /// Transform subset through other coordinate transform, shrinking. /// The following equation is satisfied: /// /// C = A.transform_expand(B) /// /// B.transform_shrink(C).delete_from_string(C.delete_from_string(s)) = /// A.delete_from_string(B.delete_from_string(s)) pub fn transform_shrink(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); // discard ZipSegments where the shrinking set has positive count for zseg in self.zip(other) { // TODO: should this actually do something like subtract counts? if zseg.b_count == 0 { sb.push_segment(zseg.len, zseg.a_count); } } sb.build() } /// Return an iterator over the ranges with a count matching the `matcher`. /// These will often be easier to work with than raw segments. pub fn range_iter(&self, matcher: CountMatcher) -> RangeIter { RangeIter { seg_iter: self.segments.iter(), consumed: 0, matcher } } /// Convenience alias for `self.range_iter(CountMatcher::Zero)`. /// Semantically iterates the ranges of the complement of this `Subset`. pub fn complement_iter(&self) -> RangeIter { self.range_iter(CountMatcher::Zero) } /// Return an iterator over `ZipSegment`s where each `ZipSegment` contains /// the count for both self and other in that range. The two `Subset`s /// must have the same total length. /// /// Each returned `ZipSegment` will differ in at least one count. pub fn zip<'a>(&'a self, other: &'a Subset) -> ZipIter<'a> { ZipIter { a_segs: self.segments.as_slice(), b_segs: other.segments.as_slice(), a_i: 0, b_i: 0, a_consumed: 0, b_consumed: 0, consumed: 0, } } /// Find the complement of this Subset. Every 0-count element will have a /// count of 1 and every non-zero element will have a count of 0. pub fn complement(&self) -> Subset { let mut sb = SubsetBuilder::new(); for seg in &self.segments { if seg.count == 0 { sb.push_segment(seg.len, 1); } else { sb.push_segment(seg.len, 0); } } sb.build() } /// Return a `Mapper` that can be use to map coordinates in the document to coordinates /// in this `Subset`, but only in non-decreasing order for performance reasons. pub fn mapper(&self, matcher: CountMatcher) -> Mapper { Mapper { range_iter: self.range_iter(matcher), last_i: 0, // indices only need to be in non-decreasing order, not increasing cur_range: (0, 0), // will immediately try to consume next range subset_amount_consumed: 0, } } } impl fmt::Debug for Subset { /// Use the alternate flag (`#`) to print a more compact representation /// where each character represents the count of one element: /// '-' is 0, '#' is 1, 2-9 are digits, `+` is >9 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if f.alternate() { for s in &self.segments { let chr = if s.count == 0 { '-' } else if s.count == 1 { '#' } else if s.count <= 9 { ((s.count as u8) + b'0') as char } else { '+' }; for _ in 0..s.len { write!(f, "{}", chr)?; } } Ok(()) } else { f.debug_tuple("Subset").field(&self.segments).finish() } } } pub struct RangeIter<'a> { seg_iter: slice::Iter<'a, Segment>, pub consumed: usize, matcher: CountMatcher, } impl<'a> Iterator for RangeIter<'a> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { while let Some(seg) = self.seg_iter.next() { self.consumed += seg.len; if self.matcher.matches(seg) { return Some((self.consumed - seg.len, self.consumed)); } } None } } /// See `Subset::zip` pub struct ZipIter<'a> { a_segs: &'a [Segment], b_segs: &'a [Segment], a_i: usize, b_i: usize, a_consumed: usize, b_consumed: usize, pub consumed: usize, } /// See `Subset::zip` #[derive(Clone, Debug)] pub struct ZipSegment { len: usize, a_count: usize, b_count: usize, } impl<'a> Iterator for ZipIter<'a> { type Item = ZipSegment; /// Consume as far as possible from `self.consumed` until reaching a /// segment boundary in either `Subset`, and return the resulting /// `ZipSegment`. Will panic if it reaches the end of one `Subset` before /// the other, that is when they have different total length. fn next(&mut self) -> Option<ZipSegment> { match (self.a_segs.get(self.a_i), self.b_segs.get(self.b_i)) { (None, None) => None, (None, Some(_)) | (Some(_), None) => { panic!("can't zip Subsets of different base lengths.") } ( Some(&Segment { len: a_len, count: a_count }), Some(&Segment { len: b_len, count: b_count }), ) => { let len = match (a_len + self.a_consumed).cmp(&(b_len + self.b_consumed)) { cmp::Ordering::Equal => { self.a_consumed += a_len; self.a_i += 1; self.b_consumed += b_len; self.b_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Less => { self.a_consumed += a_len; self.a_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Greater => { self.b_consumed += b_len; self.b_i += 1; self.b_consumed - self.consumed } }; self.consumed += len; Some(ZipSegment { len, a_count, b_count }) } } } } pub struct Mapper<'a> { range_iter: RangeIter<'a>, // Not actually necessary for computation, just for dynamic checking of invariant last_i: usize, cur_range: (usize, usize), pub subset_amount_consumed: usize, } impl<'a> Mapper<'a> { /// Map a coordinate in the document this subset corresponds to, to a /// coordinate in the subset matched by the `CountMatcher`. For example, /// if the Subset is a set of deletions and the matcher is /// `CountMatcher::NonZero`, this would map indices in the union string to /// indices in the tombstones string. /// /// Will return the closest coordinate in the subset if the index is not /// in the subset. If the coordinate is past the end of the subset it will /// return one more than the largest index in the subset (i.e the length). /// This behaviour is suitable for mapping closed-open intervals in a /// string to intervals in a subset of the string. /// /// In order to guarantee good performance, this method must be called /// with `i` values in non-decreasing order or it will panic. This allows /// the total cost to be O(n) where `n = max(calls,ranges)` over all times /// called on a single `Mapper`. pub fn doc_index_to_subset(&mut self, i: usize) -> usize { assert!( i >= self.last_i, "method must be called with i in non-decreasing order. i={}<{}=last_i", i, self.last_i ); self.last_i = i; while i >= self.cur_range.1 { self.subset_amount_consumed += self.cur_range.1 - self.cur_range.0; self.cur_range = match self.range_iter.next() { Some(range) => range, // past the end of the subset None => { // ensure we don't try to consume any more self.cur_range = (usize::max_value(), usize::max_value()); return self.subset_amount_consumed; } } } if i >= self.cur_range.0 { let dist_in_range = i - self.cur_range.0; dist_in_range + self.subset_amount_consumed } else { // not in the subset self.subset_amount_consumed } } } #[cfg(test)] mod tests { use crate::multiset::*; use crate::test_helpers::find_deletions; const TEST_STR: &'static str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; #[test] fn test_apply() { let mut sb = SubsetBuilder::new(); for &(b, e) in &[ (0, 1), (2, 4), (6, 11), (13, 14), (15, 18), (19, 23), (24, 26), (31, 32), (33, 35), (36, 37), (40, 44), (45, 48), (49, 51), (52, 57), (58, 59), ] { sb.add_range(b, e, 1); } sb.pad_to_len(TEST_STR.len()); let s = sb.build(); println!("{:?}", s); assert_eq!("145BCEINQRSTUWZbcdimpvxyz", s.delete_from_string(TEST_STR)); } #[test] fn trivial() { let s = SubsetBuilder::new().build(); assert!(s.is_empty()); } #[test] fn test_find_deletions() { let substr = "015ABDFHJOPQVYdfgloprsuvz"; let s = find_deletions(substr, TEST_STR); assert_eq!(substr, s.delete_from_string(TEST_STR)); assert!(!s.is_empty()) } #[test] fn test_complement() { let substr = "0456789DEFGHIJKLMNOPQRSTUVWXYZdefghijklmnopqrstuvw"; let s = find_deletions(substr, TEST_STR); let c = s.complement(); // deleting the complement of the deletions we found should yield the deletions assert_eq!("123ABCabcxyz", c.delete_from_string(TEST_STR)); } #[test] fn test_mapper() { let substr = "469ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwz"; let s = find_deletions(substr, TEST_STR); let mut m = s.mapper(CountMatcher::NonZero); // subset is {0123 5 78 xy} assert_eq!(0, m
{ self.count(CountMatcher::Zero) }
identifier_body
multiset.rs
self.push_segment(total_len - cur_len, 0); } } /// Sets the count for a given range. This method must be called with a /// non-empty range with `begin` not before the largest range or segment added /// so far. Gaps will be filled with a 0-count segment. pub fn add_range(&mut self, begin: usize, end: usize, count: usize) { assert!(begin >= self.total_len, "ranges must be added in non-decreasing order"); // assert!(begin < end, "ranges added must be non-empty: [{},{})", begin, end); if begin >= end { return; } let len = end - begin; let cur_total_len = self.total_len; // add 0-count segment to fill any gap if begin > self.total_len { self.push_segment(begin - cur_total_len, 0); } self.push_segment(len, count); } /// Assign `count` to the next `len` elements in the string. /// Will panic if called with `len==0`. pub fn push_segment(&mut self, len: usize, count: usize) { assert!(len > 0, "can't push empty segment"); self.total_len += len; // merge into previous segment if possible if let Some(last) = self.segments.last_mut() { if last.count == count { last.len += len; return; } } self.segments.push(Segment { len, count }); } pub fn build(self) -> Subset { Subset { segments: self.segments } } } /// Determines which elements of a `Subset` a method applies to /// based on the count of the element. #[derive(Clone, Copy, Debug)] pub enum CountMatcher { Zero, NonZero, All, } impl CountMatcher { fn matches(self, seg: &Segment) -> bool { match self { CountMatcher::Zero => (seg.count == 0), CountMatcher::NonZero => (seg.count!= 0), CountMatcher::All => true, } } } impl Subset { /// Creates an empty `Subset` of a string of length `len` pub fn new(len: usize) -> Subset { let mut sb = SubsetBuilder::new(); sb.pad_to_len(len); sb.build() } /// Mostly for testing. pub fn delete_from_string(&self, s: &str) -> String { let mut result = String::new(); for (b, e) in self.range_iter(CountMatcher::Zero) { result.push_str(&s[b..e]); } result } // Maybe Subset should be a pure data structure and this method should // be a method of Node. /// Builds a version of `s` with all the elements in this `Subset` deleted from it. pub fn delete_from<N: NodeInfo>(&self, s: &Node<N>) -> Node<N> { let mut b = TreeBuilder::new(); for (beg, end) in self.range_iter(CountMatcher::Zero) { s.push_subseq(&mut b, Interval::new(beg, end)); } b.build() } /// The length of the resulting sequence after deleting this subset. A /// convenience alias for `self.count(CountMatcher::Zero)` to reduce /// thinking about what that means in the cases where the length after /// delete is what you want to know. /// /// `self.delete_from_string(s).len() = self.len(s.len())` pub fn len_after_delete(&self) -> usize { self.count(CountMatcher::Zero) } /// Count the total length of all the segments matching `matcher`. pub fn count(&self, matcher: CountMatcher) -> usize { self.segments.iter().filter(|seg| matcher.matches(seg)).map(|seg| seg.len).sum() } /// Convenience alias for `self.count(CountMatcher::All)` pub fn len(&self) -> usize { self.count(CountMatcher::All) } /// Determine whether the subset is empty. /// In this case deleting it would do nothing. pub fn is_empty(&self) -> bool { (self.segments.is_empty()) || ((self.segments.len() == 1) && (self.segments[0].count == 0)) } /// Compute the union of two subsets. The count of an element in the /// result is the sum of the counts in the inputs. pub fn union(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count + zseg.b_count); } sb.build() } /// Compute the difference of two subsets. The count of an element in the /// result is the subtraction of the counts of other from self. pub fn subtract(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { assert!( zseg.a_count >= zseg.b_count, "can't subtract {} from {}", zseg.a_count, zseg.b_count ); sb.push_segment(zseg.len, zseg.a_count - zseg.b_count); } sb.build() } /// Compute the bitwise xor of two subsets, useful as a reversible /// difference. The count of an element in the result is the bitwise xor /// of the counts of the inputs. Unchanged segments will be 0. /// /// This works like set symmetric difference when all counts are 0 or 1 /// but it extends nicely to the case of larger counts. pub fn bitxor(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count ^ zseg.b_count); } sb.build() } /// Map the contents of `self` into the 0-regions of `other`. /// Precondition: `self.count(CountMatcher::All) == other.count(CountMatcher::Zero)` fn transform(&self, other: &Subset, union: bool) -> Subset { let mut sb = SubsetBuilder::new(); let mut seg_iter = self.segments.iter(); let mut cur_seg = Segment { len: 0, count: 0 }; for oseg in &other.segments { if oseg.count > 0 { sb.push_segment(oseg.len, if union { oseg.count } else { 0 }); } else { // fill 0-region with segments from self. let mut to_be_consumed = oseg.len; while to_be_consumed > 0 { if cur_seg.len == 0
// consume as much of the segment as possible and necessary let to_consume = cmp::min(cur_seg.len, to_be_consumed); sb.push_segment(to_consume, cur_seg.count); to_be_consumed -= to_consume; cur_seg.len -= to_consume; } } } assert_eq!(cur_seg.len, 0, "the 0-regions of other must be the size of self"); assert_eq!(seg_iter.next(), None, "the 0-regions of other must be the size of self"); sb.build() } /// Transform through coordinate transform represented by other. /// The equation satisfied is as follows: /// /// s1 = other.delete_from_string(s0) /// /// s2 = self.delete_from_string(s1) /// /// element in self.transform_expand(other).delete_from_string(s0) if (not in s1) or in s2 pub fn transform_expand(&self, other: &Subset) -> Subset { self.transform(other, false) } /// The same as taking transform_expand and then unioning with `other`. pub fn transform_union(&self, other: &Subset) -> Subset { self.transform(other, true) } /// Transform subset through other coordinate transform, shrinking. /// The following equation is satisfied: /// /// C = A.transform_expand(B) /// /// B.transform_shrink(C).delete_from_string(C.delete_from_string(s)) = /// A.delete_from_string(B.delete_from_string(s)) pub fn transform_shrink(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); // discard ZipSegments where the shrinking set has positive count for zseg in self.zip(other) { // TODO: should this actually do something like subtract counts? if zseg.b_count == 0 { sb.push_segment(zseg.len, zseg.a_count); } } sb.build() } /// Return an iterator over the ranges with a count matching the `matcher`. /// These will often be easier to work with than raw segments. pub fn range_iter(&self, matcher: CountMatcher) -> RangeIter { RangeIter { seg_iter: self.segments.iter(), consumed: 0, matcher } } /// Convenience alias for `self.range_iter(CountMatcher::Zero)`. /// Semantically iterates the ranges of the complement of this `Subset`. pub fn complement_iter(&self) -> RangeIter { self.range_iter(CountMatcher::Zero) } /// Return an iterator over `ZipSegment`s where each `ZipSegment` contains /// the count for both self and other in that range. The two `Subset`s /// must have the same total length. /// /// Each returned `ZipSegment` will differ in at least one count. pub fn zip<'a>(&'a self, other: &'a Subset) -> ZipIter<'a> { ZipIter { a_segs: self.segments.as_slice(), b_segs: other.segments.as_slice(), a_i: 0, b_i: 0, a_consumed: 0, b_consumed: 0, consumed: 0, } } /// Find the complement of this Subset. Every 0-count element will have a /// count of 1 and every non-zero element will have a count of 0. pub fn complement(&self) -> Subset { let mut sb = SubsetBuilder::new(); for seg in &self.segments { if seg.count == 0 { sb.push_segment(seg.len, 1); } else { sb.push_segment(seg.len, 0); } } sb.build() } /// Return a `Mapper` that can be use to map coordinates in the document to coordinates /// in this `Subset`, but only in non-decreasing order for performance reasons. pub fn mapper(&self, matcher: CountMatcher) -> Mapper { Mapper { range_iter: self.range_iter(matcher), last_i: 0, // indices only need to be in non-decreasing order, not increasing cur_range: (0, 0), // will immediately try to consume next range subset_amount_consumed: 0, } } } impl fmt::Debug for Subset { /// Use the alternate flag (`#`) to print a more compact representation /// where each character represents the count of one element: /// '-' is 0, '#' is 1, 2-9 are digits, `+` is >9 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if f.alternate() { for s in &self.segments { let chr = if s.count == 0 { '-' } else if s.count == 1 { '#' } else if s.count <= 9 { ((s.count as u8) + b'0') as char } else { '+' }; for _ in 0..s.len { write!(f, "{}", chr)?; } } Ok(()) } else { f.debug_tuple("Subset").field(&self.segments).finish() } } } pub struct RangeIter<'a> { seg_iter: slice::Iter<'a, Segment>, pub consumed: usize, matcher: CountMatcher, } impl<'a> Iterator for RangeIter<'a> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { while let Some(seg) = self.seg_iter.next() { self.consumed += seg.len; if self.matcher.matches(seg) { return Some((self.consumed - seg.len, self.consumed)); } } None } } /// See `Subset::zip` pub struct ZipIter<'a> { a_segs: &'a [Segment], b_segs: &'a [Segment], a_i: usize, b_i: usize, a_consumed: usize, b_consumed: usize, pub consumed: usize, } /// See `Subset::zip` #[derive(Clone, Debug)] pub struct ZipSegment { len: usize, a_count: usize, b_count: usize, } impl<'a> Iterator for ZipIter<'a> { type Item = ZipSegment; /// Consume as far as possible from `self.consumed` until reaching a /// segment boundary in either `Subset`, and return the resulting /// `ZipSegment`. Will panic if it reaches the end of one `Subset` before /// the other, that is when they have different total length. fn next(&mut self) -> Option<ZipSegment> { match (self.a_segs.get(self.a_i), self.b_segs.get(self.b_i)) { (None, None) => None, (None, Some(_)) | (Some(_), None) => { panic!("can't zip Subsets of different base lengths.") } ( Some(&Segment { len: a_len, count: a_count }), Some(&Segment { len: b_len, count: b_count }), ) => { let len = match (a_len + self.a_consumed).cmp(&(b_len + self.b_consumed)) { cmp::Ordering::Equal => { self.a_consumed += a_len; self.a_i += 1; self.b_consumed += b_len; self.b_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Less => { self.a_consumed += a_len; self.a_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Greater => { self.b_consumed += b_len; self.b_i += 1; self.b_consumed - self.consumed } }; self.consumed += len; Some(ZipSegment { len, a_count, b_count }) } } } } pub struct Mapper<'a> { range_iter: RangeIter<'a>, // Not actually necessary for computation, just for dynamic checking of invariant last_i: usize, cur_range: (usize, usize), pub subset_amount_consumed: usize, } impl<'a> Mapper<'a> { /// Map a coordinate in the document this subset corresponds to, to a /// coordinate in the subset matched by the `CountMatcher`. For example, /// if the Subset is a set of deletions and the matcher is /// `CountMatcher::NonZero`, this would map indices in the union string to /// indices in the tombstones string. /// /// Will return the closest coordinate in the subset if the index is not /// in the subset. If the coordinate is past the end of the subset it will /// return one more than the largest index in the subset (i.e the length). /// This behaviour is suitable for mapping closed-open intervals in a /// string to intervals in a subset of the string. /// /// In order to guarantee good performance, this method must be called /// with `i` values in non-decreasing order or it will panic. This allows /// the total cost to be O(n) where `n = max(calls,ranges)` over all times /// called on a single `Mapper`. pub fn doc_index_to_subset(&mut self, i: usize) -> usize { assert!( i >= self.last_i, "method must be called with i in non-decreasing order. i={}<{}=last_i", i, self.last_i ); self.last_i = i; while i >= self.cur_range.1 { self.subset_amount_consumed += self.cur_range.1 - self.cur_range.0; self.cur_range = match self.range_iter.next() { Some(range) => range, // past the end of the subset None => { // ensure we don't try to consume any more self.cur_range = (usize::max_value(), usize::max_value()); return self.subset_amount_consumed; } } } if i >= self.cur_range.0 { let dist_in_range = i - self.cur_range.0; dist_in_range + self.subset_amount_consumed } else { // not in the subset self.subset_amount_consumed } } } #[cfg(test)] mod tests { use crate::multiset::*; use crate::test_helpers::find_deletions; const TEST_STR: &'static str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; #[test] fn test_apply() { let mut sb = SubsetBuilder::new(); for &(b, e) in &[ (0, 1), (2, 4), (6, 11), (13, 14), (15, 18), (19, 23), (24, 26), (31, 32), (33, 35), (36, 37), (40, 44), (45, 48), (49, 51), (52, 57), (58, 59), ] { sb.add_range(b, e, 1); } sb.pad_to_len(TEST_STR.len()); let s = sb.build(); println!("{:?}", s); assert_eq!("145BCEINQRSTUWZbcdimpvxyz", s.delete_from_string(TEST_STR)); } #[test] fn trivial() { let s = SubsetBuilder::new().build(); assert!(s.is_empty()); } #[test] fn test_find_deletions() { let substr = "015ABDFHJOPQVYdfgloprsuvz"; let s = find_deletions(substr, TEST_STR); assert_eq!(substr, s.delete_from_string(TEST_STR)); assert!(!s.is_empty()) } #[test] fn test_complement() { let substr = "0456789DEFGHIJKLMNOPQRSTUVWXYZdefghijklmnopqrstuvw"; let s = find_deletions(substr, TEST_STR); let c = s.complement(); // deleting the complement of the deletions we found should yield the deletions assert_eq!("123ABCabcxyz", c.delete_from_string(TEST_STR)); } #[test] fn test_mapper() { let substr = "469ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwz"; let s = find_deletions(substr, TEST_STR); let mut m = s.mapper(CountMatcher::NonZero); // subset is {0123 5 78 xy} assert_eq!(0, m
{ cur_seg = seg_iter .next() .expect("self must cover all 0-regions of other") .clone(); }
conditional_block
multiset.rs
self.push_segment(total_len - cur_len, 0); } } /// Sets the count for a given range. This method must be called with a /// non-empty range with `begin` not before the largest range or segment added /// so far. Gaps will be filled with a 0-count segment. pub fn add_range(&mut self, begin: usize, end: usize, count: usize) { assert!(begin >= self.total_len, "ranges must be added in non-decreasing order"); // assert!(begin < end, "ranges added must be non-empty: [{},{})", begin, end); if begin >= end { return; } let len = end - begin; let cur_total_len = self.total_len; // add 0-count segment to fill any gap if begin > self.total_len { self.push_segment(begin - cur_total_len, 0); } self.push_segment(len, count); } /// Assign `count` to the next `len` elements in the string. /// Will panic if called with `len==0`. pub fn push_segment(&mut self, len: usize, count: usize) { assert!(len > 0, "can't push empty segment"); self.total_len += len; // merge into previous segment if possible if let Some(last) = self.segments.last_mut() { if last.count == count { last.len += len; return; } }
self.segments.push(Segment { len, count }); } pub fn build(self) -> Subset { Subset { segments: self.segments } } } /// Determines which elements of a `Subset` a method applies to /// based on the count of the element. #[derive(Clone, Copy, Debug)] pub enum CountMatcher { Zero, NonZero, All, } impl CountMatcher { fn matches(self, seg: &Segment) -> bool { match self { CountMatcher::Zero => (seg.count == 0), CountMatcher::NonZero => (seg.count!= 0), CountMatcher::All => true, } } } impl Subset { /// Creates an empty `Subset` of a string of length `len` pub fn new(len: usize) -> Subset { let mut sb = SubsetBuilder::new(); sb.pad_to_len(len); sb.build() } /// Mostly for testing. pub fn delete_from_string(&self, s: &str) -> String { let mut result = String::new(); for (b, e) in self.range_iter(CountMatcher::Zero) { result.push_str(&s[b..e]); } result } // Maybe Subset should be a pure data structure and this method should // be a method of Node. /// Builds a version of `s` with all the elements in this `Subset` deleted from it. pub fn delete_from<N: NodeInfo>(&self, s: &Node<N>) -> Node<N> { let mut b = TreeBuilder::new(); for (beg, end) in self.range_iter(CountMatcher::Zero) { s.push_subseq(&mut b, Interval::new(beg, end)); } b.build() } /// The length of the resulting sequence after deleting this subset. A /// convenience alias for `self.count(CountMatcher::Zero)` to reduce /// thinking about what that means in the cases where the length after /// delete is what you want to know. /// /// `self.delete_from_string(s).len() = self.len(s.len())` pub fn len_after_delete(&self) -> usize { self.count(CountMatcher::Zero) } /// Count the total length of all the segments matching `matcher`. pub fn count(&self, matcher: CountMatcher) -> usize { self.segments.iter().filter(|seg| matcher.matches(seg)).map(|seg| seg.len).sum() } /// Convenience alias for `self.count(CountMatcher::All)` pub fn len(&self) -> usize { self.count(CountMatcher::All) } /// Determine whether the subset is empty. /// In this case deleting it would do nothing. pub fn is_empty(&self) -> bool { (self.segments.is_empty()) || ((self.segments.len() == 1) && (self.segments[0].count == 0)) } /// Compute the union of two subsets. The count of an element in the /// result is the sum of the counts in the inputs. pub fn union(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count + zseg.b_count); } sb.build() } /// Compute the difference of two subsets. The count of an element in the /// result is the subtraction of the counts of other from self. pub fn subtract(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { assert!( zseg.a_count >= zseg.b_count, "can't subtract {} from {}", zseg.a_count, zseg.b_count ); sb.push_segment(zseg.len, zseg.a_count - zseg.b_count); } sb.build() } /// Compute the bitwise xor of two subsets, useful as a reversible /// difference. The count of an element in the result is the bitwise xor /// of the counts of the inputs. Unchanged segments will be 0. /// /// This works like set symmetric difference when all counts are 0 or 1 /// but it extends nicely to the case of larger counts. pub fn bitxor(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count ^ zseg.b_count); } sb.build() } /// Map the contents of `self` into the 0-regions of `other`. /// Precondition: `self.count(CountMatcher::All) == other.count(CountMatcher::Zero)` fn transform(&self, other: &Subset, union: bool) -> Subset { let mut sb = SubsetBuilder::new(); let mut seg_iter = self.segments.iter(); let mut cur_seg = Segment { len: 0, count: 0 }; for oseg in &other.segments { if oseg.count > 0 { sb.push_segment(oseg.len, if union { oseg.count } else { 0 }); } else { // fill 0-region with segments from self. let mut to_be_consumed = oseg.len; while to_be_consumed > 0 { if cur_seg.len == 0 { cur_seg = seg_iter .next() .expect("self must cover all 0-regions of other") .clone(); } // consume as much of the segment as possible and necessary let to_consume = cmp::min(cur_seg.len, to_be_consumed); sb.push_segment(to_consume, cur_seg.count); to_be_consumed -= to_consume; cur_seg.len -= to_consume; } } } assert_eq!(cur_seg.len, 0, "the 0-regions of other must be the size of self"); assert_eq!(seg_iter.next(), None, "the 0-regions of other must be the size of self"); sb.build() } /// Transform through coordinate transform represented by other. /// The equation satisfied is as follows: /// /// s1 = other.delete_from_string(s0) /// /// s2 = self.delete_from_string(s1) /// /// element in self.transform_expand(other).delete_from_string(s0) if (not in s1) or in s2 pub fn transform_expand(&self, other: &Subset) -> Subset { self.transform(other, false) } /// The same as taking transform_expand and then unioning with `other`. pub fn transform_union(&self, other: &Subset) -> Subset { self.transform(other, true) } /// Transform subset through other coordinate transform, shrinking. /// The following equation is satisfied: /// /// C = A.transform_expand(B) /// /// B.transform_shrink(C).delete_from_string(C.delete_from_string(s)) = /// A.delete_from_string(B.delete_from_string(s)) pub fn transform_shrink(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); // discard ZipSegments where the shrinking set has positive count for zseg in self.zip(other) { // TODO: should this actually do something like subtract counts? if zseg.b_count == 0 { sb.push_segment(zseg.len, zseg.a_count); } } sb.build() } /// Return an iterator over the ranges with a count matching the `matcher`. /// These will often be easier to work with than raw segments. pub fn range_iter(&self, matcher: CountMatcher) -> RangeIter { RangeIter { seg_iter: self.segments.iter(), consumed: 0, matcher } } /// Convenience alias for `self.range_iter(CountMatcher::Zero)`. /// Semantically iterates the ranges of the complement of this `Subset`. pub fn complement_iter(&self) -> RangeIter { self.range_iter(CountMatcher::Zero) } /// Return an iterator over `ZipSegment`s where each `ZipSegment` contains /// the count for both self and other in that range. The two `Subset`s /// must have the same total length. /// /// Each returned `ZipSegment` will differ in at least one count. pub fn zip<'a>(&'a self, other: &'a Subset) -> ZipIter<'a> { ZipIter { a_segs: self.segments.as_slice(), b_segs: other.segments.as_slice(), a_i: 0, b_i: 0, a_consumed: 0, b_consumed: 0, consumed: 0, } } /// Find the complement of this Subset. Every 0-count element will have a /// count of 1 and every non-zero element will have a count of 0. pub fn complement(&self) -> Subset { let mut sb = SubsetBuilder::new(); for seg in &self.segments { if seg.count == 0 { sb.push_segment(seg.len, 1); } else { sb.push_segment(seg.len, 0); } } sb.build() } /// Return a `Mapper` that can be use to map coordinates in the document to coordinates /// in this `Subset`, but only in non-decreasing order for performance reasons. pub fn mapper(&self, matcher: CountMatcher) -> Mapper { Mapper { range_iter: self.range_iter(matcher), last_i: 0, // indices only need to be in non-decreasing order, not increasing cur_range: (0, 0), // will immediately try to consume next range subset_amount_consumed: 0, } } } impl fmt::Debug for Subset { /// Use the alternate flag (`#`) to print a more compact representation /// where each character represents the count of one element: /// '-' is 0, '#' is 1, 2-9 are digits, `+` is >9 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if f.alternate() { for s in &self.segments { let chr = if s.count == 0 { '-' } else if s.count == 1 { '#' } else if s.count <= 9 { ((s.count as u8) + b'0') as char } else { '+' }; for _ in 0..s.len { write!(f, "{}", chr)?; } } Ok(()) } else { f.debug_tuple("Subset").field(&self.segments).finish() } } } pub struct RangeIter<'a> { seg_iter: slice::Iter<'a, Segment>, pub consumed: usize, matcher: CountMatcher, } impl<'a> Iterator for RangeIter<'a> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { while let Some(seg) = self.seg_iter.next() { self.consumed += seg.len; if self.matcher.matches(seg) { return Some((self.consumed - seg.len, self.consumed)); } } None } } /// See `Subset::zip` pub struct ZipIter<'a> { a_segs: &'a [Segment], b_segs: &'a [Segment], a_i: usize, b_i: usize, a_consumed: usize, b_consumed: usize, pub consumed: usize, } /// See `Subset::zip` #[derive(Clone, Debug)] pub struct ZipSegment { len: usize, a_count: usize, b_count: usize, } impl<'a> Iterator for ZipIter<'a> { type Item = ZipSegment; /// Consume as far as possible from `self.consumed` until reaching a /// segment boundary in either `Subset`, and return the resulting /// `ZipSegment`. Will panic if it reaches the end of one `Subset` before /// the other, that is when they have different total length. fn next(&mut self) -> Option<ZipSegment> { match (self.a_segs.get(self.a_i), self.b_segs.get(self.b_i)) { (None, None) => None, (None, Some(_)) | (Some(_), None) => { panic!("can't zip Subsets of different base lengths.") } ( Some(&Segment { len: a_len, count: a_count }), Some(&Segment { len: b_len, count: b_count }), ) => { let len = match (a_len + self.a_consumed).cmp(&(b_len + self.b_consumed)) { cmp::Ordering::Equal => { self.a_consumed += a_len; self.a_i += 1; self.b_consumed += b_len; self.b_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Less => { self.a_consumed += a_len; self.a_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Greater => { self.b_consumed += b_len; self.b_i += 1; self.b_consumed - self.consumed } }; self.consumed += len; Some(ZipSegment { len, a_count, b_count }) } } } } pub struct Mapper<'a> { range_iter: RangeIter<'a>, // Not actually necessary for computation, just for dynamic checking of invariant last_i: usize, cur_range: (usize, usize), pub subset_amount_consumed: usize, } impl<'a> Mapper<'a> { /// Map a coordinate in the document this subset corresponds to, to a /// coordinate in the subset matched by the `CountMatcher`. For example, /// if the Subset is a set of deletions and the matcher is /// `CountMatcher::NonZero`, this would map indices in the union string to /// indices in the tombstones string. /// /// Will return the closest coordinate in the subset if the index is not /// in the subset. If the coordinate is past the end of the subset it will /// return one more than the largest index in the subset (i.e the length). /// This behaviour is suitable for mapping closed-open intervals in a /// string to intervals in a subset of the string. /// /// In order to guarantee good performance, this method must be called /// with `i` values in non-decreasing order or it will panic. This allows /// the total cost to be O(n) where `n = max(calls,ranges)` over all times /// called on a single `Mapper`. pub fn doc_index_to_subset(&mut self, i: usize) -> usize { assert!( i >= self.last_i, "method must be called with i in non-decreasing order. i={}<{}=last_i", i, self.last_i ); self.last_i = i; while i >= self.cur_range.1 { self.subset_amount_consumed += self.cur_range.1 - self.cur_range.0; self.cur_range = match self.range_iter.next() { Some(range) => range, // past the end of the subset None => { // ensure we don't try to consume any more self.cur_range = (usize::max_value(), usize::max_value()); return self.subset_amount_consumed; } } } if i >= self.cur_range.0 { let dist_in_range = i - self.cur_range.0; dist_in_range + self.subset_amount_consumed } else { // not in the subset self.subset_amount_consumed } } } #[cfg(test)] mod tests { use crate::multiset::*; use crate::test_helpers::find_deletions; const TEST_STR: &'static str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; #[test] fn test_apply() { let mut sb = SubsetBuilder::new(); for &(b, e) in &[ (0, 1), (2, 4), (6, 11), (13, 14), (15, 18), (19, 23), (24, 26), (31, 32), (33, 35), (36, 37), (40, 44), (45, 48), (49, 51), (52, 57), (58, 59), ] { sb.add_range(b, e, 1); } sb.pad_to_len(TEST_STR.len()); let s = sb.build(); println!("{:?}", s); assert_eq!("145BCEINQRSTUWZbcdimpvxyz", s.delete_from_string(TEST_STR)); } #[test] fn trivial() { let s = SubsetBuilder::new().build(); assert!(s.is_empty()); } #[test] fn test_find_deletions() { let substr = "015ABDFHJOPQVYdfgloprsuvz"; let s = find_deletions(substr, TEST_STR); assert_eq!(substr, s.delete_from_string(TEST_STR)); assert!(!s.is_empty()) } #[test] fn test_complement() { let substr = "0456789DEFGHIJKLMNOPQRSTUVWXYZdefghijklmnopqrstuvw"; let s = find_deletions(substr, TEST_STR); let c = s.complement(); // deleting the complement of the deletions we found should yield the deletions assert_eq!("123ABCabcxyz", c.delete_from_string(TEST_STR)); } #[test] fn test_mapper() { let substr = "469ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwz"; let s = find_deletions(substr, TEST_STR); let mut m = s.mapper(CountMatcher::NonZero); // subset is {0123 5 78 xy} assert_eq!(0, m.doc
random_line_split
test_map_reduce.rs
use std::thread; fn main ()
result })); } //Reduce let mut intermediate_sums = vec![]; for child in children { let intermediate_sum = child.join().unwrap(); intermediate_sums.push(intermediate_sum); } let final_result = intermediate_sums.iter().sum::<u32>(); println!("Final sum result: {}", final_result); }
{ let data = "86967897737416471853297327050364959 11861322575564723963297542624962850 70856234701860851907960690014725639 38397966707106094172783238747669219 52380795257888236525459303330302837 58495327135744041048897885734297812 69920216438980873548808413720956532 16278424637452589860345374828574668"; let mut children = vec![]; let chunked_data = data.split_whitespace(); //Map for (i, data_segment) in chunked_data.enumerate() { println!("data segment {} is \"{}\"", i, data_segment); children.push(thread::spawn( move || -> u32 { let result = data.chars().map(|c| c.to_digit(10).expect("should be a digit")).sum(); println!("processed segement {}, result={}",i, result);
identifier_body
test_map_reduce.rs
use std::thread; fn
() { let data = "86967897737416471853297327050364959 11861322575564723963297542624962850 70856234701860851907960690014725639 38397966707106094172783238747669219 52380795257888236525459303330302837 58495327135744041048897885734297812 69920216438980873548808413720956532 16278424637452589860345374828574668"; let mut children = vec![]; let chunked_data = data.split_whitespace(); //Map for (i, data_segment) in chunked_data.enumerate() { println!("data segment {} is \"{}\"", i, data_segment); children.push(thread::spawn( move || -> u32 { let result = data.chars().map(|c| c.to_digit(10).expect("should be a digit")).sum(); println!("processed segement {}, result={}",i, result); result })); } //Reduce let mut intermediate_sums = vec![]; for child in children { let intermediate_sum = child.join().unwrap(); intermediate_sums.push(intermediate_sum); } let final_result = intermediate_sums.iter().sum::<u32>(); println!("Final sum result: {}", final_result); }
main
identifier_name
test_map_reduce.rs
use std::thread; fn main () { let data = "86967897737416471853297327050364959 11861322575564723963297542624962850 70856234701860851907960690014725639 38397966707106094172783238747669219 52380795257888236525459303330302837 58495327135744041048897885734297812 69920216438980873548808413720956532 16278424637452589860345374828574668"; let mut children = vec![]; let chunked_data = data.split_whitespace(); //Map for (i, data_segment) in chunked_data.enumerate() { println!("data segment {} is \"{}\"", i, data_segment); children.push(thread::spawn( move || -> u32 { let result = data.chars().map(|c| c.to_digit(10).expect("should be a digit")).sum(); println!("processed segement {}, result={}",i, result); result })); }
intermediate_sums.push(intermediate_sum); } let final_result = intermediate_sums.iter().sum::<u32>(); println!("Final sum result: {}", final_result); }
//Reduce let mut intermediate_sums = vec![]; for child in children { let intermediate_sum = child.join().unwrap();
random_line_split
callee.rs
ref_expr.id)) } ast::def_variant(tid, vid) => { // nullary variants are not callable assert!(ty::enum_variant_with_id(bcx.tcx(), tid, vid).args.len() > 0u); fn_callee(bcx, trans_fn_ref(bcx, vid, ref_expr.id)) } ast::def_struct(def_id) => { fn_callee(bcx, trans_fn_ref(bcx, def_id, ref_expr.id)) } ast::def_arg(*) | ast::def_local(*) | ast::def_binding(*) | ast::def_upvar(*) | ast::def_self(*) => { datum_callee(bcx, ref_expr) } ast::def_mod(*) | ast::def_foreign_mod(*) | ast::def_const(*) | ast::def_ty(*) | ast::def_prim_ty(*) | ast::def_use(*) | ast::def_typaram_binder(*) | ast::def_region(*) | ast::def_label(*) | ast::def_ty_param(*) | ast::def_self_ty(*) => { bcx.tcx().sess.span_bug( ref_expr.span, fmt!("Cannot translate def %? \ to a callable thing!", def)); } } } } pub fn trans_fn_ref_to_callee(bcx: block, def_id: ast::def_id, ref_id: ast::node_id) -> Callee { Callee {bcx: bcx, data: Fn(trans_fn_ref(bcx, def_id, ref_id))} } pub fn trans_fn_ref(bcx: block, def_id: ast::def_id, ref_id: ast::node_id) -> FnData { /*! * * Translates a reference (with id `ref_id`) to the fn/method * with id `def_id` into a function pointer. This may require * monomorphization or inlining. */ let _icx = bcx.insn_ctxt("trans_fn"); let type_params = node_id_type_params(bcx, ref_id); let vtables = node_vtables(bcx, ref_id); trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables) } pub fn trans_fn_ref_with_vtables_to_callee( bcx: block, def_id: ast::def_id, ref_id: ast::node_id, type_params: &[ty::t], vtables: Option<typeck::vtable_res>) -> Callee { Callee {bcx: bcx, data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables))} } pub fn trans_fn_ref_with_vtables( bcx: block, // def_id: ast::def_id, // def id of fn ref_id: ast::node_id, // node id of use of fn; may be zero if N/A type_params: &[ty::t], // values for fn's ty params vtables: Option<typeck::vtable_res>) -> FnData { //! // // Translates a reference to a fn/method item, monomorphizing and // inlining as it goes. // // # Parameters // // - `bcx`: the current block where the reference to the fn occurs // - `def_id`: def id of the fn or method item being referenced // - `ref_id`: node id of the reference to the fn/method, if applicable. // This parameter may be zero; but, if so, the resulting value may not // have the right type, so it must be cast before being used. // - `type_params`: values for each of the fn/method's type parameters // - `vtables`: values for each bound on each of the type parameters let _icx = bcx.insn_ctxt("trans_fn_ref_with_vtables"); let ccx = bcx.ccx(); let tcx = ccx.tcx; debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%?, ref_id=%?, \ type_params=%?, vtables=%?)", bcx.to_str(), def_id, ref_id, type_params.map(|t| bcx.ty_to_str(*t)), vtables); let _indenter = indenter(); assert!(type_params.all(|t|!ty::type_needs_infer(*t))); // Polytype of the function item (may have type params) let fn_tpt = ty::lookup_item_type(tcx, def_id); // Modify the def_id if this is a default method; we want to be // monomorphizing the trait's code. let (def_id, opt_impl_did) = match tcx.provided_method_sources.find(&def_id) { None => (def_id, None), Some(source) => (source.method_id, Some(source.impl_id)) }; // Check whether this fn has an inlined copy and, if so, redirect // def_id to the local id of the inlined copy. let def_id = { if def_id.crate!= ast::local_crate { let may_translate = opt_impl_did.is_none(); inline::maybe_instantiate_inline(ccx, def_id, may_translate) } else { def_id } }; // We must monomorphise if the fn has type parameters, is a rust // intrinsic, or is a default method. In particular, if we see an // intrinsic that is inlined from a different crate, we want to reemit the // intrinsic instead of trying to call it in the other crate. let must_monomorphise; if type_params.len() > 0 || opt_impl_did.is_some() { must_monomorphise = true; } else if def_id.crate == ast::local_crate { let map_node = session::expect( ccx.sess, ccx.tcx.items.find(&def_id.node), || fmt!("local item should be in ast map")); match *map_node { ast_map::node_foreign_item(_, abis, _, _) => { must_monomorphise = abis.is_intrinsic() } _ => { must_monomorphise = false; } } } else { must_monomorphise = false; } // Create a monomorphic verison of generic functions if must_monomorphise { // Should be either intra-crate or inlined. assert!(def_id.crate == ast::local_crate); let mut (val, must_cast) = monomorphize::monomorphic_fn(ccx, def_id, type_params, vtables, opt_impl_did, Some(ref_id)); if must_cast && ref_id!= 0 { // Monotype of the REFERENCE to the function (type params // are subst'd) let ref_ty = common::node_id_type(bcx, ref_id); val = PointerCast( bcx, val, T_ptr(type_of::type_of_fn_from_ty(ccx, ref_ty))); } return FnData {llfn: val}; } // Find the actual function pointer. let mut val = { if def_id.crate == ast::local_crate { // Internal reference. get_item_val(ccx, def_id.node) } else { // External reference. trans_external_path(ccx, def_id, fn_tpt.ty) } }; return FnData {llfn: val}; } // ______________________________________________________________________ // Translating calls pub fn trans_call(in_cx: block, call_ex: @ast::expr, f: @ast::expr, args: CallArgs, id: ast::node_id, dest: expr::Dest) -> block { let _icx = in_cx.insn_ctxt("trans_call"); trans_call_inner( in_cx, call_ex.info(), expr_ty(in_cx, f), node_id_type(in_cx, id), |cx| trans(cx, f), args, dest, DontAutorefArg) } pub fn trans_method_call(in_cx: block, call_ex: @ast::expr, rcvr: @ast::expr, args: CallArgs, dest: expr::Dest) -> block
~"method call expr wasn't in \ method map") } } }, args, dest, DontAutorefArg) } pub fn trans_lang_call(bcx: block, did: ast::def_id, args: &[ValueRef], dest: expr::Dest) -> block { let fty = if did.crate == ast::local_crate { ty::node_id_to_type(bcx.ccx().tcx, did.node) } else { csearch::get_type(bcx.ccx().tcx, did).ty }; let rty = ty::ty_fn_ret(fty); return callee::trans_call_inner( bcx, None, fty, rty, |bcx| trans_fn_ref_with_vtables_to_callee(bcx, did, 0, ~[], None), ArgVals(args), dest, DontAutorefArg); } pub fn trans_lang_call_with_type_params(bcx: block, did: ast::def_id, args: &[ValueRef], type_params: &[ty::t], dest: expr::Dest) -> block { let fty; if did.crate == ast::local_crate { fty = ty::node_id_to_type(bcx.tcx(), did.node); } else { fty = csearch::get_type(bcx.tcx(), did).ty; } let rty = ty::ty_fn_ret(fty); return callee::trans_call_inner( bcx, None, fty, rty, |bcx| { let callee = trans_fn_ref_with_vtables_to_callee(bcx, did, 0, type_params, None); let new_llval; match callee.data { Fn(fn_data) => { let substituted = ty::subst_tps(callee.bcx.tcx(), type_params, None, fty); let mut llfnty = type_of::type_of(callee.bcx.ccx(), substituted); new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty); } _ => fail!() } Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) } }, ArgVals(args), dest, DontAutorefArg); } pub fn body_contains_ret(body: &ast::blk) -> bool { let cx = @mut false; visit::visit_block(body, cx, visit::mk_vt(@visit::Visitor { visit_item: |_i, _cx, _v| { }, visit_expr: |e: @ast::expr, cx: @mut bool, v| { if!*cx { match e.node { ast::expr_ret(_) => *cx = true, _ => visit::visit_expr(e, cx, v), } } }, ..*visit::default_visitor() })); *cx } // See [Note-arg-mode] pub fn trans_call_inner( ++in_cx: block, call_info: Option<NodeInfo>, fn_expr_ty: ty::t, ret_ty: ty::t, get_callee: &fn(block) -> Callee, args: CallArgs, dest: expr::Dest, autoref_arg: AutorefArg) -> block { do base::with_scope(in_cx, call_info, ~"call") |cx| { let ret_in_loop = match args { ArgExprs(args) => { args.len() > 0u && match vec::last(args).node { ast::expr_loop_body(@ast::expr { node: ast::expr_fn_block(_, ref body), _ }) => body_contains_ret(body), _ => false } } _ => false }; let callee = get_callee(cx); let mut bcx = callee.bcx; let ccx = cx.ccx(); let ret_flag = if ret_in_loop { let flag = alloca(bcx, T_bool()); Store(bcx, C_bool(false), flag); Some(flag) } else { None }; let (llfn, llenv) = unsafe { match callee.data { Fn(d) => { (d.llfn, llvm::LLVMGetUndef(T_opaque_box_ptr(ccx))) } Method(d) => { // Weird but true: we pass self in the *environment* slot! let llself = PointerCast(bcx, d.llself, T_opaque_box_ptr(ccx)); (d.llfn, llself) } Closure(d) => { // Closures are represented as (llfn, llclosure) pair: // load the requisite values out. let pair = d.to_ref_llval(bcx); let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]); let llfn = Load(bcx, llfn); let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]); let llenv = Load(bcx, llenv); (llfn, llenv) } } }; let llretslot = trans_ret_slot(bcx, fn_expr_ty, dest); let mut llargs = ~[]; llargs.push(llretslot); llargs.push(llenv); bcx = trans_args(bcx, args, fn_expr_ty, ret_flag, autoref_arg, &mut llargs); // Now that the arguments have finished evaluating, we need to revoke // the cleanup for the self argument, if it exists match callee.data { Method(d) if d.self_mode == ast::by_copy => { revoke_clean(bcx, d.llself); } _ => {} } // Uncomment this to debug calls. /* io::println(fmt!("calling: %s", bcx.val_str(llfn))); for llargs.each |llarg| { io::println(fmt!("arg: %s", bcx.val_str(*llarg))); } io::println("---"); */ // If the block is terminated, then one or more of the args // has type _|_. Since that means it diverges, the code for // the call itself is unreachable. bcx = base::invoke(bcx, llfn, llargs); match dest { // drop the value if it is not being saved. expr::Ignore => { unsafe { if llvm::LLVMIsUndef(llretslot)!= lib::llvm::True { bcx = glue::drop_ty(bcx, llretslot, ret_ty); } } } expr::SaveIn(_) => { } } if ty::type_is_bot(ret_ty) { Unreachable(bcx); } else if ret_in_loop { let ret_flag_result = bool_to_i1(bcx, Load(bcx, ret_flag.get())); bcx = do with_cond(bcx, ret_flag_result) |bcx| { for (copy bcx
{ let _icx = in_cx.insn_ctxt("trans_method_call"); trans_call_inner( in_cx, call_ex.info(), node_id_type(in_cx, call_ex.callee_id), expr_ty(in_cx, call_ex), |cx| { match cx.ccx().maps.method_map.find(&call_ex.id) { Some(origin) => { // FIXME(#5562): removing this copy causes a segfault // before stage2 let origin = /*bad*/ copy *origin; meth::trans_method_callee(cx, call_ex.callee_id, rcvr, origin) } None => { cx.tcx().sess.span_bug(call_ex.span,
identifier_body
callee.rs
functions if must_monomorphise { // Should be either intra-crate or inlined. assert!(def_id.crate == ast::local_crate); let mut (val, must_cast) = monomorphize::monomorphic_fn(ccx, def_id, type_params, vtables, opt_impl_did, Some(ref_id)); if must_cast && ref_id!= 0 { // Monotype of the REFERENCE to the function (type params // are subst'd) let ref_ty = common::node_id_type(bcx, ref_id); val = PointerCast( bcx, val, T_ptr(type_of::type_of_fn_from_ty(ccx, ref_ty))); } return FnData {llfn: val}; } // Find the actual function pointer. let mut val = { if def_id.crate == ast::local_crate { // Internal reference. get_item_val(ccx, def_id.node) } else { // External reference. trans_external_path(ccx, def_id, fn_tpt.ty) } }; return FnData {llfn: val}; } // ______________________________________________________________________ // Translating calls pub fn trans_call(in_cx: block, call_ex: @ast::expr, f: @ast::expr, args: CallArgs, id: ast::node_id, dest: expr::Dest) -> block { let _icx = in_cx.insn_ctxt("trans_call"); trans_call_inner( in_cx, call_ex.info(), expr_ty(in_cx, f), node_id_type(in_cx, id), |cx| trans(cx, f), args, dest, DontAutorefArg) } pub fn trans_method_call(in_cx: block, call_ex: @ast::expr, rcvr: @ast::expr, args: CallArgs, dest: expr::Dest) -> block { let _icx = in_cx.insn_ctxt("trans_method_call"); trans_call_inner( in_cx, call_ex.info(), node_id_type(in_cx, call_ex.callee_id), expr_ty(in_cx, call_ex), |cx| { match cx.ccx().maps.method_map.find(&call_ex.id) { Some(origin) => { // FIXME(#5562): removing this copy causes a segfault // before stage2 let origin = /*bad*/ copy *origin; meth::trans_method_callee(cx, call_ex.callee_id, rcvr, origin) } None => { cx.tcx().sess.span_bug(call_ex.span, ~"method call expr wasn't in \ method map") } } }, args, dest, DontAutorefArg) } pub fn trans_lang_call(bcx: block, did: ast::def_id, args: &[ValueRef], dest: expr::Dest) -> block { let fty = if did.crate == ast::local_crate { ty::node_id_to_type(bcx.ccx().tcx, did.node) } else { csearch::get_type(bcx.ccx().tcx, did).ty }; let rty = ty::ty_fn_ret(fty); return callee::trans_call_inner( bcx, None, fty, rty, |bcx| trans_fn_ref_with_vtables_to_callee(bcx, did, 0, ~[], None), ArgVals(args), dest, DontAutorefArg); } pub fn trans_lang_call_with_type_params(bcx: block, did: ast::def_id, args: &[ValueRef], type_params: &[ty::t], dest: expr::Dest) -> block { let fty; if did.crate == ast::local_crate { fty = ty::node_id_to_type(bcx.tcx(), did.node); } else { fty = csearch::get_type(bcx.tcx(), did).ty; } let rty = ty::ty_fn_ret(fty); return callee::trans_call_inner( bcx, None, fty, rty, |bcx| { let callee = trans_fn_ref_with_vtables_to_callee(bcx, did, 0, type_params, None); let new_llval; match callee.data { Fn(fn_data) => { let substituted = ty::subst_tps(callee.bcx.tcx(), type_params, None, fty); let mut llfnty = type_of::type_of(callee.bcx.ccx(), substituted); new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty); } _ => fail!() } Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) } }, ArgVals(args), dest, DontAutorefArg); } pub fn body_contains_ret(body: &ast::blk) -> bool { let cx = @mut false; visit::visit_block(body, cx, visit::mk_vt(@visit::Visitor { visit_item: |_i, _cx, _v| { }, visit_expr: |e: @ast::expr, cx: @mut bool, v| { if!*cx { match e.node { ast::expr_ret(_) => *cx = true, _ => visit::visit_expr(e, cx, v), } } }, ..*visit::default_visitor() })); *cx } // See [Note-arg-mode] pub fn trans_call_inner( ++in_cx: block, call_info: Option<NodeInfo>, fn_expr_ty: ty::t, ret_ty: ty::t, get_callee: &fn(block) -> Callee, args: CallArgs, dest: expr::Dest, autoref_arg: AutorefArg) -> block { do base::with_scope(in_cx, call_info, ~"call") |cx| { let ret_in_loop = match args { ArgExprs(args) => { args.len() > 0u && match vec::last(args).node { ast::expr_loop_body(@ast::expr { node: ast::expr_fn_block(_, ref body), _ }) => body_contains_ret(body), _ => false } } _ => false }; let callee = get_callee(cx); let mut bcx = callee.bcx; let ccx = cx.ccx(); let ret_flag = if ret_in_loop { let flag = alloca(bcx, T_bool()); Store(bcx, C_bool(false), flag); Some(flag) } else { None }; let (llfn, llenv) = unsafe { match callee.data { Fn(d) => { (d.llfn, llvm::LLVMGetUndef(T_opaque_box_ptr(ccx))) } Method(d) => { // Weird but true: we pass self in the *environment* slot! let llself = PointerCast(bcx, d.llself, T_opaque_box_ptr(ccx)); (d.llfn, llself) } Closure(d) => { // Closures are represented as (llfn, llclosure) pair: // load the requisite values out. let pair = d.to_ref_llval(bcx); let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]); let llfn = Load(bcx, llfn); let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]); let llenv = Load(bcx, llenv); (llfn, llenv) } } }; let llretslot = trans_ret_slot(bcx, fn_expr_ty, dest); let mut llargs = ~[]; llargs.push(llretslot); llargs.push(llenv); bcx = trans_args(bcx, args, fn_expr_ty, ret_flag, autoref_arg, &mut llargs); // Now that the arguments have finished evaluating, we need to revoke // the cleanup for the self argument, if it exists match callee.data { Method(d) if d.self_mode == ast::by_copy => { revoke_clean(bcx, d.llself); } _ => {} } // Uncomment this to debug calls. /* io::println(fmt!("calling: %s", bcx.val_str(llfn))); for llargs.each |llarg| { io::println(fmt!("arg: %s", bcx.val_str(*llarg))); } io::println("---"); */ // If the block is terminated, then one or more of the args // has type _|_. Since that means it diverges, the code for // the call itself is unreachable. bcx = base::invoke(bcx, llfn, llargs); match dest { // drop the value if it is not being saved. expr::Ignore => { unsafe { if llvm::LLVMIsUndef(llretslot)!= lib::llvm::True { bcx = glue::drop_ty(bcx, llretslot, ret_ty); } } } expr::SaveIn(_) => { } } if ty::type_is_bot(ret_ty) { Unreachable(bcx); } else if ret_in_loop { let ret_flag_result = bool_to_i1(bcx, Load(bcx, ret_flag.get())); bcx = do with_cond(bcx, ret_flag_result) |bcx| { for (copy bcx.fcx.loop_ret).each |&(flagptr, _)| { Store(bcx, C_bool(true), flagptr); Store(bcx, C_bool(false), bcx.fcx.llretptr); } base::cleanup_and_leave(bcx, None, Some(bcx.fcx.llreturn)); Unreachable(bcx); bcx } } bcx } } pub enum CallArgs<'self> { ArgExprs(&'self [@ast::expr]), ArgVals(&'self [ValueRef]) } pub fn trans_ret_slot(+bcx: block, +fn_ty: ty::t, +dest: expr::Dest) -> ValueRef { let retty = ty::ty_fn_ret(fn_ty); match dest { expr::SaveIn(dst) => dst, expr::Ignore => { if ty::type_is_nil(retty) { unsafe { llvm::LLVMGetUndef(T_ptr(T_nil())) } } else { alloc_ty(bcx, retty) } } } } pub fn trans_args(+cx: block, +args: CallArgs, +fn_ty: ty::t, +ret_flag: Option<ValueRef>, +autoref_arg: AutorefArg, +llargs: &mut ~[ValueRef]) -> block { let _icx = cx.insn_ctxt("trans_args"); let mut temp_cleanups = ~[]; let arg_tys = ty::ty_fn_args(fn_ty); let mut bcx = cx; // First we figure out the caller's view of the types of the arguments. // This will be needed if this is a generic call, because the callee has // to cast her view of the arguments to the caller's view. match args { ArgExprs(arg_exprs) => { let last = arg_exprs.len() - 1u; for vec::eachi(arg_exprs) |i, arg_expr| { let arg_val = unpack_result!(bcx, { trans_arg_expr(bcx, arg_tys[i], *arg_expr, &mut temp_cleanups, if i == last { ret_flag } else { None }, autoref_arg) }); llargs.push(arg_val); } } ArgVals(vs) => { llargs.push_all(vs); } } // now that all arguments have been successfully built, we can revoke any // temporary cleanups, as they are only needed if argument construction // should fail (for example, cleanup of copy mode args). for vec::each(temp_cleanups) |c| { revoke_clean(bcx, *c) } return bcx; } pub enum AutorefArg { DontAutorefArg, DoAutorefArg } // temp_cleanups: cleanups that should run only if failure occurs before the // call takes place: pub fn trans_arg_expr(bcx: block, formal_ty: ty::arg, arg_expr: @ast::expr, +temp_cleanups: &mut ~[ValueRef], +ret_flag: Option<ValueRef>, +autoref_arg: AutorefArg) -> Result { let _icx = bcx.insn_ctxt("trans_arg_expr"); let ccx = bcx.ccx(); debug!("trans_arg_expr(formal_ty=(%?,%s), arg_expr=%s, \ ret_flag=%?)", formal_ty.mode, bcx.ty_to_str(formal_ty.ty), bcx.expr_to_str(arg_expr), ret_flag.map(|v| bcx.val_str(*v))); let _indenter = indenter(); // translate the arg expr to a datum let arg_datumblock = match ret_flag { None => expr::trans_to_datum(bcx, arg_expr), // If there is a ret_flag, this *must* be a loop body Some(_) => { match arg_expr.node { ast::expr_loop_body( blk @ @ast::expr { node: ast::expr_fn_block(ref decl, ref body), _ }) => { let scratch_ty = expr_ty(bcx, arg_expr); let scratch = alloc_ty(bcx, scratch_ty); let arg_ty = expr_ty(bcx, arg_expr); let sigil = ty::ty_closure_sigil(arg_ty); let bcx = closure::trans_expr_fn( bcx, sigil, decl, body, arg_expr.id, blk.id, Some(ret_flag), expr::SaveIn(scratch)); DatumBlock {bcx: bcx, datum: Datum {val: scratch, ty: scratch_ty, mode: ByRef, source: RevokeClean}} } _ => { bcx.sess().impossible_case( arg_expr.span, ~"ret_flag with non-loop-\ body expr"); } } } }; let mut arg_datum = arg_datumblock.datum; let mut bcx = arg_datumblock.bcx; debug!(" arg datum: %s", arg_datum.to_str(bcx.ccx())); // finally, deal with the various modes let arg_mode = ty::resolved_mode(ccx.tcx, formal_ty.mode); let mut val; if ty::type_is_bot(arg_datum.ty) { // For values of type _|_, we generate an // "undef" value, as such a value should never // be inspected. It's important for the value
random_line_split
callee.rs
ref_expr.id)) } ast::def_variant(tid, vid) => { // nullary variants are not callable assert!(ty::enum_variant_with_id(bcx.tcx(), tid, vid).args.len() > 0u); fn_callee(bcx, trans_fn_ref(bcx, vid, ref_expr.id)) } ast::def_struct(def_id) => { fn_callee(bcx, trans_fn_ref(bcx, def_id, ref_expr.id)) } ast::def_arg(*) | ast::def_local(*) | ast::def_binding(*) | ast::def_upvar(*) | ast::def_self(*) => { datum_callee(bcx, ref_expr) } ast::def_mod(*) | ast::def_foreign_mod(*) | ast::def_const(*) | ast::def_ty(*) | ast::def_prim_ty(*) | ast::def_use(*) | ast::def_typaram_binder(*) | ast::def_region(*) | ast::def_label(*) | ast::def_ty_param(*) | ast::def_self_ty(*) => { bcx.tcx().sess.span_bug( ref_expr.span, fmt!("Cannot translate def %? \ to a callable thing!", def)); } } } } pub fn trans_fn_ref_to_callee(bcx: block, def_id: ast::def_id, ref_id: ast::node_id) -> Callee { Callee {bcx: bcx, data: Fn(trans_fn_ref(bcx, def_id, ref_id))} } pub fn trans_fn_ref(bcx: block, def_id: ast::def_id, ref_id: ast::node_id) -> FnData { /*! * * Translates a reference (with id `ref_id`) to the fn/method * with id `def_id` into a function pointer. This may require * monomorphization or inlining. */ let _icx = bcx.insn_ctxt("trans_fn"); let type_params = node_id_type_params(bcx, ref_id); let vtables = node_vtables(bcx, ref_id); trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables) } pub fn trans_fn_ref_with_vtables_to_callee( bcx: block, def_id: ast::def_id, ref_id: ast::node_id, type_params: &[ty::t], vtables: Option<typeck::vtable_res>) -> Callee { Callee {bcx: bcx, data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables))} } pub fn trans_fn_ref_with_vtables( bcx: block, // def_id: ast::def_id, // def id of fn ref_id: ast::node_id, // node id of use of fn; may be zero if N/A type_params: &[ty::t], // values for fn's ty params vtables: Option<typeck::vtable_res>) -> FnData { //! // // Translates a reference to a fn/method item, monomorphizing and // inlining as it goes. // // # Parameters // // - `bcx`: the current block where the reference to the fn occurs // - `def_id`: def id of the fn or method item being referenced // - `ref_id`: node id of the reference to the fn/method, if applicable. // This parameter may be zero; but, if so, the resulting value may not // have the right type, so it must be cast before being used. // - `type_params`: values for each of the fn/method's type parameters // - `vtables`: values for each bound on each of the type parameters let _icx = bcx.insn_ctxt("trans_fn_ref_with_vtables"); let ccx = bcx.ccx(); let tcx = ccx.tcx; debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%?, ref_id=%?, \ type_params=%?, vtables=%?)", bcx.to_str(), def_id, ref_id, type_params.map(|t| bcx.ty_to_str(*t)), vtables); let _indenter = indenter(); assert!(type_params.all(|t|!ty::type_needs_infer(*t))); // Polytype of the function item (may have type params) let fn_tpt = ty::lookup_item_type(tcx, def_id); // Modify the def_id if this is a default method; we want to be // monomorphizing the trait's code. let (def_id, opt_impl_did) = match tcx.provided_method_sources.find(&def_id) { None => (def_id, None), Some(source) => (source.method_id, Some(source.impl_id)) }; // Check whether this fn has an inlined copy and, if so, redirect // def_id to the local id of the inlined copy. let def_id = { if def_id.crate!= ast::local_crate { let may_translate = opt_impl_did.is_none(); inline::maybe_instantiate_inline(ccx, def_id, may_translate) } else { def_id } }; // We must monomorphise if the fn has type parameters, is a rust // intrinsic, or is a default method. In particular, if we see an // intrinsic that is inlined from a different crate, we want to reemit the // intrinsic instead of trying to call it in the other crate. let must_monomorphise; if type_params.len() > 0 || opt_impl_did.is_some() { must_monomorphise = true; } else if def_id.crate == ast::local_crate { let map_node = session::expect( ccx.sess, ccx.tcx.items.find(&def_id.node), || fmt!("local item should be in ast map")); match *map_node { ast_map::node_foreign_item(_, abis, _, _) => { must_monomorphise = abis.is_intrinsic() } _ => { must_monomorphise = false; } } } else { must_monomorphise = false; } // Create a monomorphic verison of generic functions if must_monomorphise { // Should be either intra-crate or inlined. assert!(def_id.crate == ast::local_crate); let mut (val, must_cast) = monomorphize::monomorphic_fn(ccx, def_id, type_params, vtables, opt_impl_did, Some(ref_id)); if must_cast && ref_id!= 0 { // Monotype of the REFERENCE to the function (type params // are subst'd) let ref_ty = common::node_id_type(bcx, ref_id); val = PointerCast( bcx, val, T_ptr(type_of::type_of_fn_from_ty(ccx, ref_ty))); } return FnData {llfn: val}; } // Find the actual function pointer. let mut val = { if def_id.crate == ast::local_crate { // Internal reference. get_item_val(ccx, def_id.node) } else { // External reference. trans_external_path(ccx, def_id, fn_tpt.ty) } }; return FnData {llfn: val}; } // ______________________________________________________________________ // Translating calls pub fn trans_call(in_cx: block, call_ex: @ast::expr, f: @ast::expr, args: CallArgs, id: ast::node_id, dest: expr::Dest) -> block { let _icx = in_cx.insn_ctxt("trans_call"); trans_call_inner( in_cx, call_ex.info(), expr_ty(in_cx, f), node_id_type(in_cx, id), |cx| trans(cx, f), args, dest, DontAutorefArg) } pub fn
(in_cx: block, call_ex: @ast::expr, rcvr: @ast::expr, args: CallArgs, dest: expr::Dest) -> block { let _icx = in_cx.insn_ctxt("trans_method_call"); trans_call_inner( in_cx, call_ex.info(), node_id_type(in_cx, call_ex.callee_id), expr_ty(in_cx, call_ex), |cx| { match cx.ccx().maps.method_map.find(&call_ex.id) { Some(origin) => { // FIXME(#5562): removing this copy causes a segfault // before stage2 let origin = /*bad*/ copy *origin; meth::trans_method_callee(cx, call_ex.callee_id, rcvr, origin) } None => { cx.tcx().sess.span_bug(call_ex.span, ~"method call expr wasn't in \ method map") } } }, args, dest, DontAutorefArg) } pub fn trans_lang_call(bcx: block, did: ast::def_id, args: &[ValueRef], dest: expr::Dest) -> block { let fty = if did.crate == ast::local_crate { ty::node_id_to_type(bcx.ccx().tcx, did.node) } else { csearch::get_type(bcx.ccx().tcx, did).ty }; let rty = ty::ty_fn_ret(fty); return callee::trans_call_inner( bcx, None, fty, rty, |bcx| trans_fn_ref_with_vtables_to_callee(bcx, did, 0, ~[], None), ArgVals(args), dest, DontAutorefArg); } pub fn trans_lang_call_with_type_params(bcx: block, did: ast::def_id, args: &[ValueRef], type_params: &[ty::t], dest: expr::Dest) -> block { let fty; if did.crate == ast::local_crate { fty = ty::node_id_to_type(bcx.tcx(), did.node); } else { fty = csearch::get_type(bcx.tcx(), did).ty; } let rty = ty::ty_fn_ret(fty); return callee::trans_call_inner( bcx, None, fty, rty, |bcx| { let callee = trans_fn_ref_with_vtables_to_callee(bcx, did, 0, type_params, None); let new_llval; match callee.data { Fn(fn_data) => { let substituted = ty::subst_tps(callee.bcx.tcx(), type_params, None, fty); let mut llfnty = type_of::type_of(callee.bcx.ccx(), substituted); new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty); } _ => fail!() } Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) } }, ArgVals(args), dest, DontAutorefArg); } pub fn body_contains_ret(body: &ast::blk) -> bool { let cx = @mut false; visit::visit_block(body, cx, visit::mk_vt(@visit::Visitor { visit_item: |_i, _cx, _v| { }, visit_expr: |e: @ast::expr, cx: @mut bool, v| { if!*cx { match e.node { ast::expr_ret(_) => *cx = true, _ => visit::visit_expr(e, cx, v), } } }, ..*visit::default_visitor() })); *cx } // See [Note-arg-mode] pub fn trans_call_inner( ++in_cx: block, call_info: Option<NodeInfo>, fn_expr_ty: ty::t, ret_ty: ty::t, get_callee: &fn(block) -> Callee, args: CallArgs, dest: expr::Dest, autoref_arg: AutorefArg) -> block { do base::with_scope(in_cx, call_info, ~"call") |cx| { let ret_in_loop = match args { ArgExprs(args) => { args.len() > 0u && match vec::last(args).node { ast::expr_loop_body(@ast::expr { node: ast::expr_fn_block(_, ref body), _ }) => body_contains_ret(body), _ => false } } _ => false }; let callee = get_callee(cx); let mut bcx = callee.bcx; let ccx = cx.ccx(); let ret_flag = if ret_in_loop { let flag = alloca(bcx, T_bool()); Store(bcx, C_bool(false), flag); Some(flag) } else { None }; let (llfn, llenv) = unsafe { match callee.data { Fn(d) => { (d.llfn, llvm::LLVMGetUndef(T_opaque_box_ptr(ccx))) } Method(d) => { // Weird but true: we pass self in the *environment* slot! let llself = PointerCast(bcx, d.llself, T_opaque_box_ptr(ccx)); (d.llfn, llself) } Closure(d) => { // Closures are represented as (llfn, llclosure) pair: // load the requisite values out. let pair = d.to_ref_llval(bcx); let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]); let llfn = Load(bcx, llfn); let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]); let llenv = Load(bcx, llenv); (llfn, llenv) } } }; let llretslot = trans_ret_slot(bcx, fn_expr_ty, dest); let mut llargs = ~[]; llargs.push(llretslot); llargs.push(llenv); bcx = trans_args(bcx, args, fn_expr_ty, ret_flag, autoref_arg, &mut llargs); // Now that the arguments have finished evaluating, we need to revoke // the cleanup for the self argument, if it exists match callee.data { Method(d) if d.self_mode == ast::by_copy => { revoke_clean(bcx, d.llself); } _ => {} } // Uncomment this to debug calls. /* io::println(fmt!("calling: %s", bcx.val_str(llfn))); for llargs.each |llarg| { io::println(fmt!("arg: %s", bcx.val_str(*llarg))); } io::println("---"); */ // If the block is terminated, then one or more of the args // has type _|_. Since that means it diverges, the code for // the call itself is unreachable. bcx = base::invoke(bcx, llfn, llargs); match dest { // drop the value if it is not being saved. expr::Ignore => { unsafe { if llvm::LLVMIsUndef(llretslot)!= lib::llvm::True { bcx = glue::drop_ty(bcx, llretslot, ret_ty); } } } expr::SaveIn(_) => { } } if ty::type_is_bot(ret_ty) { Unreachable(bcx); } else if ret_in_loop { let ret_flag_result = bool_to_i1(bcx, Load(bcx, ret_flag.get())); bcx = do with_cond(bcx, ret_flag_result) |bcx| { for (copy bcx
trans_method_call
identifier_name
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] //! Test infrastructure for the Diem VM. //! //! This crate contains helpers for executing tests against the Diem VM. use diem_types::{transaction::TransactionStatus, vm_status::KeptVMStatus}; pub mod account; pub mod account_universe; pub mod common_transactions; pub mod compile; pub mod currencies; pub mod data_store; pub mod execution_strategies; pub mod executor; pub mod gas_costs; mod golden_outputs; pub mod keygen; mod proptest_types; pub fn assert_status_eq(s1: &KeptVMStatus, s2: &KeptVMStatus) -> bool { assert_eq!(s1, s2); true } pub fn transaction_status_eq(t1: &TransactionStatus, t2: &TransactionStatus) -> bool { match (t1, t2) { (TransactionStatus::Discard(s1), TransactionStatus::Discard(s2)) => { assert_eq!(s1, s2); true } (TransactionStatus::Keep(s1), TransactionStatus::Keep(s2)) => { assert_eq!(s1, s2); true } _ => false, }
#[macro_export] macro_rules! assert_prologue_parity { ($e1:expr, $e2:expr, $e3:expr) => { assert_eq!($e1.unwrap(), $e3); assert!(transaction_status_eq($e2, &TransactionStatus::Discard($e3))); }; } #[macro_export] macro_rules! assert_prologue_disparity { ($e1:expr => $e2:expr, $e3:expr => $e4:expr) => { assert_eq!($e1, $e2); assert!(transaction_status_eq($e3, &$e4)); }; } /// Returns the name of the current function. This macro is used to derive the name for the golden /// file of each test case. #[macro_export] macro_rules! current_function_name { () => {{ fn f() {} fn type_name_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } let name = type_name_of(f); &name[..name.len() - 3] }}; }
}
random_line_split
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] //! Test infrastructure for the Diem VM. //! //! This crate contains helpers for executing tests against the Diem VM. use diem_types::{transaction::TransactionStatus, vm_status::KeptVMStatus}; pub mod account; pub mod account_universe; pub mod common_transactions; pub mod compile; pub mod currencies; pub mod data_store; pub mod execution_strategies; pub mod executor; pub mod gas_costs; mod golden_outputs; pub mod keygen; mod proptest_types; pub fn assert_status_eq(s1: &KeptVMStatus, s2: &KeptVMStatus) -> bool { assert_eq!(s1, s2); true } pub fn
(t1: &TransactionStatus, t2: &TransactionStatus) -> bool { match (t1, t2) { (TransactionStatus::Discard(s1), TransactionStatus::Discard(s2)) => { assert_eq!(s1, s2); true } (TransactionStatus::Keep(s1), TransactionStatus::Keep(s2)) => { assert_eq!(s1, s2); true } _ => false, } } #[macro_export] macro_rules! assert_prologue_parity { ($e1:expr, $e2:expr, $e3:expr) => { assert_eq!($e1.unwrap(), $e3); assert!(transaction_status_eq($e2, &TransactionStatus::Discard($e3))); }; } #[macro_export] macro_rules! assert_prologue_disparity { ($e1:expr => $e2:expr, $e3:expr => $e4:expr) => { assert_eq!($e1, $e2); assert!(transaction_status_eq($e3, &$e4)); }; } /// Returns the name of the current function. This macro is used to derive the name for the golden /// file of each test case. #[macro_export] macro_rules! current_function_name { () => {{ fn f() {} fn type_name_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } let name = type_name_of(f); &name[..name.len() - 3] }}; }
transaction_status_eq
identifier_name
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] //! Test infrastructure for the Diem VM. //! //! This crate contains helpers for executing tests against the Diem VM. use diem_types::{transaction::TransactionStatus, vm_status::KeptVMStatus}; pub mod account; pub mod account_universe; pub mod common_transactions; pub mod compile; pub mod currencies; pub mod data_store; pub mod execution_strategies; pub mod executor; pub mod gas_costs; mod golden_outputs; pub mod keygen; mod proptest_types; pub fn assert_status_eq(s1: &KeptVMStatus, s2: &KeptVMStatus) -> bool { assert_eq!(s1, s2); true } pub fn transaction_status_eq(t1: &TransactionStatus, t2: &TransactionStatus) -> bool
#[macro_export] macro_rules! assert_prologue_parity { ($e1:expr, $e2:expr, $e3:expr) => { assert_eq!($e1.unwrap(), $e3); assert!(transaction_status_eq($e2, &TransactionStatus::Discard($e3))); }; } #[macro_export] macro_rules! assert_prologue_disparity { ($e1:expr => $e2:expr, $e3:expr => $e4:expr) => { assert_eq!($e1, $e2); assert!(transaction_status_eq($e3, &$e4)); }; } /// Returns the name of the current function. This macro is used to derive the name for the golden /// file of each test case. #[macro_export] macro_rules! current_function_name { () => {{ fn f() {} fn type_name_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } let name = type_name_of(f); &name[..name.len() - 3] }}; }
{ match (t1, t2) { (TransactionStatus::Discard(s1), TransactionStatus::Discard(s2)) => { assert_eq!(s1, s2); true } (TransactionStatus::Keep(s1), TransactionStatus::Keep(s2)) => { assert_eq!(s1, s2); true } _ => false, } }
identifier_body
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] //! Test infrastructure for the Diem VM. //! //! This crate contains helpers for executing tests against the Diem VM. use diem_types::{transaction::TransactionStatus, vm_status::KeptVMStatus}; pub mod account; pub mod account_universe; pub mod common_transactions; pub mod compile; pub mod currencies; pub mod data_store; pub mod execution_strategies; pub mod executor; pub mod gas_costs; mod golden_outputs; pub mod keygen; mod proptest_types; pub fn assert_status_eq(s1: &KeptVMStatus, s2: &KeptVMStatus) -> bool { assert_eq!(s1, s2); true } pub fn transaction_status_eq(t1: &TransactionStatus, t2: &TransactionStatus) -> bool { match (t1, t2) { (TransactionStatus::Discard(s1), TransactionStatus::Discard(s2)) => { assert_eq!(s1, s2); true } (TransactionStatus::Keep(s1), TransactionStatus::Keep(s2)) =>
_ => false, } } #[macro_export] macro_rules! assert_prologue_parity { ($e1:expr, $e2:expr, $e3:expr) => { assert_eq!($e1.unwrap(), $e3); assert!(transaction_status_eq($e2, &TransactionStatus::Discard($e3))); }; } #[macro_export] macro_rules! assert_prologue_disparity { ($e1:expr => $e2:expr, $e3:expr => $e4:expr) => { assert_eq!($e1, $e2); assert!(transaction_status_eq($e3, &$e4)); }; } /// Returns the name of the current function. This macro is used to derive the name for the golden /// file of each test case. #[macro_export] macro_rules! current_function_name { () => {{ fn f() {} fn type_name_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } let name = type_name_of(f); &name[..name.len() - 3] }}; }
{ assert_eq!(s1, s2); true }
conditional_block
utility.rs
use std::sync::Arc;
/// [`ArenaSet`]: struct.ArenaSet.html pub fn string_arena_set() -> ArenaSet<String> { builder().hash().unwrap() } /// Create an [`ArenaSet`] for `Vec<u8>` with a `HashMap` and an ID of `usize`. /// [`ArenaSet`]: struct.ArenaSet.html pub fn byte_arena_set() -> ArenaSet<Vec<u8>> { builder().hash().unwrap() } /// Create a [`StadiumSet`] for `Arc<String>` with a `HashMap` and an ID of `usize`. /// [`StadiumSet`]: struct.StadiumSet.html pub fn string_stadium_set() -> StadiumSet<Arc<String>> { builder().stadium_set_hash().unwrap() } /// Create a [`StadiumSet`] for `Arc<Vec<u8>>` with a `HashMap` and an ID of `usize`. /// [`StadiumSet`]: struct.StadiumSet.html pub fn byte_stadium_set() -> StadiumSet<Arc<Vec<u8>>> { builder().stadium_set_hash().unwrap() }
use builder::builder; use arena_set::{ArenaSet, StadiumSet}; /// Create an [`ArenaSet`] for `String` with a `HashMap` and an ID of `usize`.
random_line_split
utility.rs
use std::sync::Arc; use builder::builder; use arena_set::{ArenaSet, StadiumSet}; /// Create an [`ArenaSet`] for `String` with a `HashMap` and an ID of `usize`. /// [`ArenaSet`]: struct.ArenaSet.html pub fn string_arena_set() -> ArenaSet<String> { builder().hash().unwrap() } /// Create an [`ArenaSet`] for `Vec<u8>` with a `HashMap` and an ID of `usize`. /// [`ArenaSet`]: struct.ArenaSet.html pub fn byte_arena_set() -> ArenaSet<Vec<u8>>
/// Create a [`StadiumSet`] for `Arc<String>` with a `HashMap` and an ID of `usize`. /// [`StadiumSet`]: struct.StadiumSet.html pub fn string_stadium_set() -> StadiumSet<Arc<String>> { builder().stadium_set_hash().unwrap() } /// Create a [`StadiumSet`] for `Arc<Vec<u8>>` with a `HashMap` and an ID of `usize`. /// [`StadiumSet`]: struct.StadiumSet.html pub fn byte_stadium_set() -> StadiumSet<Arc<Vec<u8>>> { builder().stadium_set_hash().unwrap() }
{ builder().hash().unwrap() }
identifier_body
utility.rs
use std::sync::Arc; use builder::builder; use arena_set::{ArenaSet, StadiumSet}; /// Create an [`ArenaSet`] for `String` with a `HashMap` and an ID of `usize`. /// [`ArenaSet`]: struct.ArenaSet.html pub fn string_arena_set() -> ArenaSet<String> { builder().hash().unwrap() } /// Create an [`ArenaSet`] for `Vec<u8>` with a `HashMap` and an ID of `usize`. /// [`ArenaSet`]: struct.ArenaSet.html pub fn byte_arena_set() -> ArenaSet<Vec<u8>> { builder().hash().unwrap() } /// Create a [`StadiumSet`] for `Arc<String>` with a `HashMap` and an ID of `usize`. /// [`StadiumSet`]: struct.StadiumSet.html pub fn string_stadium_set() -> StadiumSet<Arc<String>> { builder().stadium_set_hash().unwrap() } /// Create a [`StadiumSet`] for `Arc<Vec<u8>>` with a `HashMap` and an ID of `usize`. /// [`StadiumSet`]: struct.StadiumSet.html pub fn
() -> StadiumSet<Arc<Vec<u8>>> { builder().stadium_set_hash().unwrap() }
byte_stadium_set
identifier_name
fps.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // 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 extra::time; use perf_metrics::PerfHandler; pub struct Fps { priv frames: f64, priv cur_frames: f64, priv frame_start: f64, } impl Fps { pub fn
() -> Fps { Fps { frames: 0., cur_frames: 0., frame_start: time::precise_time_s() } } } impl PerfHandler for Fps { fn reset(&mut self) -> () { self.frames = 0.; self.cur_frames = 0.; self.frame_start = time::precise_time_s(); } fn frame_begin(&mut self) -> () { } fn frame_end(&mut self) -> () { self.cur_frames += 1.; if time::precise_time_s() - self.frame_start >= 1. { self.frame_start = time::precise_time_s(); self.frames = self.cur_frames; self.cur_frames = 0.; } } fn get_value(&self) -> Option<f64> { Some(self.frames) } }
new
identifier_name
fps.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // 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 extra::time; use perf_metrics::PerfHandler; pub struct Fps { priv frames: f64, priv cur_frames: f64, priv frame_start: f64, } impl Fps { pub fn new() -> Fps { Fps { frames: 0., cur_frames: 0., frame_start: time::precise_time_s() } } } impl PerfHandler for Fps { fn reset(&mut self) -> () { self.frames = 0.; self.cur_frames = 0.; self.frame_start = time::precise_time_s(); }
fn frame_end(&mut self) -> () { self.cur_frames += 1.; if time::precise_time_s() - self.frame_start >= 1. { self.frame_start = time::precise_time_s(); self.frames = self.cur_frames; self.cur_frames = 0.; } } fn get_value(&self) -> Option<f64> { Some(self.frames) } }
fn frame_begin(&mut self) -> () { }
random_line_split
fps.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // 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 extra::time; use perf_metrics::PerfHandler; pub struct Fps { priv frames: f64, priv cur_frames: f64, priv frame_start: f64, } impl Fps { pub fn new() -> Fps { Fps { frames: 0., cur_frames: 0., frame_start: time::precise_time_s() } } } impl PerfHandler for Fps { fn reset(&mut self) -> () { self.frames = 0.; self.cur_frames = 0.; self.frame_start = time::precise_time_s(); } fn frame_begin(&mut self) -> () { } fn frame_end(&mut self) -> () { self.cur_frames += 1.; if time::precise_time_s() - self.frame_start >= 1.
} fn get_value(&self) -> Option<f64> { Some(self.frames) } }
{ self.frame_start = time::precise_time_s(); self.frames = self.cur_frames; self.cur_frames = 0.; }
conditional_block
fps.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // 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 extra::time; use perf_metrics::PerfHandler; pub struct Fps { priv frames: f64, priv cur_frames: f64, priv frame_start: f64, } impl Fps { pub fn new() -> Fps { Fps { frames: 0., cur_frames: 0., frame_start: time::precise_time_s() } } } impl PerfHandler for Fps { fn reset(&mut self) -> () { self.frames = 0.; self.cur_frames = 0.; self.frame_start = time::precise_time_s(); } fn frame_begin(&mut self) -> ()
fn frame_end(&mut self) -> () { self.cur_frames += 1.; if time::precise_time_s() - self.frame_start >= 1. { self.frame_start = time::precise_time_s(); self.frames = self.cur_frames; self.cur_frames = 0.; } } fn get_value(&self) -> Option<f64> { Some(self.frames) } }
{ }
identifier_body