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 |
---|---|---|---|---|
script.rs | use std::fmt;
use std::str::FromStr;
use super::lang_mapping;
use crate::error::Error;
use crate::Lang;
#[cfg(feature = "enum-map")]
use enum_map::Enum;
/// Represents a writing system (Latin, Cyrillic, Arabic, etc).
#[cfg_attr(feature = "enum-map", derive(Enum))]
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Script {
// Keep this in alphabetic order (for C bindings)
Arabic,
Bengali,
Cyrillic,
Devanagari,
Ethiopic,
Georgian,
Greek,
Gujarati,
Gurmukhi,
Hangul,
Hebrew,
Hiragana,
Kannada,
Katakana,
Khmer,
Latin,
Malayalam,
Mandarin,
Myanmar,
Oriya,
Sinhala,
Tamil,
Telugu,
Thai,
}
// Array of all existing Script values.
const VALUES: [Script; 24] = [
Script::Arabic,
Script::Bengali,
Script::Cyrillic,
Script::Devanagari,
Script::Ethiopic,
Script::Georgian,
Script::Greek,
Script::Gujarati,
Script::Gurmukhi,
Script::Hangul,
Script::Hebrew,
Script::Hiragana,
Script::Kannada,
Script::Katakana,
Script::Khmer,
Script::Latin,
Script::Malayalam,
Script::Mandarin,
Script::Myanmar,
Script::Oriya,
Script::Sinhala,
Script::Tamil,
Script::Telugu,
Script::Thai,
];
impl Script {
/// Get all existing scripts.
///
/// # Example
/// ```
/// use whatlang::Script;
/// for script in Script::all() {
/// println!("{}", script);
/// }
/// ```
pub fn all() -> &'static [Script] {
&VALUES
}
pub fn name(&self) -> &str {
match *self {
Script::Latin => "Latin",
Script::Cyrillic => "Cyrillic",
Script::Arabic => "Arabic",
Script::Devanagari => "Devanagari",
Script::Hiragana => "Hiragana",
Script::Katakana => "Katakana",
Script::Ethiopic => "Ethiopic",
Script::Hebrew => "Hebrew",
Script::Bengali => "Bengali",
Script::Georgian => "Georgian",
Script::Mandarin => "Mandarin",
Script::Hangul => "Hangul",
Script::Greek => "Greek",
Script::Kannada => "Kannada",
Script::Tamil => "Tamil",
Script::Thai => "Thai",
Script::Gujarati => "Gujarati",
Script::Gurmukhi => "Gurmukhi",
Script::Telugu => "Telugu",
Script::Malayalam => "Malayalam",
Script::Oriya => "Oriya",
Script::Myanmar => "Myanmar",
Script::Sinhala => "Sinhala",
Script::Khmer => "Khmer",
}
}
pub fn langs(&self) -> &[Lang] {
lang_mapping::script_langs(*self)
}
}
impl fmt::Display for Script {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name())
}
}
impl FromStr for Script {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().trim() {
"latin" => Ok(Script::Latin),
"cyrillic" => Ok(Script::Cyrillic),
"arabic" => Ok(Script::Arabic),
"devanagari" => Ok(Script::Devanagari),
"hiragana" => Ok(Script::Hiragana),
"katakana" => Ok(Script::Katakana),
"ethiopic" => Ok(Script::Ethiopic),
"hebrew" => Ok(Script::Hebrew),
"bengali" => Ok(Script::Bengali),
"georgian" => Ok(Script::Georgian),
"mandarin" => Ok(Script::Mandarin),
"hangul" => Ok(Script::Hangul),
"greek" => Ok(Script::Greek),
"kannada" => Ok(Script::Kannada),
"tamil" => Ok(Script::Tamil),
"thai" => Ok(Script::Thai),
"gujarati" => Ok(Script::Gujarati),
"gurmukhi" => Ok(Script::Gurmukhi),
"telugu" => Ok(Script::Telugu),
"malayalam" => Ok(Script::Malayalam),
"oriya" => Ok(Script::Oriya),
"myanmar" => Ok(Script::Myanmar),
"sinhala" => Ok(Script::Sinhala),
"khmer" => Ok(Script::Khmer),
_ => Err(Error::ParseScript(s.to_string())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_all() {
assert_eq!(Script::all().len(), 24);
let all = Script::all();
assert!(all.contains(&Script::Cyrillic));
assert!(all.contains(&Script::Arabic));
assert!(all.contains(&Script::Latin));
}
#[test]
fn test_from_str() {
for &script in Script::all() {
let s = script.name();
assert_eq!(s.parse::<Script>().unwrap(), script);
assert_eq!(s.to_lowercase().parse::<Script>().unwrap(), script);
assert_eq!(s.to_uppercase().parse::<Script>().unwrap(), script);
}
let result = "foobar".parse::<Script>();
assert!(matches!(result, Err(Error::ParseScript(_))));
}
#[test]
fn test_langs() {
// Vec of all langs obtained with script.langs()
let script_langs: Vec<Lang> = Script::all()
.iter()
.map(|script| script.langs())
.flatten()
.copied()
.collect();
// Ensure all langs belong at least to one script
for lang in Lang::all() {
assert!(script_langs.contains(&lang));
}
}
}
| fmt | identifier_name |
script.rs | use std::fmt;
use std::str::FromStr;
use super::lang_mapping;
use crate::error::Error;
use crate::Lang;
#[cfg(feature = "enum-map")]
use enum_map::Enum;
/// Represents a writing system (Latin, Cyrillic, Arabic, etc).
#[cfg_attr(feature = "enum-map", derive(Enum))]
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Script {
// Keep this in alphabetic order (for C bindings)
Arabic,
Bengali,
Cyrillic,
Devanagari,
Ethiopic,
Georgian,
Greek,
Gujarati,
Gurmukhi,
Hangul,
Hebrew,
Hiragana,
Kannada,
Katakana,
Khmer,
Latin,
Malayalam,
Mandarin,
Myanmar,
Oriya,
Sinhala,
Tamil,
Telugu,
Thai,
}
// Array of all existing Script values.
const VALUES: [Script; 24] = [
Script::Arabic,
Script::Bengali,
Script::Cyrillic,
Script::Devanagari,
Script::Ethiopic,
Script::Georgian,
Script::Greek,
Script::Gujarati,
Script::Gurmukhi,
Script::Hangul,
Script::Hebrew,
Script::Hiragana,
Script::Kannada,
Script::Katakana,
Script::Khmer,
Script::Latin,
Script::Malayalam,
Script::Mandarin,
Script::Myanmar,
Script::Oriya,
Script::Sinhala,
Script::Tamil,
Script::Telugu,
Script::Thai,
];
impl Script {
/// Get all existing scripts.
///
/// # Example
/// ```
/// use whatlang::Script;
/// for script in Script::all() {
/// println!("{}", script);
/// }
/// ```
pub fn all() -> &'static [Script] {
&VALUES
}
pub fn name(&self) -> &str {
match *self {
Script::Latin => "Latin",
Script::Cyrillic => "Cyrillic",
Script::Arabic => "Arabic",
Script::Devanagari => "Devanagari",
Script::Hiragana => "Hiragana",
Script::Katakana => "Katakana",
Script::Ethiopic => "Ethiopic",
Script::Hebrew => "Hebrew",
Script::Bengali => "Bengali",
Script::Georgian => "Georgian",
Script::Mandarin => "Mandarin",
Script::Hangul => "Hangul",
Script::Greek => "Greek",
Script::Kannada => "Kannada",
Script::Tamil => "Tamil",
Script::Thai => "Thai",
Script::Gujarati => "Gujarati",
Script::Gurmukhi => "Gurmukhi",
Script::Telugu => "Telugu",
Script::Malayalam => "Malayalam",
Script::Oriya => "Oriya",
Script::Myanmar => "Myanmar",
Script::Sinhala => "Sinhala",
Script::Khmer => "Khmer",
}
}
pub fn langs(&self) -> &[Lang] {
lang_mapping::script_langs(*self)
}
}
impl fmt::Display for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name())
}
}
impl FromStr for Script {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().trim() {
"latin" => Ok(Script::Latin),
"cyrillic" => Ok(Script::Cyrillic),
"arabic" => Ok(Script::Arabic),
"devanagari" => Ok(Script::Devanagari),
"hiragana" => Ok(Script::Hiragana), | "mandarin" => Ok(Script::Mandarin),
"hangul" => Ok(Script::Hangul),
"greek" => Ok(Script::Greek),
"kannada" => Ok(Script::Kannada),
"tamil" => Ok(Script::Tamil),
"thai" => Ok(Script::Thai),
"gujarati" => Ok(Script::Gujarati),
"gurmukhi" => Ok(Script::Gurmukhi),
"telugu" => Ok(Script::Telugu),
"malayalam" => Ok(Script::Malayalam),
"oriya" => Ok(Script::Oriya),
"myanmar" => Ok(Script::Myanmar),
"sinhala" => Ok(Script::Sinhala),
"khmer" => Ok(Script::Khmer),
_ => Err(Error::ParseScript(s.to_string())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_all() {
assert_eq!(Script::all().len(), 24);
let all = Script::all();
assert!(all.contains(&Script::Cyrillic));
assert!(all.contains(&Script::Arabic));
assert!(all.contains(&Script::Latin));
}
#[test]
fn test_from_str() {
for &script in Script::all() {
let s = script.name();
assert_eq!(s.parse::<Script>().unwrap(), script);
assert_eq!(s.to_lowercase().parse::<Script>().unwrap(), script);
assert_eq!(s.to_uppercase().parse::<Script>().unwrap(), script);
}
let result = "foobar".parse::<Script>();
assert!(matches!(result, Err(Error::ParseScript(_))));
}
#[test]
fn test_langs() {
// Vec of all langs obtained with script.langs()
let script_langs: Vec<Lang> = Script::all()
.iter()
.map(|script| script.langs())
.flatten()
.copied()
.collect();
// Ensure all langs belong at least to one script
for lang in Lang::all() {
assert!(script_langs.contains(&lang));
}
}
} | "katakana" => Ok(Script::Katakana),
"ethiopic" => Ok(Script::Ethiopic),
"hebrew" => Ok(Script::Hebrew),
"bengali" => Ok(Script::Bengali),
"georgian" => Ok(Script::Georgian), | random_line_split |
contact_ball_ball.rs | use crate::math::{Point, Vector};
use crate::query::Contact;
use crate::shape::Ball;
use na::{self, RealField, Unit};
/// Contact between balls.
#[inline]
pub fn contact_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
prediction: N,
) -> Option<Contact<N>> {
let r1 = b1.radius;
let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
let sum_radius_with_error = sum_radius + prediction;
if distance_squared < sum_radius_with_error * sum_radius_with_error {
let normal = if!distance_squared.is_zero() {
Unit::new_normalize(delta_pos)
} else | ;
Some(Contact::new(
*center1 + *normal * r1,
*center2 + *normal * (-r2),
normal,
sum_radius - distance_squared.sqrt(),
))
} else {
None
}
}
| {
Vector::x_axis()
} | conditional_block |
contact_ball_ball.rs | use crate::math::{Point, Vector};
use crate::query::Contact;
use crate::shape::Ball;
use na::{self, RealField, Unit};
/// Contact between balls.
#[inline]
pub fn contact_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
prediction: N,
) -> Option<Contact<N>> | ))
} else {
None
}
}
| {
let r1 = b1.radius;
let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
let sum_radius_with_error = sum_radius + prediction;
if distance_squared < sum_radius_with_error * sum_radius_with_error {
let normal = if !distance_squared.is_zero() {
Unit::new_normalize(delta_pos)
} else {
Vector::x_axis()
};
Some(Contact::new(
*center1 + *normal * r1,
*center2 + *normal * (-r2),
normal,
sum_radius - distance_squared.sqrt(), | identifier_body |
contact_ball_ball.rs | use crate::math::{Point, Vector};
use crate::query::Contact;
use crate::shape::Ball;
use na::{self, RealField, Unit};
/// Contact between balls.
#[inline]
pub fn | <N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
prediction: N,
) -> Option<Contact<N>> {
let r1 = b1.radius;
let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
let sum_radius_with_error = sum_radius + prediction;
if distance_squared < sum_radius_with_error * sum_radius_with_error {
let normal = if!distance_squared.is_zero() {
Unit::new_normalize(delta_pos)
} else {
Vector::x_axis()
};
Some(Contact::new(
*center1 + *normal * r1,
*center2 + *normal * (-r2),
normal,
sum_radius - distance_squared.sqrt(),
))
} else {
None
}
}
| contact_ball_ball | identifier_name |
contact_ball_ball.rs | use crate::math::{Point, Vector};
use crate::query::Contact;
use crate::shape::Ball;
use na::{self, RealField, Unit};
/// Contact between balls.
#[inline]
pub fn contact_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
prediction: N,
) -> Option<Contact<N>> { | let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
let sum_radius_with_error = sum_radius + prediction;
if distance_squared < sum_radius_with_error * sum_radius_with_error {
let normal = if!distance_squared.is_zero() {
Unit::new_normalize(delta_pos)
} else {
Vector::x_axis()
};
Some(Contact::new(
*center1 + *normal * r1,
*center2 + *normal * (-r2),
normal,
sum_radius - distance_squared.sqrt(),
))
} else {
None
}
} | let r1 = b1.radius; | random_line_split |
tests.rs | extern crate rustsocks;
use rustsocks::{Socks4, Socks4a, Socks5};
use std::io::net::ip::IpAddr;
static SOCKS_HOST : &'static str = "127.0.0.1";
static SOCKS_PORT : u16 = 9150;
static GET_REQUEST : &'static str =
"GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n";
#[test]
fn socks4a() {
let mut socks = Socks4a::new(SOCKS_HOST, SOCKS_PORT);
let mut stream = socks.connect("www.google.com", 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks4() {
let mut socks = Socks4::new(SOCKS_HOST, SOCKS_PORT);
let addr = from_str::<IpAddr>("74.125.230.65").unwrap();
let mut stream = socks.connect(addr, 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks5_domain() {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let mut stream = socks.connect("www.google.com", 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks5_ipv4() | {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let addr = from_str::<IpAddr>("74.125.230.65").unwrap();
let mut stream = socks.connect(addr, 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
} | identifier_body |
|
tests.rs | extern crate rustsocks;
use rustsocks::{Socks4, Socks4a, Socks5};
use std::io::net::ip::IpAddr;
static SOCKS_HOST : &'static str = "127.0.0.1";
static SOCKS_PORT : u16 = 9150;
static GET_REQUEST : &'static str =
"GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n";
#[test]
fn socks4a() {
let mut socks = Socks4a::new(SOCKS_HOST, SOCKS_PORT);
let mut stream = socks.connect("www.google.com", 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks4() {
let mut socks = Socks4::new(SOCKS_HOST, SOCKS_PORT);
let addr = from_str::<IpAddr>("74.125.230.65").unwrap();
let mut stream = socks.connect(addr, 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn | () {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let mut stream = socks.connect("www.google.com", 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks5_ipv4() {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let addr = from_str::<IpAddr>("74.125.230.65").unwrap();
let mut stream = socks.connect(addr, 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
| socks5_domain | identifier_name |
tests.rs | extern crate rustsocks;
use rustsocks::{Socks4, Socks4a, Socks5};
use std::io::net::ip::IpAddr;
static SOCKS_HOST : &'static str = "127.0.0.1";
static SOCKS_PORT : u16 = 9150;
static GET_REQUEST : &'static str =
"GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n";
#[test]
fn socks4a() {
let mut socks = Socks4a::new(SOCKS_HOST, SOCKS_PORT);
let mut stream = socks.connect("www.google.com", 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks4() {
let mut socks = Socks4::new(SOCKS_HOST, SOCKS_PORT);
let addr = from_str::<IpAddr>("74.125.230.65").unwrap();
let mut stream = socks.connect(addr, 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks5_domain() {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let mut stream = socks.connect("www.google.com", 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks5_ipv4() {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let addr = from_str::<IpAddr>("74.125.230.65").unwrap();
let mut stream = socks.connect(addr, 80); | println!("{}", stream.read_to_string().unwrap());
} |
let _ = stream.write_str(GET_REQUEST); | random_line_split |
main.rs | use {
futures::{
future::{BoxFuture, FutureExt},
task::{waker_ref, ArcWake},
},
std::{
future::Future,
sync::mpsc::{sync_channel, Receiver, SyncSender},
sync::{Arc, Mutex},
task::{Context, Poll},
time::Duration,
},
};
struct Task {
future: Mutex<Option<BoxFuture<'static, ()>>>,
task_sender: SyncSender<Arc<Task>>,
}
impl ArcWake for Task {
fn wake_by_ref(arc_self: &Arc<Self>) {
println!("wake_by_ref.1");
let cloned = arc_self.clone();
println!("wake_by_ref.2");
arc_self
.task_sender
.send(cloned)
.expect("too many tasks queued");
println!("wake_by_ref.3");
}
}
struct Sender(SyncSender<BoxFuture<'static, ()>>);
struct Executor {
task_sender: Arc<Sender>,
ready_queue: Receiver<BoxFuture<'static, ()>>,
}
impl ArcWake for Sender {
fn wake_by_ref(arc_self: &Arc<Self>) {
arc_self.
}
}
impl Executor {
fn run(&self) {
while let Ok(mut f) = self.ready_queue.recv() {
let c = self.task_sender.clone();
let waker = waker_ref(&c);
let ctx = &mut Context::from_waker(&*waker);
let t = f.as_mut();
t.poll(ctx);
// let mut future_slot = task.future.lock().unwrap();
// if let Some(mut future) = future_slot.take() {
// let waker = waker_ref(&task);
// let context = &mut Context::from_waker(&*waker);
// if let Poll::Pending = future.as_mut().poll(context) {
// *future_slot = Some(future);
// }
// }
}
}
fn spawn(&self, future: impl Future<Output = ()> +'static + Send) {
let future = future.boxed();
self.task_sender
.0
.send(future)
.expect("too many tasks queued");
}
}
fn new_executor_and_spawner() -> Executor {
const MAX_QUEUED_TASKS: usize = 10_000;
let (task_sender, ready_queue) = sync_channel(MAX_QUEUED_TASKS);
Executor {
task_sender: Arc::new(Sender(task_sender)),
ready_queue,
}
}
struct FutureReceiver<T>(Arc<Mutex<std::sync::mpsc::Receiver<T>>>, Option<T>);
impl<T:'static + Send + Sync> Future for FutureReceiver<T> {
type Output = T;
fn poll(
self: std::pin::Pin<&mut Self>,
ctx: &mut std::task::Context<'_>,
) -> std::task::Poll<T> {
println!("FutureReceiver.poll.1");
let ch = self.0.lock().unwrap();
let mut iter = ch.try_iter();
match iter.next() {
Some(v) => std::task::Poll::Ready(v),
None => {
let waker = ctx.waker().clone();
let channel = self.0.clone();
std::thread::spawn(move || {
let item = channel.lock().unwrap().recv();
println!("received!");
waker.wake();
});
std::task::Poll::Pending
}
}
}
}
fn main() | }
| {
let (sender, receiver) = std::sync::mpsc::channel::<i32>();
let s1 = sender.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(1000));
println!("sent!");
s1.send(1).unwrap();
});
let receiver = FutureReceiver(Arc::from(Mutex::from(receiver)), None);
//sender.send(1).unwrap();
let f = async move {
println!("howdy!");
receiver.await;
println!("done!");
};
let exec = new_executor_and_spawner();
exec.spawn(f);
exec.run(); | identifier_body |
main.rs | use {
futures::{
future::{BoxFuture, FutureExt},
task::{waker_ref, ArcWake},
},
std::{
future::Future,
sync::mpsc::{sync_channel, Receiver, SyncSender},
sync::{Arc, Mutex},
task::{Context, Poll},
time::Duration,
},
};
struct Task {
future: Mutex<Option<BoxFuture<'static, ()>>>,
task_sender: SyncSender<Arc<Task>>,
}
impl ArcWake for Task {
fn wake_by_ref(arc_self: &Arc<Self>) {
println!("wake_by_ref.1");
let cloned = arc_self.clone();
println!("wake_by_ref.2");
arc_self
.task_sender
.send(cloned)
.expect("too many tasks queued");
println!("wake_by_ref.3");
}
}
struct Sender(SyncSender<BoxFuture<'static, ()>>);
struct Executor {
task_sender: Arc<Sender>,
ready_queue: Receiver<BoxFuture<'static, ()>>,
}
impl ArcWake for Sender {
fn wake_by_ref(arc_self: &Arc<Self>) {
arc_self.
}
}
impl Executor {
fn run(&self) {
while let Ok(mut f) = self.ready_queue.recv() {
let c = self.task_sender.clone();
let waker = waker_ref(&c);
let ctx = &mut Context::from_waker(&*waker);
let t = f.as_mut();
t.poll(ctx);
// let mut future_slot = task.future.lock().unwrap();
// if let Some(mut future) = future_slot.take() {
// let waker = waker_ref(&task);
// let context = &mut Context::from_waker(&*waker);
// if let Poll::Pending = future.as_mut().poll(context) {
// *future_slot = Some(future);
// }
// }
}
}
fn spawn(&self, future: impl Future<Output = ()> +'static + Send) {
let future = future.boxed();
self.task_sender
.0
.send(future)
.expect("too many tasks queued");
}
}
fn new_executor_and_spawner() -> Executor {
const MAX_QUEUED_TASKS: usize = 10_000;
let (task_sender, ready_queue) = sync_channel(MAX_QUEUED_TASKS);
Executor {
task_sender: Arc::new(Sender(task_sender)),
ready_queue,
}
}
struct FutureReceiver<T>(Arc<Mutex<std::sync::mpsc::Receiver<T>>>, Option<T>);
impl<T:'static + Send + Sync> Future for FutureReceiver<T> {
type Output = T;
fn | (
self: std::pin::Pin<&mut Self>,
ctx: &mut std::task::Context<'_>,
) -> std::task::Poll<T> {
println!("FutureReceiver.poll.1");
let ch = self.0.lock().unwrap();
let mut iter = ch.try_iter();
match iter.next() {
Some(v) => std::task::Poll::Ready(v),
None => {
let waker = ctx.waker().clone();
let channel = self.0.clone();
std::thread::spawn(move || {
let item = channel.lock().unwrap().recv();
println!("received!");
waker.wake();
});
std::task::Poll::Pending
}
}
}
}
fn main() {
let (sender, receiver) = std::sync::mpsc::channel::<i32>();
let s1 = sender.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(1000));
println!("sent!");
s1.send(1).unwrap();
});
let receiver = FutureReceiver(Arc::from(Mutex::from(receiver)), None);
//sender.send(1).unwrap();
let f = async move {
println!("howdy!");
receiver.await;
println!("done!");
};
let exec = new_executor_and_spawner();
exec.spawn(f);
exec.run();
}
| poll | identifier_name |
main.rs | use {
futures::{
future::{BoxFuture, FutureExt},
task::{waker_ref, ArcWake},
},
std::{
future::Future,
sync::mpsc::{sync_channel, Receiver, SyncSender},
sync::{Arc, Mutex},
task::{Context, Poll},
time::Duration,
},
};
struct Task {
future: Mutex<Option<BoxFuture<'static, ()>>>,
task_sender: SyncSender<Arc<Task>>,
}
impl ArcWake for Task {
fn wake_by_ref(arc_self: &Arc<Self>) {
println!("wake_by_ref.1");
let cloned = arc_self.clone();
println!("wake_by_ref.2");
arc_self
.task_sender
.send(cloned)
.expect("too many tasks queued");
println!("wake_by_ref.3");
}
}
struct Sender(SyncSender<BoxFuture<'static, ()>>);
struct Executor {
task_sender: Arc<Sender>,
ready_queue: Receiver<BoxFuture<'static, ()>>,
}
impl ArcWake for Sender {
fn wake_by_ref(arc_self: &Arc<Self>) {
arc_self.
}
}
impl Executor {
fn run(&self) {
while let Ok(mut f) = self.ready_queue.recv() {
let c = self.task_sender.clone();
let waker = waker_ref(&c);
let ctx = &mut Context::from_waker(&*waker);
let t = f.as_mut();
t.poll(ctx);
// let mut future_slot = task.future.lock().unwrap();
// if let Some(mut future) = future_slot.take() {
// let waker = waker_ref(&task);
// let context = &mut Context::from_waker(&*waker);
// if let Poll::Pending = future.as_mut().poll(context) {
// *future_slot = Some(future);
// }
// }
}
}
fn spawn(&self, future: impl Future<Output = ()> +'static + Send) {
let future = future.boxed();
self.task_sender
.0
.send(future)
.expect("too many tasks queued");
}
}
fn new_executor_and_spawner() -> Executor {
const MAX_QUEUED_TASKS: usize = 10_000;
let (task_sender, ready_queue) = sync_channel(MAX_QUEUED_TASKS);
Executor {
task_sender: Arc::new(Sender(task_sender)),
ready_queue,
}
}
struct FutureReceiver<T>(Arc<Mutex<std::sync::mpsc::Receiver<T>>>, Option<T>);
impl<T:'static + Send + Sync> Future for FutureReceiver<T> {
type Output = T;
fn poll(
self: std::pin::Pin<&mut Self>,
ctx: &mut std::task::Context<'_>,
) -> std::task::Poll<T> {
println!("FutureReceiver.poll.1");
let ch = self.0.lock().unwrap();
let mut iter = ch.try_iter();
match iter.next() {
Some(v) => std::task::Poll::Ready(v),
None => {
let waker = ctx.waker().clone();
let channel = self.0.clone();
std::thread::spawn(move || {
let item = channel.lock().unwrap().recv();
println!("received!");
waker.wake();
});
std::task::Poll::Pending
}
}
}
}
fn main() {
let (sender, receiver) = std::sync::mpsc::channel::<i32>();
let s1 = sender.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(1000));
println!("sent!");
s1.send(1).unwrap();
});
let receiver = FutureReceiver(Arc::from(Mutex::from(receiver)), None);
//sender.send(1).unwrap();
let f = async move {
println!("howdy!"); | };
let exec = new_executor_and_spawner();
exec.spawn(f);
exec.run();
} | receiver.await;
println!("done!"); | random_line_split |
cg.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStreamExt;
use syn::{self, AngleBracketedGenericArguments, Binding, DeriveInput, Field};
use syn::{GenericArgument, GenericParam, Ident, Path};
use syn::{PathArguments, PathSegment, QSelf, Type, TypeArray};
use syn::{TypeParam, TypeParen, TypePath, TypeSlice, TypeTuple};
use syn::{Variant, WherePredicate};
use synstructure::{self, BindStyle, BindingInfo, VariantAst, VariantInfo};
/// Given an input type which has some where clauses already, like:
///
/// struct InputType<T>
/// where
/// T: Zero,
/// {
/// ...
/// }
///
/// Add the necessary `where` clauses so that the output type of a trait
/// fulfils them.
///
/// For example:
///
/// <T as ToComputedValue>::ComputedValue: Zero,
///
/// This needs to run before adding other bounds to the type parameters.
pub fn propagate_clauses_to_output_type(
where_clause: &mut Option<syn::WhereClause>,
generics: &syn::Generics,
trait_path: Path,
trait_output: Ident,
) {
let where_clause = match *where_clause {
Some(ref mut clause) => clause,
None => return,
};
let mut extra_bounds = vec![];
for pred in &where_clause.predicates {
let ty = match *pred {
syn::WherePredicate::Type(ref ty) => ty,
ref predicate => panic!("Unhanded complex where predicate: {:?}", predicate),
};
let path = match ty.bounded_ty {
syn::Type::Path(ref p) => &p.path,
ref ty => panic!("Unhanded complex where type: {:?}", ty),
};
assert!(
ty.lifetimes.is_none(),
"Unhanded complex lifetime bound: {:?}",
ty,
);
let ident = match path_to_ident(path) {
Some(i) => i,
None => panic!("Unhanded complex where type path: {:?}", path),
};
if generics.type_params().any(|param| param.ident == *ident) {
extra_bounds.push(ty.clone());
}
}
for bound in extra_bounds {
let ty = bound.bounded_ty;
let bounds = bound.bounds;
where_clause
.predicates
.push(parse_quote!(<#ty as #trait_path>::#trait_output: #bounds))
}
}
pub fn add_predicate(where_clause: &mut Option<syn::WhereClause>, pred: WherePredicate) {
where_clause
.get_or_insert(parse_quote!(where))
.predicates
.push(pred);
}
pub fn fmap_match<F>(input: &DeriveInput, bind_style: BindStyle, mut f: F) -> TokenStream
where
F: FnMut(BindingInfo) -> TokenStream,
{
let mut s = synstructure::Structure::new(input);
s.variants_mut().iter_mut().for_each(|v| {
v.bind_with(|_| bind_style);
});
s.each_variant(|variant| {
let (mapped, mapped_fields) = value(variant, "mapped");
let fields_pairs = variant.bindings().iter().zip(mapped_fields);
let mut computations = quote!();
computations.append_all(fields_pairs.map(|(field, mapped_field)| {
let expr = f(field.clone());
quote! { let #mapped_field = #expr; }
}));
computations.append_all(mapped);
Some(computations)
})
}
pub fn fmap_trait_output(input: &DeriveInput, trait_path: &Path, trait_output: Ident) -> Path {
let segment = PathSegment {
ident: input.ident.clone(),
arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: input
.generics
.params
.iter()
.map(|arg| match arg {
&GenericParam::Lifetime(ref data) => {
GenericArgument::Lifetime(data.lifetime.clone())
},
&GenericParam::Type(ref data) => {
let ident = &data.ident;
GenericArgument::Type(parse_quote!(<#ident as #trait_path>::#trait_output))
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
colon2_token: Default::default(),
gt_token: Default::default(),
lt_token: Default::default(),
}),
};
segment.into()
}
pub fn | <F>(ty: &Type, params: &[&TypeParam], f: &mut F) -> Type
where
F: FnMut(&Ident) -> Type,
{
match *ty {
Type::Slice(ref inner) => Type::from(TypeSlice {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
Type::Array(ref inner) => {
//ref ty, ref expr) => {
Type::from(TypeArray {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
})
},
ref ty @ Type::Never(_) => ty.clone(),
Type::Tuple(ref inner) => Type::from(TypeTuple {
elems: inner
.elems
.iter()
.map(|ty| map_type_params(&ty, params, f))
.collect(),
..inner.clone()
}),
Type::Path(TypePath {
qself: None,
ref path,
}) => {
if let Some(ident) = path_to_ident(path) {
if params.iter().any(|ref param| ¶m.ident == ident) {
return f(ident);
}
}
Type::from(TypePath {
qself: None,
path: map_type_params_in_path(path, params, f),
})
},
Type::Path(TypePath {
ref qself,
ref path,
}) => Type::from(TypePath {
qself: qself.as_ref().map(|qself| QSelf {
ty: Box::new(map_type_params(&qself.ty, params, f)),
position: qself.position,
..qself.clone()
}),
path: map_type_params_in_path(path, params, f),
}),
Type::Paren(ref inner) => Type::from(TypeParen {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
ref ty => panic!("type {:?} cannot be mapped yet", ty),
}
}
fn map_type_params_in_path<F>(path: &Path, params: &[&TypeParam], f: &mut F) -> Path
where
F: FnMut(&Ident) -> Type,
{
Path {
leading_colon: path.leading_colon,
segments: path
.segments
.iter()
.map(|segment| PathSegment {
ident: segment.ident.clone(),
arguments: match segment.arguments {
PathArguments::AngleBracketed(ref data) => {
PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: data
.args
.iter()
.map(|arg| match arg {
ty @ &GenericArgument::Lifetime(_) => ty.clone(),
&GenericArgument::Type(ref data) => {
GenericArgument::Type(map_type_params(data, params, f))
},
&GenericArgument::Binding(ref data) => {
GenericArgument::Binding(Binding {
ty: map_type_params(&data.ty, params, f),
..data.clone()
})
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
..data.clone()
})
},
ref arg @ PathArguments::None => arg.clone(),
ref parameters => panic!("parameters {:?} cannot be mapped yet", parameters),
},
})
.collect(),
}
}
fn path_to_ident(path: &Path) -> Option<&Ident> {
match *path {
Path {
leading_colon: None,
ref segments,
} if segments.len() == 1 => {
if segments[0].arguments.is_empty() {
Some(&segments[0].ident)
} else {
None
}
},
_ => None,
}
}
pub fn parse_field_attrs<A>(field: &Field) -> A
where
A: FromField,
{
match A::from_field(field) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse field attributes: {}", e),
}
}
pub fn parse_input_attrs<A>(input: &DeriveInput) -> A
where
A: FromDeriveInput,
{
match A::from_derive_input(input) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse input attributes: {}", e),
}
}
pub fn parse_variant_attrs_from_ast<A>(variant: &VariantAst) -> A
where
A: FromVariant,
{
let v = Variant {
ident: variant.ident.clone(),
attrs: variant.attrs.to_vec(),
fields: variant.fields.clone(),
discriminant: variant.discriminant.clone(),
};
parse_variant_attrs(&v)
}
pub fn parse_variant_attrs<A>(variant: &Variant) -> A
where
A: FromVariant,
{
match A::from_variant(variant) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse variant attributes: {}", e),
}
}
pub fn ref_pattern<'a>(
variant: &'a VariantInfo,
prefix: &str,
) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bind_with(|_| BindStyle::Ref);
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
(v.pat(), v.bindings().to_vec())
}
pub fn value<'a>(variant: &'a VariantInfo, prefix: &str) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
v.bind_with(|_| BindStyle::Move);
(v.pat(), v.bindings().to_vec())
}
/// Transforms "FooBar" to "foo-bar".
///
/// If the first Camel segment is "Moz", "Webkit", or "Servo", the result string
/// is prepended with "-".
pub fn to_css_identifier(mut camel_case: &str) -> String {
camel_case = camel_case.trim_end_matches('_');
let mut first = true;
let mut result = String::with_capacity(camel_case.len());
while let Some(segment) = split_camel_segment(&mut camel_case) {
if first {
match segment {
"Moz" | "Webkit" | "Servo" => first = false,
_ => {},
}
}
if!first {
result.push_str("-");
}
first = false;
result.push_str(&segment.to_lowercase());
}
result
}
/// Given "FooBar", returns "Foo" and sets `camel_case` to "Bar".
fn split_camel_segment<'input>(camel_case: &mut &'input str) -> Option<&'input str> {
let index = match camel_case.chars().next() {
None => return None,
Some(ch) => ch.len_utf8(),
};
let end_position = camel_case[index..]
.find(char::is_uppercase)
.map_or(camel_case.len(), |pos| index + pos);
let result = &camel_case[..end_position];
*camel_case = &camel_case[end_position..];
Some(result)
}
| map_type_params | identifier_name |
cg.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStreamExt;
use syn::{self, AngleBracketedGenericArguments, Binding, DeriveInput, Field};
use syn::{GenericArgument, GenericParam, Ident, Path};
use syn::{PathArguments, PathSegment, QSelf, Type, TypeArray};
use syn::{TypeParam, TypeParen, TypePath, TypeSlice, TypeTuple};
use syn::{Variant, WherePredicate};
use synstructure::{self, BindStyle, BindingInfo, VariantAst, VariantInfo};
/// Given an input type which has some where clauses already, like:
///
/// struct InputType<T>
/// where
/// T: Zero,
/// {
/// ...
/// }
///
/// Add the necessary `where` clauses so that the output type of a trait
/// fulfils them.
///
/// For example:
///
/// <T as ToComputedValue>::ComputedValue: Zero,
///
/// This needs to run before adding other bounds to the type parameters.
pub fn propagate_clauses_to_output_type(
where_clause: &mut Option<syn::WhereClause>,
generics: &syn::Generics,
trait_path: Path,
trait_output: Ident,
) {
let where_clause = match *where_clause {
Some(ref mut clause) => clause,
None => return,
};
let mut extra_bounds = vec![];
for pred in &where_clause.predicates {
let ty = match *pred {
syn::WherePredicate::Type(ref ty) => ty,
ref predicate => panic!("Unhanded complex where predicate: {:?}", predicate),
};
let path = match ty.bounded_ty {
syn::Type::Path(ref p) => &p.path,
ref ty => panic!("Unhanded complex where type: {:?}", ty),
};
assert!(
ty.lifetimes.is_none(),
"Unhanded complex lifetime bound: {:?}",
ty,
);
let ident = match path_to_ident(path) {
Some(i) => i,
None => panic!("Unhanded complex where type path: {:?}", path),
};
if generics.type_params().any(|param| param.ident == *ident) {
extra_bounds.push(ty.clone());
}
}
for bound in extra_bounds {
let ty = bound.bounded_ty;
let bounds = bound.bounds;
where_clause
.predicates
.push(parse_quote!(<#ty as #trait_path>::#trait_output: #bounds))
}
}
pub fn add_predicate(where_clause: &mut Option<syn::WhereClause>, pred: WherePredicate) {
where_clause
.get_or_insert(parse_quote!(where))
.predicates
.push(pred);
}
pub fn fmap_match<F>(input: &DeriveInput, bind_style: BindStyle, mut f: F) -> TokenStream
where
F: FnMut(BindingInfo) -> TokenStream,
{
let mut s = synstructure::Structure::new(input);
s.variants_mut().iter_mut().for_each(|v| {
v.bind_with(|_| bind_style);
});
s.each_variant(|variant| {
let (mapped, mapped_fields) = value(variant, "mapped");
let fields_pairs = variant.bindings().iter().zip(mapped_fields);
let mut computations = quote!();
computations.append_all(fields_pairs.map(|(field, mapped_field)| {
let expr = f(field.clone());
quote! { let #mapped_field = #expr; }
}));
computations.append_all(mapped);
Some(computations)
})
}
pub fn fmap_trait_output(input: &DeriveInput, trait_path: &Path, trait_output: Ident) -> Path {
let segment = PathSegment {
ident: input.ident.clone(),
arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: input
.generics
.params
.iter()
.map(|arg| match arg {
&GenericParam::Lifetime(ref data) => {
GenericArgument::Lifetime(data.lifetime.clone())
},
&GenericParam::Type(ref data) => {
let ident = &data.ident;
GenericArgument::Type(parse_quote!(<#ident as #trait_path>::#trait_output))
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
colon2_token: Default::default(),
gt_token: Default::default(),
lt_token: Default::default(),
}),
};
segment.into()
}
pub fn map_type_params<F>(ty: &Type, params: &[&TypeParam], f: &mut F) -> Type
where
F: FnMut(&Ident) -> Type,
{
match *ty {
Type::Slice(ref inner) => Type::from(TypeSlice {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
Type::Array(ref inner) => {
//ref ty, ref expr) => {
Type::from(TypeArray {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
})
},
ref ty @ Type::Never(_) => ty.clone(),
Type::Tuple(ref inner) => Type::from(TypeTuple {
elems: inner
.elems
.iter()
.map(|ty| map_type_params(&ty, params, f))
.collect(),
..inner.clone()
}),
Type::Path(TypePath {
qself: None,
ref path,
}) => {
if let Some(ident) = path_to_ident(path) {
if params.iter().any(|ref param| ¶m.ident == ident) |
}
Type::from(TypePath {
qself: None,
path: map_type_params_in_path(path, params, f),
})
},
Type::Path(TypePath {
ref qself,
ref path,
}) => Type::from(TypePath {
qself: qself.as_ref().map(|qself| QSelf {
ty: Box::new(map_type_params(&qself.ty, params, f)),
position: qself.position,
..qself.clone()
}),
path: map_type_params_in_path(path, params, f),
}),
Type::Paren(ref inner) => Type::from(TypeParen {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
ref ty => panic!("type {:?} cannot be mapped yet", ty),
}
}
fn map_type_params_in_path<F>(path: &Path, params: &[&TypeParam], f: &mut F) -> Path
where
F: FnMut(&Ident) -> Type,
{
Path {
leading_colon: path.leading_colon,
segments: path
.segments
.iter()
.map(|segment| PathSegment {
ident: segment.ident.clone(),
arguments: match segment.arguments {
PathArguments::AngleBracketed(ref data) => {
PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: data
.args
.iter()
.map(|arg| match arg {
ty @ &GenericArgument::Lifetime(_) => ty.clone(),
&GenericArgument::Type(ref data) => {
GenericArgument::Type(map_type_params(data, params, f))
},
&GenericArgument::Binding(ref data) => {
GenericArgument::Binding(Binding {
ty: map_type_params(&data.ty, params, f),
..data.clone()
})
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
..data.clone()
})
},
ref arg @ PathArguments::None => arg.clone(),
ref parameters => panic!("parameters {:?} cannot be mapped yet", parameters),
},
})
.collect(),
}
}
fn path_to_ident(path: &Path) -> Option<&Ident> {
match *path {
Path {
leading_colon: None,
ref segments,
} if segments.len() == 1 => {
if segments[0].arguments.is_empty() {
Some(&segments[0].ident)
} else {
None
}
},
_ => None,
}
}
pub fn parse_field_attrs<A>(field: &Field) -> A
where
A: FromField,
{
match A::from_field(field) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse field attributes: {}", e),
}
}
pub fn parse_input_attrs<A>(input: &DeriveInput) -> A
where
A: FromDeriveInput,
{
match A::from_derive_input(input) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse input attributes: {}", e),
}
}
pub fn parse_variant_attrs_from_ast<A>(variant: &VariantAst) -> A
where
A: FromVariant,
{
let v = Variant {
ident: variant.ident.clone(),
attrs: variant.attrs.to_vec(),
fields: variant.fields.clone(),
discriminant: variant.discriminant.clone(),
};
parse_variant_attrs(&v)
}
pub fn parse_variant_attrs<A>(variant: &Variant) -> A
where
A: FromVariant,
{
match A::from_variant(variant) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse variant attributes: {}", e),
}
}
pub fn ref_pattern<'a>(
variant: &'a VariantInfo,
prefix: &str,
) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bind_with(|_| BindStyle::Ref);
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
(v.pat(), v.bindings().to_vec())
}
pub fn value<'a>(variant: &'a VariantInfo, prefix: &str) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
v.bind_with(|_| BindStyle::Move);
(v.pat(), v.bindings().to_vec())
}
/// Transforms "FooBar" to "foo-bar".
///
/// If the first Camel segment is "Moz", "Webkit", or "Servo", the result string
/// is prepended with "-".
pub fn to_css_identifier(mut camel_case: &str) -> String {
camel_case = camel_case.trim_end_matches('_');
let mut first = true;
let mut result = String::with_capacity(camel_case.len());
while let Some(segment) = split_camel_segment(&mut camel_case) {
if first {
match segment {
"Moz" | "Webkit" | "Servo" => first = false,
_ => {},
}
}
if!first {
result.push_str("-");
}
first = false;
result.push_str(&segment.to_lowercase());
}
result
}
/// Given "FooBar", returns "Foo" and sets `camel_case` to "Bar".
fn split_camel_segment<'input>(camel_case: &mut &'input str) -> Option<&'input str> {
let index = match camel_case.chars().next() {
None => return None,
Some(ch) => ch.len_utf8(),
};
let end_position = camel_case[index..]
.find(char::is_uppercase)
.map_or(camel_case.len(), |pos| index + pos);
let result = &camel_case[..end_position];
*camel_case = &camel_case[end_position..];
Some(result)
}
| {
return f(ident);
} | conditional_block |
cg.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStreamExt;
use syn::{self, AngleBracketedGenericArguments, Binding, DeriveInput, Field};
use syn::{GenericArgument, GenericParam, Ident, Path};
use syn::{PathArguments, PathSegment, QSelf, Type, TypeArray};
use syn::{TypeParam, TypeParen, TypePath, TypeSlice, TypeTuple};
use syn::{Variant, WherePredicate};
use synstructure::{self, BindStyle, BindingInfo, VariantAst, VariantInfo};
/// Given an input type which has some where clauses already, like:
///
/// struct InputType<T>
/// where
/// T: Zero,
/// {
/// ...
/// }
///
/// Add the necessary `where` clauses so that the output type of a trait
/// fulfils them.
///
/// For example:
///
/// <T as ToComputedValue>::ComputedValue: Zero,
///
/// This needs to run before adding other bounds to the type parameters.
pub fn propagate_clauses_to_output_type(
where_clause: &mut Option<syn::WhereClause>,
generics: &syn::Generics,
trait_path: Path,
trait_output: Ident,
) {
let where_clause = match *where_clause {
Some(ref mut clause) => clause,
None => return,
};
let mut extra_bounds = vec![];
for pred in &where_clause.predicates {
let ty = match *pred {
syn::WherePredicate::Type(ref ty) => ty,
ref predicate => panic!("Unhanded complex where predicate: {:?}", predicate),
};
let path = match ty.bounded_ty {
syn::Type::Path(ref p) => &p.path,
ref ty => panic!("Unhanded complex where type: {:?}", ty),
};
| ty,
);
let ident = match path_to_ident(path) {
Some(i) => i,
None => panic!("Unhanded complex where type path: {:?}", path),
};
if generics.type_params().any(|param| param.ident == *ident) {
extra_bounds.push(ty.clone());
}
}
for bound in extra_bounds {
let ty = bound.bounded_ty;
let bounds = bound.bounds;
where_clause
.predicates
.push(parse_quote!(<#ty as #trait_path>::#trait_output: #bounds))
}
}
pub fn add_predicate(where_clause: &mut Option<syn::WhereClause>, pred: WherePredicate) {
where_clause
.get_or_insert(parse_quote!(where))
.predicates
.push(pred);
}
pub fn fmap_match<F>(input: &DeriveInput, bind_style: BindStyle, mut f: F) -> TokenStream
where
F: FnMut(BindingInfo) -> TokenStream,
{
let mut s = synstructure::Structure::new(input);
s.variants_mut().iter_mut().for_each(|v| {
v.bind_with(|_| bind_style);
});
s.each_variant(|variant| {
let (mapped, mapped_fields) = value(variant, "mapped");
let fields_pairs = variant.bindings().iter().zip(mapped_fields);
let mut computations = quote!();
computations.append_all(fields_pairs.map(|(field, mapped_field)| {
let expr = f(field.clone());
quote! { let #mapped_field = #expr; }
}));
computations.append_all(mapped);
Some(computations)
})
}
pub fn fmap_trait_output(input: &DeriveInput, trait_path: &Path, trait_output: Ident) -> Path {
let segment = PathSegment {
ident: input.ident.clone(),
arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: input
.generics
.params
.iter()
.map(|arg| match arg {
&GenericParam::Lifetime(ref data) => {
GenericArgument::Lifetime(data.lifetime.clone())
},
&GenericParam::Type(ref data) => {
let ident = &data.ident;
GenericArgument::Type(parse_quote!(<#ident as #trait_path>::#trait_output))
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
colon2_token: Default::default(),
gt_token: Default::default(),
lt_token: Default::default(),
}),
};
segment.into()
}
pub fn map_type_params<F>(ty: &Type, params: &[&TypeParam], f: &mut F) -> Type
where
F: FnMut(&Ident) -> Type,
{
match *ty {
Type::Slice(ref inner) => Type::from(TypeSlice {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
Type::Array(ref inner) => {
//ref ty, ref expr) => {
Type::from(TypeArray {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
})
},
ref ty @ Type::Never(_) => ty.clone(),
Type::Tuple(ref inner) => Type::from(TypeTuple {
elems: inner
.elems
.iter()
.map(|ty| map_type_params(&ty, params, f))
.collect(),
..inner.clone()
}),
Type::Path(TypePath {
qself: None,
ref path,
}) => {
if let Some(ident) = path_to_ident(path) {
if params.iter().any(|ref param| ¶m.ident == ident) {
return f(ident);
}
}
Type::from(TypePath {
qself: None,
path: map_type_params_in_path(path, params, f),
})
},
Type::Path(TypePath {
ref qself,
ref path,
}) => Type::from(TypePath {
qself: qself.as_ref().map(|qself| QSelf {
ty: Box::new(map_type_params(&qself.ty, params, f)),
position: qself.position,
..qself.clone()
}),
path: map_type_params_in_path(path, params, f),
}),
Type::Paren(ref inner) => Type::from(TypeParen {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
ref ty => panic!("type {:?} cannot be mapped yet", ty),
}
}
fn map_type_params_in_path<F>(path: &Path, params: &[&TypeParam], f: &mut F) -> Path
where
F: FnMut(&Ident) -> Type,
{
Path {
leading_colon: path.leading_colon,
segments: path
.segments
.iter()
.map(|segment| PathSegment {
ident: segment.ident.clone(),
arguments: match segment.arguments {
PathArguments::AngleBracketed(ref data) => {
PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: data
.args
.iter()
.map(|arg| match arg {
ty @ &GenericArgument::Lifetime(_) => ty.clone(),
&GenericArgument::Type(ref data) => {
GenericArgument::Type(map_type_params(data, params, f))
},
&GenericArgument::Binding(ref data) => {
GenericArgument::Binding(Binding {
ty: map_type_params(&data.ty, params, f),
..data.clone()
})
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
..data.clone()
})
},
ref arg @ PathArguments::None => arg.clone(),
ref parameters => panic!("parameters {:?} cannot be mapped yet", parameters),
},
})
.collect(),
}
}
fn path_to_ident(path: &Path) -> Option<&Ident> {
match *path {
Path {
leading_colon: None,
ref segments,
} if segments.len() == 1 => {
if segments[0].arguments.is_empty() {
Some(&segments[0].ident)
} else {
None
}
},
_ => None,
}
}
pub fn parse_field_attrs<A>(field: &Field) -> A
where
A: FromField,
{
match A::from_field(field) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse field attributes: {}", e),
}
}
pub fn parse_input_attrs<A>(input: &DeriveInput) -> A
where
A: FromDeriveInput,
{
match A::from_derive_input(input) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse input attributes: {}", e),
}
}
pub fn parse_variant_attrs_from_ast<A>(variant: &VariantAst) -> A
where
A: FromVariant,
{
let v = Variant {
ident: variant.ident.clone(),
attrs: variant.attrs.to_vec(),
fields: variant.fields.clone(),
discriminant: variant.discriminant.clone(),
};
parse_variant_attrs(&v)
}
pub fn parse_variant_attrs<A>(variant: &Variant) -> A
where
A: FromVariant,
{
match A::from_variant(variant) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse variant attributes: {}", e),
}
}
pub fn ref_pattern<'a>(
variant: &'a VariantInfo,
prefix: &str,
) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bind_with(|_| BindStyle::Ref);
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
(v.pat(), v.bindings().to_vec())
}
pub fn value<'a>(variant: &'a VariantInfo, prefix: &str) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
v.bind_with(|_| BindStyle::Move);
(v.pat(), v.bindings().to_vec())
}
/// Transforms "FooBar" to "foo-bar".
///
/// If the first Camel segment is "Moz", "Webkit", or "Servo", the result string
/// is prepended with "-".
pub fn to_css_identifier(mut camel_case: &str) -> String {
camel_case = camel_case.trim_end_matches('_');
let mut first = true;
let mut result = String::with_capacity(camel_case.len());
while let Some(segment) = split_camel_segment(&mut camel_case) {
if first {
match segment {
"Moz" | "Webkit" | "Servo" => first = false,
_ => {},
}
}
if!first {
result.push_str("-");
}
first = false;
result.push_str(&segment.to_lowercase());
}
result
}
/// Given "FooBar", returns "Foo" and sets `camel_case` to "Bar".
fn split_camel_segment<'input>(camel_case: &mut &'input str) -> Option<&'input str> {
let index = match camel_case.chars().next() {
None => return None,
Some(ch) => ch.len_utf8(),
};
let end_position = camel_case[index..]
.find(char::is_uppercase)
.map_or(camel_case.len(), |pos| index + pos);
let result = &camel_case[..end_position];
*camel_case = &camel_case[end_position..];
Some(result)
} | assert!(
ty.lifetimes.is_none(),
"Unhanded complex lifetime bound: {:?}", | random_line_split |
cg.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStreamExt;
use syn::{self, AngleBracketedGenericArguments, Binding, DeriveInput, Field};
use syn::{GenericArgument, GenericParam, Ident, Path};
use syn::{PathArguments, PathSegment, QSelf, Type, TypeArray};
use syn::{TypeParam, TypeParen, TypePath, TypeSlice, TypeTuple};
use syn::{Variant, WherePredicate};
use synstructure::{self, BindStyle, BindingInfo, VariantAst, VariantInfo};
/// Given an input type which has some where clauses already, like:
///
/// struct InputType<T>
/// where
/// T: Zero,
/// {
/// ...
/// }
///
/// Add the necessary `where` clauses so that the output type of a trait
/// fulfils them.
///
/// For example:
///
/// <T as ToComputedValue>::ComputedValue: Zero,
///
/// This needs to run before adding other bounds to the type parameters.
pub fn propagate_clauses_to_output_type(
where_clause: &mut Option<syn::WhereClause>,
generics: &syn::Generics,
trait_path: Path,
trait_output: Ident,
) {
let where_clause = match *where_clause {
Some(ref mut clause) => clause,
None => return,
};
let mut extra_bounds = vec![];
for pred in &where_clause.predicates {
let ty = match *pred {
syn::WherePredicate::Type(ref ty) => ty,
ref predicate => panic!("Unhanded complex where predicate: {:?}", predicate),
};
let path = match ty.bounded_ty {
syn::Type::Path(ref p) => &p.path,
ref ty => panic!("Unhanded complex where type: {:?}", ty),
};
assert!(
ty.lifetimes.is_none(),
"Unhanded complex lifetime bound: {:?}",
ty,
);
let ident = match path_to_ident(path) {
Some(i) => i,
None => panic!("Unhanded complex where type path: {:?}", path),
};
if generics.type_params().any(|param| param.ident == *ident) {
extra_bounds.push(ty.clone());
}
}
for bound in extra_bounds {
let ty = bound.bounded_ty;
let bounds = bound.bounds;
where_clause
.predicates
.push(parse_quote!(<#ty as #trait_path>::#trait_output: #bounds))
}
}
pub fn add_predicate(where_clause: &mut Option<syn::WhereClause>, pred: WherePredicate) {
where_clause
.get_or_insert(parse_quote!(where))
.predicates
.push(pred);
}
pub fn fmap_match<F>(input: &DeriveInput, bind_style: BindStyle, mut f: F) -> TokenStream
where
F: FnMut(BindingInfo) -> TokenStream,
{
let mut s = synstructure::Structure::new(input);
s.variants_mut().iter_mut().for_each(|v| {
v.bind_with(|_| bind_style);
});
s.each_variant(|variant| {
let (mapped, mapped_fields) = value(variant, "mapped");
let fields_pairs = variant.bindings().iter().zip(mapped_fields);
let mut computations = quote!();
computations.append_all(fields_pairs.map(|(field, mapped_field)| {
let expr = f(field.clone());
quote! { let #mapped_field = #expr; }
}));
computations.append_all(mapped);
Some(computations)
})
}
pub fn fmap_trait_output(input: &DeriveInput, trait_path: &Path, trait_output: Ident) -> Path {
let segment = PathSegment {
ident: input.ident.clone(),
arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: input
.generics
.params
.iter()
.map(|arg| match arg {
&GenericParam::Lifetime(ref data) => {
GenericArgument::Lifetime(data.lifetime.clone())
},
&GenericParam::Type(ref data) => {
let ident = &data.ident;
GenericArgument::Type(parse_quote!(<#ident as #trait_path>::#trait_output))
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
colon2_token: Default::default(),
gt_token: Default::default(),
lt_token: Default::default(),
}),
};
segment.into()
}
pub fn map_type_params<F>(ty: &Type, params: &[&TypeParam], f: &mut F) -> Type
where
F: FnMut(&Ident) -> Type,
{
match *ty {
Type::Slice(ref inner) => Type::from(TypeSlice {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
Type::Array(ref inner) => {
//ref ty, ref expr) => {
Type::from(TypeArray {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
})
},
ref ty @ Type::Never(_) => ty.clone(),
Type::Tuple(ref inner) => Type::from(TypeTuple {
elems: inner
.elems
.iter()
.map(|ty| map_type_params(&ty, params, f))
.collect(),
..inner.clone()
}),
Type::Path(TypePath {
qself: None,
ref path,
}) => {
if let Some(ident) = path_to_ident(path) {
if params.iter().any(|ref param| ¶m.ident == ident) {
return f(ident);
}
}
Type::from(TypePath {
qself: None,
path: map_type_params_in_path(path, params, f),
})
},
Type::Path(TypePath {
ref qself,
ref path,
}) => Type::from(TypePath {
qself: qself.as_ref().map(|qself| QSelf {
ty: Box::new(map_type_params(&qself.ty, params, f)),
position: qself.position,
..qself.clone()
}),
path: map_type_params_in_path(path, params, f),
}),
Type::Paren(ref inner) => Type::from(TypeParen {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
ref ty => panic!("type {:?} cannot be mapped yet", ty),
}
}
fn map_type_params_in_path<F>(path: &Path, params: &[&TypeParam], f: &mut F) -> Path
where
F: FnMut(&Ident) -> Type,
{
Path {
leading_colon: path.leading_colon,
segments: path
.segments
.iter()
.map(|segment| PathSegment {
ident: segment.ident.clone(),
arguments: match segment.arguments {
PathArguments::AngleBracketed(ref data) => {
PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: data
.args
.iter()
.map(|arg| match arg {
ty @ &GenericArgument::Lifetime(_) => ty.clone(),
&GenericArgument::Type(ref data) => {
GenericArgument::Type(map_type_params(data, params, f))
},
&GenericArgument::Binding(ref data) => {
GenericArgument::Binding(Binding {
ty: map_type_params(&data.ty, params, f),
..data.clone()
})
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
..data.clone()
})
},
ref arg @ PathArguments::None => arg.clone(),
ref parameters => panic!("parameters {:?} cannot be mapped yet", parameters),
},
})
.collect(),
}
}
fn path_to_ident(path: &Path) -> Option<&Ident> {
match *path {
Path {
leading_colon: None,
ref segments,
} if segments.len() == 1 => {
if segments[0].arguments.is_empty() {
Some(&segments[0].ident)
} else {
None
}
},
_ => None,
}
}
pub fn parse_field_attrs<A>(field: &Field) -> A
where
A: FromField,
{
match A::from_field(field) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse field attributes: {}", e),
}
}
pub fn parse_input_attrs<A>(input: &DeriveInput) -> A
where
A: FromDeriveInput,
{
match A::from_derive_input(input) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse input attributes: {}", e),
}
}
pub fn parse_variant_attrs_from_ast<A>(variant: &VariantAst) -> A
where
A: FromVariant,
|
pub fn parse_variant_attrs<A>(variant: &Variant) -> A
where
A: FromVariant,
{
match A::from_variant(variant) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse variant attributes: {}", e),
}
}
pub fn ref_pattern<'a>(
variant: &'a VariantInfo,
prefix: &str,
) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bind_with(|_| BindStyle::Ref);
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
(v.pat(), v.bindings().to_vec())
}
pub fn value<'a>(variant: &'a VariantInfo, prefix: &str) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
v.bind_with(|_| BindStyle::Move);
(v.pat(), v.bindings().to_vec())
}
/// Transforms "FooBar" to "foo-bar".
///
/// If the first Camel segment is "Moz", "Webkit", or "Servo", the result string
/// is prepended with "-".
pub fn to_css_identifier(mut camel_case: &str) -> String {
camel_case = camel_case.trim_end_matches('_');
let mut first = true;
let mut result = String::with_capacity(camel_case.len());
while let Some(segment) = split_camel_segment(&mut camel_case) {
if first {
match segment {
"Moz" | "Webkit" | "Servo" => first = false,
_ => {},
}
}
if!first {
result.push_str("-");
}
first = false;
result.push_str(&segment.to_lowercase());
}
result
}
/// Given "FooBar", returns "Foo" and sets `camel_case` to "Bar".
fn split_camel_segment<'input>(camel_case: &mut &'input str) -> Option<&'input str> {
let index = match camel_case.chars().next() {
None => return None,
Some(ch) => ch.len_utf8(),
};
let end_position = camel_case[index..]
.find(char::is_uppercase)
.map_or(camel_case.len(), |pos| index + pos);
let result = &camel_case[..end_position];
*camel_case = &camel_case[end_position..];
Some(result)
}
| {
let v = Variant {
ident: variant.ident.clone(),
attrs: variant.attrs.to_vec(),
fields: variant.fields.clone(),
discriminant: variant.discriminant.clone(),
};
parse_variant_attrs(&v)
} | identifier_body |
traits.rs | use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel};
use std::borrow::Cow;
use std::ops;
/// Interface for types used for storing hash data.
///
/// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of
/// useful x86 bytewise SIMD register widths (64, 128, 256, 512 bits).
///
/// Please feel free to open a pull request [on Github](https://github.com/abonander/img_hash)
/// if you need this implemented for a different array size.
pub trait HashBytes {
/// Construct this type from an iterator of bytes.
///
/// If this type has a finite capacity (i.e. an array) then it can ignore extra data
/// (the hash API will not create a hash larger than this type can contain). Unused capacity
/// **must** be zeroed.
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self where Self: Sized;
/// Return the maximum capacity of this type, in bits.
///
/// If this type has an arbitrary/theoretically infinite capacity, return `usize::max_value()`.
fn max_bits() -> usize;
/// Get the hash bytes as a slice.
fn as_slice(&self) -> &[u8];
}
impl HashBytes for Box<[u8]> {
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self {
// stable in 1.32, effectively the same thing
// iter.collect()
iter.collect::<Vec<u8>>().into_boxed_slice()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
impl HashBytes for Vec<u8> {
fn from_iter<I: Iterator<Item=u8>>(iter: I) -> Self {
iter.collect()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
macro_rules! hash_bytes_array {
($($n:expr),*) => {$(
impl HashBytes for [u8; $n] {
fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self {
// optimizer should eliminate this zeroing
let mut out = [0; $n];
for (src, dest) in iter.by_ref().zip(out.as_mut()) {
*dest = src;
}
out
}
fn max_bits() -> usize {
$n * 8
}
fn as_slice(&self) -> &[u8] { self }
}
)*}
}
hash_bytes_array!(8, 16, 24, 32, 40, 48, 56, 64);
struct BoolsToBytes<I> {
iter: I,
}
impl<I> Iterator for BoolsToBytes<I> where I: Iterator<Item=bool> {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
// starts at the LSB and works up
self.iter.by_ref().take(8).enumerate().fold(None, |accum, (n, val)| {
accum.or(Some(0)).map(|accum| accum | ((val as u8) << n))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
(
lower / 8,
// if the upper bound doesn't evenly divide by `8` then we will yield an extra item
upper.map(|upper| if upper % 8 == 0 { upper / 8 } else { upper / 8 + 1})
)
}
}
pub(crate) trait BitSet: HashBytes {
fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized {
Self::from_iter(BoolsToBytes { iter })
}
fn hamming(&self, other: &Self) -> u32 {
self.as_slice().iter().zip(other.as_slice()).map(|(l, r)| (l ^ r).count_ones()).sum()
}
}
impl<T: HashBytes> BitSet for T {}
/// Shorthand trait bound for APIs in this crate.
///
/// Currently only implemented for the types provided by `image` with 8-bit channels.
pub trait Image: GenericImageView +'static {
/// The equivalent `ImageBuffer` type for this container.
type Buf: Image + DiffImage;
/// Grayscale the image, reducing to 8 bit depth and dropping the alpha channel.
fn to_grayscale(&self) -> Cow<GrayImage>;
/// Blur the image with the given `Gaussian` sigma.
fn blur(&self, sigma: f32) -> Self::Buf;
/// Iterate over the image, passing each pixel's coordinates and values in `u8` to the closure.
///
/// The iteration order is unspecified but each pixel **must** be visited exactly _once_.
///
/// If the pixel's channels are wider than 8 bits then the values should be scaled to
/// `[0, 255]`, not truncated.
///
/// ### Note
/// If the pixel data length is 2 or 4, the last index is assumed to be the alpha channel.
/// A pixel data length outside of `[1, 4]` will cause a panic.
fn foreach_pixel8<F>(&self, foreach: F) where F: FnMut(u32, u32, &[u8]);
}
/// Image types that can be diffed.
pub trait DiffImage {
/// Subtract the pixel values of `other` from `self` in-place.
fn diff_inplace(&mut self, other: &Self);
}
#[cfg(not(feature = "nightly"))]
impl<P:'static, C:'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl<P:'static, C:'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
default fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
default fn blur(&self, sigma: f32) -> Self::Buf |
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
impl<P:'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> {
fn diff_inplace(&mut self, other: &Self) {
self.iter_mut().zip(other.iter()).for_each(|(l, r)| *l -= r);
}
}
impl Image for DynamicImage {
type Buf = image::RgbaImage;
fn to_grayscale(&self) -> Cow<GrayImage> {
self.as_luma8().map_or_else(|| Cow::Owned(self.to_luma()), Cow::Borrowed)
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl Image for GrayImage {
// type Buf = GrayImage;
// Avoids copying
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Borrowed(self)
}
}
#[test]
fn test_bools_to_bytes() {
let bools = (0.. 16).map(|x| x & 1 == 0);
let bytes = Vec::from_bools(bools.clone());
assert_eq!(*bytes, [0b01010101; 2]);
let bools_to_bytes = BoolsToBytes { iter: bools };
assert_eq!(bools_to_bytes.size_hint(), (2, Some(2)));
}
| { imageops::blur(self, sigma) } | identifier_body |
traits.rs | use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel};
use std::borrow::Cow;
use std::ops;
/// Interface for types used for storing hash data.
///
/// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of
/// useful x86 bytewise SIMD register widths (64, 128, 256, 512 bits).
///
/// Please feel free to open a pull request [on Github](https://github.com/abonander/img_hash)
/// if you need this implemented for a different array size.
pub trait HashBytes {
/// Construct this type from an iterator of bytes.
///
/// If this type has a finite capacity (i.e. an array) then it can ignore extra data
/// (the hash API will not create a hash larger than this type can contain). Unused capacity
/// **must** be zeroed.
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self where Self: Sized;
/// Return the maximum capacity of this type, in bits.
///
/// If this type has an arbitrary/theoretically infinite capacity, return `usize::max_value()`.
fn max_bits() -> usize;
/// Get the hash bytes as a slice.
fn as_slice(&self) -> &[u8];
}
impl HashBytes for Box<[u8]> {
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self {
// stable in 1.32, effectively the same thing
// iter.collect()
iter.collect::<Vec<u8>>().into_boxed_slice()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
impl HashBytes for Vec<u8> {
fn from_iter<I: Iterator<Item=u8>>(iter: I) -> Self {
iter.collect()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
macro_rules! hash_bytes_array {
($($n:expr),*) => {$(
impl HashBytes for [u8; $n] {
fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self {
// optimizer should eliminate this zeroing
let mut out = [0; $n];
for (src, dest) in iter.by_ref().zip(out.as_mut()) {
*dest = src;
}
out
}
fn max_bits() -> usize {
$n * 8
}
fn as_slice(&self) -> &[u8] { self }
}
)*}
}
hash_bytes_array!(8, 16, 24, 32, 40, 48, 56, 64);
struct BoolsToBytes<I> {
iter: I,
}
impl<I> Iterator for BoolsToBytes<I> where I: Iterator<Item=bool> {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
// starts at the LSB and works up
self.iter.by_ref().take(8).enumerate().fold(None, |accum, (n, val)| {
accum.or(Some(0)).map(|accum| accum | ((val as u8) << n))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
(
lower / 8,
// if the upper bound doesn't evenly divide by `8` then we will yield an extra item
upper.map(|upper| if upper % 8 == 0 | else { upper / 8 + 1})
)
}
}
pub(crate) trait BitSet: HashBytes {
fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized {
Self::from_iter(BoolsToBytes { iter })
}
fn hamming(&self, other: &Self) -> u32 {
self.as_slice().iter().zip(other.as_slice()).map(|(l, r)| (l ^ r).count_ones()).sum()
}
}
impl<T: HashBytes> BitSet for T {}
/// Shorthand trait bound for APIs in this crate.
///
/// Currently only implemented for the types provided by `image` with 8-bit channels.
pub trait Image: GenericImageView +'static {
/// The equivalent `ImageBuffer` type for this container.
type Buf: Image + DiffImage;
/// Grayscale the image, reducing to 8 bit depth and dropping the alpha channel.
fn to_grayscale(&self) -> Cow<GrayImage>;
/// Blur the image with the given `Gaussian` sigma.
fn blur(&self, sigma: f32) -> Self::Buf;
/// Iterate over the image, passing each pixel's coordinates and values in `u8` to the closure.
///
/// The iteration order is unspecified but each pixel **must** be visited exactly _once_.
///
/// If the pixel's channels are wider than 8 bits then the values should be scaled to
/// `[0, 255]`, not truncated.
///
/// ### Note
/// If the pixel data length is 2 or 4, the last index is assumed to be the alpha channel.
/// A pixel data length outside of `[1, 4]` will cause a panic.
fn foreach_pixel8<F>(&self, foreach: F) where F: FnMut(u32, u32, &[u8]);
}
/// Image types that can be diffed.
pub trait DiffImage {
/// Subtract the pixel values of `other` from `self` in-place.
fn diff_inplace(&mut self, other: &Self);
}
#[cfg(not(feature = "nightly"))]
impl<P:'static, C:'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl<P:'static, C:'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
default fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
default fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
impl<P:'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> {
fn diff_inplace(&mut self, other: &Self) {
self.iter_mut().zip(other.iter()).for_each(|(l, r)| *l -= r);
}
}
impl Image for DynamicImage {
type Buf = image::RgbaImage;
fn to_grayscale(&self) -> Cow<GrayImage> {
self.as_luma8().map_or_else(|| Cow::Owned(self.to_luma()), Cow::Borrowed)
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl Image for GrayImage {
// type Buf = GrayImage;
// Avoids copying
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Borrowed(self)
}
}
#[test]
fn test_bools_to_bytes() {
let bools = (0.. 16).map(|x| x & 1 == 0);
let bytes = Vec::from_bools(bools.clone());
assert_eq!(*bytes, [0b01010101; 2]);
let bools_to_bytes = BoolsToBytes { iter: bools };
assert_eq!(bools_to_bytes.size_hint(), (2, Some(2)));
}
| { upper / 8 } | conditional_block |
traits.rs | use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel};
use std::borrow::Cow;
use std::ops;
/// Interface for types used for storing hash data.
///
/// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of
/// useful x86 bytewise SIMD register widths (64, 128, 256, 512 bits).
///
/// Please feel free to open a pull request [on Github](https://github.com/abonander/img_hash)
/// if you need this implemented for a different array size.
pub trait HashBytes {
/// Construct this type from an iterator of bytes.
///
/// If this type has a finite capacity (i.e. an array) then it can ignore extra data
/// (the hash API will not create a hash larger than this type can contain). Unused capacity
/// **must** be zeroed.
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self where Self: Sized;
/// Return the maximum capacity of this type, in bits.
///
/// If this type has an arbitrary/theoretically infinite capacity, return `usize::max_value()`.
fn max_bits() -> usize;
/// Get the hash bytes as a slice.
fn as_slice(&self) -> &[u8];
}
impl HashBytes for Box<[u8]> {
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self {
// stable in 1.32, effectively the same thing
// iter.collect()
iter.collect::<Vec<u8>>().into_boxed_slice()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
impl HashBytes for Vec<u8> {
fn from_iter<I: Iterator<Item=u8>>(iter: I) -> Self {
iter.collect()
}
fn max_bits() -> usize {
usize::max_value()
}
| impl HashBytes for [u8; $n] {
fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self {
// optimizer should eliminate this zeroing
let mut out = [0; $n];
for (src, dest) in iter.by_ref().zip(out.as_mut()) {
*dest = src;
}
out
}
fn max_bits() -> usize {
$n * 8
}
fn as_slice(&self) -> &[u8] { self }
}
)*}
}
hash_bytes_array!(8, 16, 24, 32, 40, 48, 56, 64);
struct BoolsToBytes<I> {
iter: I,
}
impl<I> Iterator for BoolsToBytes<I> where I: Iterator<Item=bool> {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
// starts at the LSB and works up
self.iter.by_ref().take(8).enumerate().fold(None, |accum, (n, val)| {
accum.or(Some(0)).map(|accum| accum | ((val as u8) << n))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
(
lower / 8,
// if the upper bound doesn't evenly divide by `8` then we will yield an extra item
upper.map(|upper| if upper % 8 == 0 { upper / 8 } else { upper / 8 + 1})
)
}
}
pub(crate) trait BitSet: HashBytes {
fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized {
Self::from_iter(BoolsToBytes { iter })
}
fn hamming(&self, other: &Self) -> u32 {
self.as_slice().iter().zip(other.as_slice()).map(|(l, r)| (l ^ r).count_ones()).sum()
}
}
impl<T: HashBytes> BitSet for T {}
/// Shorthand trait bound for APIs in this crate.
///
/// Currently only implemented for the types provided by `image` with 8-bit channels.
pub trait Image: GenericImageView +'static {
/// The equivalent `ImageBuffer` type for this container.
type Buf: Image + DiffImage;
/// Grayscale the image, reducing to 8 bit depth and dropping the alpha channel.
fn to_grayscale(&self) -> Cow<GrayImage>;
/// Blur the image with the given `Gaussian` sigma.
fn blur(&self, sigma: f32) -> Self::Buf;
/// Iterate over the image, passing each pixel's coordinates and values in `u8` to the closure.
///
/// The iteration order is unspecified but each pixel **must** be visited exactly _once_.
///
/// If the pixel's channels are wider than 8 bits then the values should be scaled to
/// `[0, 255]`, not truncated.
///
/// ### Note
/// If the pixel data length is 2 or 4, the last index is assumed to be the alpha channel.
/// A pixel data length outside of `[1, 4]` will cause a panic.
fn foreach_pixel8<F>(&self, foreach: F) where F: FnMut(u32, u32, &[u8]);
}
/// Image types that can be diffed.
pub trait DiffImage {
/// Subtract the pixel values of `other` from `self` in-place.
fn diff_inplace(&mut self, other: &Self);
}
#[cfg(not(feature = "nightly"))]
impl<P:'static, C:'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl<P:'static, C:'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
default fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
default fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
impl<P:'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> {
fn diff_inplace(&mut self, other: &Self) {
self.iter_mut().zip(other.iter()).for_each(|(l, r)| *l -= r);
}
}
impl Image for DynamicImage {
type Buf = image::RgbaImage;
fn to_grayscale(&self) -> Cow<GrayImage> {
self.as_luma8().map_or_else(|| Cow::Owned(self.to_luma()), Cow::Borrowed)
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl Image for GrayImage {
// type Buf = GrayImage;
// Avoids copying
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Borrowed(self)
}
}
#[test]
fn test_bools_to_bytes() {
let bools = (0.. 16).map(|x| x & 1 == 0);
let bytes = Vec::from_bools(bools.clone());
assert_eq!(*bytes, [0b01010101; 2]);
let bools_to_bytes = BoolsToBytes { iter: bools };
assert_eq!(bools_to_bytes.size_hint(), (2, Some(2)));
} | fn as_slice(&self) -> &[u8] { self }
}
macro_rules! hash_bytes_array {
($($n:expr),*) => {$( | random_line_split |
traits.rs | use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel};
use std::borrow::Cow;
use std::ops;
/// Interface for types used for storing hash data.
///
/// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of
/// useful x86 bytewise SIMD register widths (64, 128, 256, 512 bits).
///
/// Please feel free to open a pull request [on Github](https://github.com/abonander/img_hash)
/// if you need this implemented for a different array size.
pub trait HashBytes {
/// Construct this type from an iterator of bytes.
///
/// If this type has a finite capacity (i.e. an array) then it can ignore extra data
/// (the hash API will not create a hash larger than this type can contain). Unused capacity
/// **must** be zeroed.
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self where Self: Sized;
/// Return the maximum capacity of this type, in bits.
///
/// If this type has an arbitrary/theoretically infinite capacity, return `usize::max_value()`.
fn max_bits() -> usize;
/// Get the hash bytes as a slice.
fn as_slice(&self) -> &[u8];
}
impl HashBytes for Box<[u8]> {
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self {
// stable in 1.32, effectively the same thing
// iter.collect()
iter.collect::<Vec<u8>>().into_boxed_slice()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
impl HashBytes for Vec<u8> {
fn from_iter<I: Iterator<Item=u8>>(iter: I) -> Self {
iter.collect()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
macro_rules! hash_bytes_array {
($($n:expr),*) => {$(
impl HashBytes for [u8; $n] {
fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self {
// optimizer should eliminate this zeroing
let mut out = [0; $n];
for (src, dest) in iter.by_ref().zip(out.as_mut()) {
*dest = src;
}
out
}
fn max_bits() -> usize {
$n * 8
}
fn as_slice(&self) -> &[u8] { self }
}
)*}
}
hash_bytes_array!(8, 16, 24, 32, 40, 48, 56, 64);
struct BoolsToBytes<I> {
iter: I,
}
impl<I> Iterator for BoolsToBytes<I> where I: Iterator<Item=bool> {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
// starts at the LSB and works up
self.iter.by_ref().take(8).enumerate().fold(None, |accum, (n, val)| {
accum.or(Some(0)).map(|accum| accum | ((val as u8) << n))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
(
lower / 8,
// if the upper bound doesn't evenly divide by `8` then we will yield an extra item
upper.map(|upper| if upper % 8 == 0 { upper / 8 } else { upper / 8 + 1})
)
}
}
pub(crate) trait BitSet: HashBytes {
fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized {
Self::from_iter(BoolsToBytes { iter })
}
fn hamming(&self, other: &Self) -> u32 {
self.as_slice().iter().zip(other.as_slice()).map(|(l, r)| (l ^ r).count_ones()).sum()
}
}
impl<T: HashBytes> BitSet for T {}
/// Shorthand trait bound for APIs in this crate.
///
/// Currently only implemented for the types provided by `image` with 8-bit channels.
pub trait Image: GenericImageView +'static {
/// The equivalent `ImageBuffer` type for this container.
type Buf: Image + DiffImage;
/// Grayscale the image, reducing to 8 bit depth and dropping the alpha channel.
fn to_grayscale(&self) -> Cow<GrayImage>;
/// Blur the image with the given `Gaussian` sigma.
fn blur(&self, sigma: f32) -> Self::Buf;
/// Iterate over the image, passing each pixel's coordinates and values in `u8` to the closure.
///
/// The iteration order is unspecified but each pixel **must** be visited exactly _once_.
///
/// If the pixel's channels are wider than 8 bits then the values should be scaled to
/// `[0, 255]`, not truncated.
///
/// ### Note
/// If the pixel data length is 2 or 4, the last index is assumed to be the alpha channel.
/// A pixel data length outside of `[1, 4]` will cause a panic.
fn foreach_pixel8<F>(&self, foreach: F) where F: FnMut(u32, u32, &[u8]);
}
/// Image types that can be diffed.
pub trait DiffImage {
/// Subtract the pixel values of `other` from `self` in-place.
fn diff_inplace(&mut self, other: &Self);
}
#[cfg(not(feature = "nightly"))]
impl<P:'static, C:'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl<P:'static, C:'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
default fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
default fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
impl<P:'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> {
fn diff_inplace(&mut self, other: &Self) {
self.iter_mut().zip(other.iter()).for_each(|(l, r)| *l -= r);
}
}
impl Image for DynamicImage {
type Buf = image::RgbaImage;
fn to_grayscale(&self) -> Cow<GrayImage> {
self.as_luma8().map_or_else(|| Cow::Owned(self.to_luma()), Cow::Borrowed)
}
fn | (&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl Image for GrayImage {
// type Buf = GrayImage;
// Avoids copying
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Borrowed(self)
}
}
#[test]
fn test_bools_to_bytes() {
let bools = (0.. 16).map(|x| x & 1 == 0);
let bytes = Vec::from_bools(bools.clone());
assert_eq!(*bytes, [0b01010101; 2]);
let bools_to_bytes = BoolsToBytes { iter: bools };
assert_eq!(bools_to_bytes.size_hint(), (2, Some(2)));
}
| blur | identifier_name |
time.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/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat;
use values::computed::{Context, ToComputedValue};
use values::computed::time::Time as ComputedTime;
use values::specified::calc::CalcNode;
/// A time value according to CSS-VALUES § 6.2.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
pub struct T | {
seconds: CSSFloat,
unit: TimeUnit,
was_calc: bool,
}
/// A time unit.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
pub enum TimeUnit {
/// `s`
Second,
/// `ms`
Millisecond,
}
impl Time {
/// Returns a time value that represents `seconds` seconds.
pub fn from_seconds(seconds: CSSFloat) -> Self {
Time {
seconds,
unit: TimeUnit::Second,
was_calc: false,
}
}
/// Returns `0s`.
pub fn zero() -> Self {
Self::from_seconds(0.0)
}
/// Returns the time in fractional seconds.
pub fn seconds(self) -> CSSFloat {
self.seconds
}
/// Parses a time according to CSS-VALUES § 6.2.
pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Time, ()> {
let (seconds, unit) = match_ignore_ascii_case! { unit,
"s" => (value, TimeUnit::Second),
"ms" => (value / 1000.0, TimeUnit::Millisecond),
_ => return Err(())
};
Ok(Time {
seconds,
unit,
was_calc,
})
}
/// Returns a `Time` value from a CSS `calc()` expression.
pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second,
was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit,..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {},
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(e) => return Err(e.into()),
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(ParsingMode::DEFAULT, time.seconds) => Ok(time),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
/// Parses a non-negative time value.
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::NonNegative)
}
}
impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
ComputedTime::from_seconds(self.seconds())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::All)
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc {
dest.write_str("calc(")?;
}
match self.unit {
TimeUnit::Second => {
self.seconds.to_css(dest)?;
dest.write_str("s")?;
},
TimeUnit::Millisecond => {
(self.seconds * 1000.).to_css(dest)?;
dest.write_str("ms")?;
},
}
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
}
| ime | identifier_name |
time.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/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat;
use values::computed::{Context, ToComputedValue};
use values::computed::time::Time as ComputedTime;
use values::specified::calc::CalcNode;
/// A time value according to CSS-VALUES § 6.2.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
pub struct Time {
seconds: CSSFloat,
unit: TimeUnit,
was_calc: bool,
}
/// A time unit.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
pub enum TimeUnit {
/// `s`
Second,
/// `ms`
Millisecond,
}
impl Time { | unit: TimeUnit::Second,
was_calc: false,
}
}
/// Returns `0s`.
pub fn zero() -> Self {
Self::from_seconds(0.0)
}
/// Returns the time in fractional seconds.
pub fn seconds(self) -> CSSFloat {
self.seconds
}
/// Parses a time according to CSS-VALUES § 6.2.
pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Time, ()> {
let (seconds, unit) = match_ignore_ascii_case! { unit,
"s" => (value, TimeUnit::Second),
"ms" => (value / 1000.0, TimeUnit::Millisecond),
_ => return Err(())
};
Ok(Time {
seconds,
unit,
was_calc,
})
}
/// Returns a `Time` value from a CSS `calc()` expression.
pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second,
was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit,..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {},
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(e) => return Err(e.into()),
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(ParsingMode::DEFAULT, time.seconds) => Ok(time),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
/// Parses a non-negative time value.
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::NonNegative)
}
}
impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
ComputedTime::from_seconds(self.seconds())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::All)
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc {
dest.write_str("calc(")?;
}
match self.unit {
TimeUnit::Second => {
self.seconds.to_css(dest)?;
dest.write_str("s")?;
},
TimeUnit::Millisecond => {
(self.seconds * 1000.).to_css(dest)?;
dest.write_str("ms")?;
},
}
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
} | /// Returns a time value that represents `seconds` seconds.
pub fn from_seconds(seconds: CSSFloat) -> Self {
Time {
seconds, | random_line_split |
time.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/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat;
use values::computed::{Context, ToComputedValue};
use values::computed::time::Time as ComputedTime;
use values::specified::calc::CalcNode;
/// A time value according to CSS-VALUES § 6.2.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
pub struct Time {
seconds: CSSFloat,
unit: TimeUnit,
was_calc: bool,
}
/// A time unit.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
pub enum TimeUnit {
/// `s`
Second,
/// `ms`
Millisecond,
}
impl Time {
/// Returns a time value that represents `seconds` seconds.
pub fn from_seconds(seconds: CSSFloat) -> Self {
Time {
seconds,
unit: TimeUnit::Second,
was_calc: false,
}
}
/// Returns `0s`.
pub fn zero() -> Self {
Self::from_seconds(0.0)
}
/// Returns the time in fractional seconds.
pub fn seconds(self) -> CSSFloat {
self.seconds
}
/// Parses a time according to CSS-VALUES § 6.2.
pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Time, ()> {
| /// Returns a `Time` value from a CSS `calc()` expression.
pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second,
was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit,..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {},
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(e) => return Err(e.into()),
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(ParsingMode::DEFAULT, time.seconds) => Ok(time),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
/// Parses a non-negative time value.
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::NonNegative)
}
}
impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
ComputedTime::from_seconds(self.seconds())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::All)
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc {
dest.write_str("calc(")?;
}
match self.unit {
TimeUnit::Second => {
self.seconds.to_css(dest)?;
dest.write_str("s")?;
},
TimeUnit::Millisecond => {
(self.seconds * 1000.).to_css(dest)?;
dest.write_str("ms")?;
},
}
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
}
| let (seconds, unit) = match_ignore_ascii_case! { unit,
"s" => (value, TimeUnit::Second),
"ms" => (value / 1000.0, TimeUnit::Millisecond),
_ => return Err(())
};
Ok(Time {
seconds,
unit,
was_calc,
})
}
| identifier_body |
time.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/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat;
use values::computed::{Context, ToComputedValue};
use values::computed::time::Time as ComputedTime;
use values::specified::calc::CalcNode;
/// A time value according to CSS-VALUES § 6.2.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
pub struct Time {
seconds: CSSFloat,
unit: TimeUnit,
was_calc: bool,
}
/// A time unit.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
pub enum TimeUnit {
/// `s`
Second,
/// `ms`
Millisecond,
}
impl Time {
/// Returns a time value that represents `seconds` seconds.
pub fn from_seconds(seconds: CSSFloat) -> Self {
Time {
seconds,
unit: TimeUnit::Second,
was_calc: false,
}
}
/// Returns `0s`.
pub fn zero() -> Self {
Self::from_seconds(0.0)
}
/// Returns the time in fractional seconds.
pub fn seconds(self) -> CSSFloat {
self.seconds
}
/// Parses a time according to CSS-VALUES § 6.2.
pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Time, ()> {
let (seconds, unit) = match_ignore_ascii_case! { unit,
"s" => (value, TimeUnit::Second),
"ms" => (value / 1000.0, TimeUnit::Millisecond),
_ => return Err(())
};
Ok(Time {
seconds,
unit,
was_calc,
})
}
/// Returns a `Time` value from a CSS `calc()` expression.
pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second,
was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit,..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {},
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(e) => return Err(e.into()),
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(ParsingMode::DEFAULT, time.seconds) => Ok(time),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
/// Parses a non-negative time value.
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::NonNegative)
}
}
impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
ComputedTime::from_seconds(self.seconds())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::All)
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc {
| match self.unit {
TimeUnit::Second => {
self.seconds.to_css(dest)?;
dest.write_str("s")?;
},
TimeUnit::Millisecond => {
(self.seconds * 1000.).to_css(dest)?;
dest.write_str("ms")?;
},
}
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
}
| dest.write_str("calc(")?;
}
| conditional_block |
main.rs | use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
// ANCHOR: here
use std::thread;
use std::time::Duration;
// --snip--
// ANCHOR_END: here
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// ANCHOR: here
fn handle_connection(mut stream: TcpStream) {
// --snip--
// ANCHOR_END: here
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
// ANCHOR: here
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) | else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
// --snip--
// ANCHOR_END: here
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
// ANCHOR: here
}
// ANCHOR_END: here
| {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} | conditional_block |
main.rs | use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
// ANCHOR: here
use std::thread;
use std::time::Duration;
// --snip--
// ANCHOR_END: here
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// ANCHOR: here
fn handle_connection(mut stream: TcpStream) {
// --snip--
// ANCHOR_END: here
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
// ANCHOR: here
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
// --snip-- | // ANCHOR_END: here
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
// ANCHOR: here
}
// ANCHOR_END: here | random_line_split |
|
main.rs | use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
// ANCHOR: here
use std::thread;
use std::time::Duration;
// --snip--
// ANCHOR_END: here
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// ANCHOR: here
fn handle_connection(mut stream: TcpStream) | // --snip--
// ANCHOR_END: here
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
// ANCHOR: here
}
// ANCHOR_END: here
| {
// --snip--
// ANCHOR_END: here
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
// ANCHOR: here
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
| identifier_body |
main.rs | use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
// ANCHOR: here
use std::thread;
use std::time::Duration;
// --snip--
// ANCHOR_END: here
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// ANCHOR: here
fn | (mut stream: TcpStream) {
// --snip--
// ANCHOR_END: here
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
// ANCHOR: here
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
// --snip--
// ANCHOR_END: here
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
// ANCHOR: here
}
// ANCHOR_END: here
| handle_connection | identifier_name |
command.rs | // Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Command Buffer device interface
use std::ops::Deref;
use std::collections::hash_set::{self, HashSet};
use {Resources, IndexType, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ClearColor {
/// Standard floating-point vec4 color
Float([f32; 4]),
/// Integer vector to clear ivec4 targets.
Int([i32; 4]),
/// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready for execution on the device.
#[allow(missing_docs)]
pub trait Buffer<R: Resources>: Send {
/// Reset the command buffer contents, retain the allocated storage
fn reset(&mut self);
/// Bind a pipeline state object
fn bind_pipeline_state(&mut self, R::PipelineStateObject);
/// Bind a complete set of vertex buffers
fn bind_vertex_buffers(&mut self, pso::VertexBufferSet<R>);
/// Bind a complete set of constant buffers
fn bind_constant_buffers(&mut self, &[pso::ConstantBufferParam<R>]);
/// Bind a global constant
fn bind_global_constant(&mut self, shade::Location, shade::UniformValue);
/// Bind a complete set of shader resource views
fn bind_resource_views(&mut self, &[pso::ResourceViewParam<R>]);
/// Bind a complete set of unordered access views
fn bind_unordered_views(&mut self, &[pso::UnorderedViewParam<R>]);
/// Bind a complete set of samplers
fn bind_samplers(&mut self, &[pso::SamplerParam<R>]);
/// Bind a complete set of pixel targets, including multiple
/// colors views and an optional depth/stencil view.
fn bind_pixel_targets(&mut self, pso::PixelTargetSet<R>);
/// Bind an index buffer
fn bind_index(&mut self, R::Buffer, IndexType);
/// Set scissor rectangle
fn set_scissor(&mut self, target::Rect);
/// Set reference values for the blending and stencil front/back
fn set_ref_values(&mut self, state::RefValues);
/// Copy part of a buffer to another
fn copy_buffer(&mut self, src: R::Buffer, dst: R::Buffer,
src_offset_bytes: usize, dst_offset_bytes: usize,
size_bytes: usize);
/// Copy part of a buffer to a texture
fn copy_buffer_to_texture(&mut self,
src: R::Buffer, src_offset_bytes: usize,
dst: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo);
/// Copy part of a texture to a buffer
fn copy_texture_to_buffer(&mut self,
src: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo,
dst: R::Buffer, dst_offset_bytes: usize);
/// Update a vertex/index/uniform buffer
fn update_buffer(&mut self, R::Buffer, data: &[u8], offset: usize);
/// Update a texture
fn update_texture(&mut self, R::Texture, texture::Kind, Option<texture::CubeFace>,
data: &[u8], texture::RawImageInfo);
fn generate_mipmap(&mut self, R::ShaderResourceView);
/// Clear color target
fn clear_color(&mut self, R::RenderTargetView, ClearColor);
fn clear_depth_stencil(&mut self, R::DepthStencilView,
Option<target::Depth>, Option<target::Stencil>);
/// Draw a primitive
fn call_draw(&mut self, VertexCount, VertexCount, Option<InstanceParams>);
/// Draw a primitive with index buffer
fn call_draw_indexed(&mut self, VertexCount, VertexCount, VertexCount, Option<InstanceParams>);
}
macro_rules! impl_clear {
{ $( $ty:ty = $sub:ident[$a:expr, $b:expr, $c:expr, $d:expr], )* } => {
$(
impl From<$ty> for ClearColor {
fn from(v: $ty) -> ClearColor {
ClearColor::$sub([v[$a], v[$b], v[$c], v[$d]])
}
}
)*
}
}
impl_clear! {
[f32; 4] = Float[0, 1, 2, 3],
[f32; 3] = Float[0, 1, 2, 0],
[f32; 2] = Float[0, 1, 0, 0],
[i32; 4] = Int [0, 1, 2, 3],
[i32; 3] = Int [0, 1, 2, 0],
[i32; 2] = Int [0, 1, 0, 0],
[u32; 4] = Uint [0, 1, 2, 3],
[u32; 3] = Uint [0, 1, 2, 0],
[u32; 2] = Uint [0, 1, 0, 0],
}
impl From<f32> for ClearColor {
fn from(v: f32) -> ClearColor {
ClearColor::Float([v, 0.0, 0.0, 0.0])
}
}
impl From<i32> for ClearColor {
fn from(v: i32) -> ClearColor {
ClearColor::Int([v, 0, 0, 0])
}
}
impl From<u32> for ClearColor {
fn from(v: u32) -> ClearColor {
ClearColor::Uint([v, 0, 0, 0])
}
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informations
pub fn new() -> Self {
AccessInfo {
mapped_reads: HashSet::new(),
mapped_writes: HashSet::new(),
}
}
/// Clear access informations
pub fn clear(&mut self) {
self.mapped_reads.clear();
self.mapped_writes.clear();
}
/// Register a buffer read access
pub fn buffer_read(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_reads.insert(buffer.clone());
}
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() |
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> AccessInfoBuffers<R> {
self.mapped_reads.iter()
}
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads?
pub fn has_mapped_reads(&self) -> bool {
!self.mapped_reads.is_empty()
}
/// Is there any mapped buffer writes?
pub fn has_mapped_writes(&self) -> bool {
!self.mapped_writes.is_empty()
}
/// Takes all the accesses necessary for submission
pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> {
for buffer in self.mapped_reads().chain(self.mapped_writes()) {
unsafe {
if!buffer.mapping().unwrap().take_access() {
return Err(SubmissionError::AccessOverlap);
}
}
}
Ok(AccessGuard { inner: self })
}
}
#[allow(missing_docs)]
pub type AccessInfoBuffers<'a, R> = hash_set::Iter<'a, handle::RawBuffer<R>>;
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuard<'a, R: Resources> {
inner: &'a AccessInfo<R>,
}
#[allow(missing_docs)]
impl<'a, R: Resources> AccessGuard<'a, R> {
/// Returns the mapped buffers that The GPU will read from,
/// with exclusive acces to their mapping
pub fn access_mapped_reads(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_reads()
}
}
/// Returns the mapped buffers that The GPU will write to,
/// with exclusive acces to their mapping
pub fn access_mapped_writes(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_writes()
}
}
pub fn access_mapped(&mut self) -> AccessGuardBuffersChain<R> {
AccessGuardBuffersChain {
fst: self.inner.mapped_reads(),
snd: self.inner.mapped_writes(),
}
}
}
impl<'a, R: Resources> Deref for AccessGuard<'a, R> {
type Target = AccessInfo<R>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, R: Resources> Drop for AccessGuard<'a, R> {
fn drop(&mut self) {
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffersChain<'a, R: Resources> {
fst: AccessInfoBuffers<'a, R>,
snd: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffersChain<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.fst.next().or_else(|| self.snd.next())
.map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
| {
self.mapped_writes.insert(buffer.clone());
} | conditional_block |
command.rs | // Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Command Buffer device interface
use std::ops::Deref;
use std::collections::hash_set::{self, HashSet};
use {Resources, IndexType, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ClearColor {
/// Standard floating-point vec4 color
Float([f32; 4]),
/// Integer vector to clear ivec4 targets.
Int([i32; 4]),
/// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready for execution on the device.
#[allow(missing_docs)]
pub trait Buffer<R: Resources>: Send {
/// Reset the command buffer contents, retain the allocated storage
fn reset(&mut self);
/// Bind a pipeline state object
fn bind_pipeline_state(&mut self, R::PipelineStateObject);
/// Bind a complete set of vertex buffers
fn bind_vertex_buffers(&mut self, pso::VertexBufferSet<R>);
/// Bind a complete set of constant buffers
fn bind_constant_buffers(&mut self, &[pso::ConstantBufferParam<R>]);
/// Bind a global constant
fn bind_global_constant(&mut self, shade::Location, shade::UniformValue);
/// Bind a complete set of shader resource views
fn bind_resource_views(&mut self, &[pso::ResourceViewParam<R>]);
/// Bind a complete set of unordered access views
fn bind_unordered_views(&mut self, &[pso::UnorderedViewParam<R>]);
/// Bind a complete set of samplers
fn bind_samplers(&mut self, &[pso::SamplerParam<R>]);
/// Bind a complete set of pixel targets, including multiple
/// colors views and an optional depth/stencil view.
fn bind_pixel_targets(&mut self, pso::PixelTargetSet<R>);
/// Bind an index buffer
fn bind_index(&mut self, R::Buffer, IndexType);
/// Set scissor rectangle
fn set_scissor(&mut self, target::Rect);
/// Set reference values for the blending and stencil front/back
fn set_ref_values(&mut self, state::RefValues);
/// Copy part of a buffer to another
fn copy_buffer(&mut self, src: R::Buffer, dst: R::Buffer,
src_offset_bytes: usize, dst_offset_bytes: usize,
size_bytes: usize);
/// Copy part of a buffer to a texture
fn copy_buffer_to_texture(&mut self,
src: R::Buffer, src_offset_bytes: usize,
dst: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo);
/// Copy part of a texture to a buffer
fn copy_texture_to_buffer(&mut self,
src: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo,
dst: R::Buffer, dst_offset_bytes: usize);
/// Update a vertex/index/uniform buffer
fn update_buffer(&mut self, R::Buffer, data: &[u8], offset: usize);
/// Update a texture
fn update_texture(&mut self, R::Texture, texture::Kind, Option<texture::CubeFace>,
data: &[u8], texture::RawImageInfo); | fn generate_mipmap(&mut self, R::ShaderResourceView);
/// Clear color target
fn clear_color(&mut self, R::RenderTargetView, ClearColor);
fn clear_depth_stencil(&mut self, R::DepthStencilView,
Option<target::Depth>, Option<target::Stencil>);
/// Draw a primitive
fn call_draw(&mut self, VertexCount, VertexCount, Option<InstanceParams>);
/// Draw a primitive with index buffer
fn call_draw_indexed(&mut self, VertexCount, VertexCount, VertexCount, Option<InstanceParams>);
}
macro_rules! impl_clear {
{ $( $ty:ty = $sub:ident[$a:expr, $b:expr, $c:expr, $d:expr], )* } => {
$(
impl From<$ty> for ClearColor {
fn from(v: $ty) -> ClearColor {
ClearColor::$sub([v[$a], v[$b], v[$c], v[$d]])
}
}
)*
}
}
impl_clear! {
[f32; 4] = Float[0, 1, 2, 3],
[f32; 3] = Float[0, 1, 2, 0],
[f32; 2] = Float[0, 1, 0, 0],
[i32; 4] = Int [0, 1, 2, 3],
[i32; 3] = Int [0, 1, 2, 0],
[i32; 2] = Int [0, 1, 0, 0],
[u32; 4] = Uint [0, 1, 2, 3],
[u32; 3] = Uint [0, 1, 2, 0],
[u32; 2] = Uint [0, 1, 0, 0],
}
impl From<f32> for ClearColor {
fn from(v: f32) -> ClearColor {
ClearColor::Float([v, 0.0, 0.0, 0.0])
}
}
impl From<i32> for ClearColor {
fn from(v: i32) -> ClearColor {
ClearColor::Int([v, 0, 0, 0])
}
}
impl From<u32> for ClearColor {
fn from(v: u32) -> ClearColor {
ClearColor::Uint([v, 0, 0, 0])
}
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informations
pub fn new() -> Self {
AccessInfo {
mapped_reads: HashSet::new(),
mapped_writes: HashSet::new(),
}
}
/// Clear access informations
pub fn clear(&mut self) {
self.mapped_reads.clear();
self.mapped_writes.clear();
}
/// Register a buffer read access
pub fn buffer_read(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_reads.insert(buffer.clone());
}
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_writes.insert(buffer.clone());
}
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> AccessInfoBuffers<R> {
self.mapped_reads.iter()
}
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads?
pub fn has_mapped_reads(&self) -> bool {
!self.mapped_reads.is_empty()
}
/// Is there any mapped buffer writes?
pub fn has_mapped_writes(&self) -> bool {
!self.mapped_writes.is_empty()
}
/// Takes all the accesses necessary for submission
pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> {
for buffer in self.mapped_reads().chain(self.mapped_writes()) {
unsafe {
if!buffer.mapping().unwrap().take_access() {
return Err(SubmissionError::AccessOverlap);
}
}
}
Ok(AccessGuard { inner: self })
}
}
#[allow(missing_docs)]
pub type AccessInfoBuffers<'a, R> = hash_set::Iter<'a, handle::RawBuffer<R>>;
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuard<'a, R: Resources> {
inner: &'a AccessInfo<R>,
}
#[allow(missing_docs)]
impl<'a, R: Resources> AccessGuard<'a, R> {
/// Returns the mapped buffers that The GPU will read from,
/// with exclusive acces to their mapping
pub fn access_mapped_reads(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_reads()
}
}
/// Returns the mapped buffers that The GPU will write to,
/// with exclusive acces to their mapping
pub fn access_mapped_writes(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_writes()
}
}
pub fn access_mapped(&mut self) -> AccessGuardBuffersChain<R> {
AccessGuardBuffersChain {
fst: self.inner.mapped_reads(),
snd: self.inner.mapped_writes(),
}
}
}
impl<'a, R: Resources> Deref for AccessGuard<'a, R> {
type Target = AccessInfo<R>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, R: Resources> Drop for AccessGuard<'a, R> {
fn drop(&mut self) {
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffersChain<'a, R: Resources> {
fst: AccessInfoBuffers<'a, R>,
snd: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffersChain<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.fst.next().or_else(|| self.snd.next())
.map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
} | random_line_split |
|
command.rs | // Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Command Buffer device interface
use std::ops::Deref;
use std::collections::hash_set::{self, HashSet};
use {Resources, IndexType, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ClearColor {
/// Standard floating-point vec4 color
Float([f32; 4]),
/// Integer vector to clear ivec4 targets.
Int([i32; 4]),
/// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready for execution on the device.
#[allow(missing_docs)]
pub trait Buffer<R: Resources>: Send {
/// Reset the command buffer contents, retain the allocated storage
fn reset(&mut self);
/// Bind a pipeline state object
fn bind_pipeline_state(&mut self, R::PipelineStateObject);
/// Bind a complete set of vertex buffers
fn bind_vertex_buffers(&mut self, pso::VertexBufferSet<R>);
/// Bind a complete set of constant buffers
fn bind_constant_buffers(&mut self, &[pso::ConstantBufferParam<R>]);
/// Bind a global constant
fn bind_global_constant(&mut self, shade::Location, shade::UniformValue);
/// Bind a complete set of shader resource views
fn bind_resource_views(&mut self, &[pso::ResourceViewParam<R>]);
/// Bind a complete set of unordered access views
fn bind_unordered_views(&mut self, &[pso::UnorderedViewParam<R>]);
/// Bind a complete set of samplers
fn bind_samplers(&mut self, &[pso::SamplerParam<R>]);
/// Bind a complete set of pixel targets, including multiple
/// colors views and an optional depth/stencil view.
fn bind_pixel_targets(&mut self, pso::PixelTargetSet<R>);
/// Bind an index buffer
fn bind_index(&mut self, R::Buffer, IndexType);
/// Set scissor rectangle
fn set_scissor(&mut self, target::Rect);
/// Set reference values for the blending and stencil front/back
fn set_ref_values(&mut self, state::RefValues);
/// Copy part of a buffer to another
fn copy_buffer(&mut self, src: R::Buffer, dst: R::Buffer,
src_offset_bytes: usize, dst_offset_bytes: usize,
size_bytes: usize);
/// Copy part of a buffer to a texture
fn copy_buffer_to_texture(&mut self,
src: R::Buffer, src_offset_bytes: usize,
dst: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo);
/// Copy part of a texture to a buffer
fn copy_texture_to_buffer(&mut self,
src: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo,
dst: R::Buffer, dst_offset_bytes: usize);
/// Update a vertex/index/uniform buffer
fn update_buffer(&mut self, R::Buffer, data: &[u8], offset: usize);
/// Update a texture
fn update_texture(&mut self, R::Texture, texture::Kind, Option<texture::CubeFace>,
data: &[u8], texture::RawImageInfo);
fn generate_mipmap(&mut self, R::ShaderResourceView);
/// Clear color target
fn clear_color(&mut self, R::RenderTargetView, ClearColor);
fn clear_depth_stencil(&mut self, R::DepthStencilView,
Option<target::Depth>, Option<target::Stencil>);
/// Draw a primitive
fn call_draw(&mut self, VertexCount, VertexCount, Option<InstanceParams>);
/// Draw a primitive with index buffer
fn call_draw_indexed(&mut self, VertexCount, VertexCount, VertexCount, Option<InstanceParams>);
}
macro_rules! impl_clear {
{ $( $ty:ty = $sub:ident[$a:expr, $b:expr, $c:expr, $d:expr], )* } => {
$(
impl From<$ty> for ClearColor {
fn from(v: $ty) -> ClearColor {
ClearColor::$sub([v[$a], v[$b], v[$c], v[$d]])
}
}
)*
}
}
impl_clear! {
[f32; 4] = Float[0, 1, 2, 3],
[f32; 3] = Float[0, 1, 2, 0],
[f32; 2] = Float[0, 1, 0, 0],
[i32; 4] = Int [0, 1, 2, 3],
[i32; 3] = Int [0, 1, 2, 0],
[i32; 2] = Int [0, 1, 0, 0],
[u32; 4] = Uint [0, 1, 2, 3],
[u32; 3] = Uint [0, 1, 2, 0],
[u32; 2] = Uint [0, 1, 0, 0],
}
impl From<f32> for ClearColor {
fn from(v: f32) -> ClearColor {
ClearColor::Float([v, 0.0, 0.0, 0.0])
}
}
impl From<i32> for ClearColor {
fn from(v: i32) -> ClearColor {
ClearColor::Int([v, 0, 0, 0])
}
}
impl From<u32> for ClearColor {
fn from(v: u32) -> ClearColor {
ClearColor::Uint([v, 0, 0, 0])
}
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informations
pub fn new() -> Self {
AccessInfo {
mapped_reads: HashSet::new(),
mapped_writes: HashSet::new(),
}
}
/// Clear access informations
pub fn clear(&mut self) {
self.mapped_reads.clear();
self.mapped_writes.clear();
}
/// Register a buffer read access
pub fn buffer_read(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_reads.insert(buffer.clone());
}
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_writes.insert(buffer.clone());
}
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> AccessInfoBuffers<R> |
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads?
pub fn has_mapped_reads(&self) -> bool {
!self.mapped_reads.is_empty()
}
/// Is there any mapped buffer writes?
pub fn has_mapped_writes(&self) -> bool {
!self.mapped_writes.is_empty()
}
/// Takes all the accesses necessary for submission
pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> {
for buffer in self.mapped_reads().chain(self.mapped_writes()) {
unsafe {
if!buffer.mapping().unwrap().take_access() {
return Err(SubmissionError::AccessOverlap);
}
}
}
Ok(AccessGuard { inner: self })
}
}
#[allow(missing_docs)]
pub type AccessInfoBuffers<'a, R> = hash_set::Iter<'a, handle::RawBuffer<R>>;
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuard<'a, R: Resources> {
inner: &'a AccessInfo<R>,
}
#[allow(missing_docs)]
impl<'a, R: Resources> AccessGuard<'a, R> {
/// Returns the mapped buffers that The GPU will read from,
/// with exclusive acces to their mapping
pub fn access_mapped_reads(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_reads()
}
}
/// Returns the mapped buffers that The GPU will write to,
/// with exclusive acces to their mapping
pub fn access_mapped_writes(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_writes()
}
}
pub fn access_mapped(&mut self) -> AccessGuardBuffersChain<R> {
AccessGuardBuffersChain {
fst: self.inner.mapped_reads(),
snd: self.inner.mapped_writes(),
}
}
}
impl<'a, R: Resources> Deref for AccessGuard<'a, R> {
type Target = AccessInfo<R>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, R: Resources> Drop for AccessGuard<'a, R> {
fn drop(&mut self) {
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffersChain<'a, R: Resources> {
fst: AccessInfoBuffers<'a, R>,
snd: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffersChain<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.fst.next().or_else(|| self.snd.next())
.map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
| {
self.mapped_reads.iter()
} | identifier_body |
command.rs | // Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Command Buffer device interface
use std::ops::Deref;
use std::collections::hash_set::{self, HashSet};
use {Resources, IndexType, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ClearColor {
/// Standard floating-point vec4 color
Float([f32; 4]),
/// Integer vector to clear ivec4 targets.
Int([i32; 4]),
/// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready for execution on the device.
#[allow(missing_docs)]
pub trait Buffer<R: Resources>: Send {
/// Reset the command buffer contents, retain the allocated storage
fn reset(&mut self);
/// Bind a pipeline state object
fn bind_pipeline_state(&mut self, R::PipelineStateObject);
/// Bind a complete set of vertex buffers
fn bind_vertex_buffers(&mut self, pso::VertexBufferSet<R>);
/// Bind a complete set of constant buffers
fn bind_constant_buffers(&mut self, &[pso::ConstantBufferParam<R>]);
/// Bind a global constant
fn bind_global_constant(&mut self, shade::Location, shade::UniformValue);
/// Bind a complete set of shader resource views
fn bind_resource_views(&mut self, &[pso::ResourceViewParam<R>]);
/// Bind a complete set of unordered access views
fn bind_unordered_views(&mut self, &[pso::UnorderedViewParam<R>]);
/// Bind a complete set of samplers
fn bind_samplers(&mut self, &[pso::SamplerParam<R>]);
/// Bind a complete set of pixel targets, including multiple
/// colors views and an optional depth/stencil view.
fn bind_pixel_targets(&mut self, pso::PixelTargetSet<R>);
/// Bind an index buffer
fn bind_index(&mut self, R::Buffer, IndexType);
/// Set scissor rectangle
fn set_scissor(&mut self, target::Rect);
/// Set reference values for the blending and stencil front/back
fn set_ref_values(&mut self, state::RefValues);
/// Copy part of a buffer to another
fn copy_buffer(&mut self, src: R::Buffer, dst: R::Buffer,
src_offset_bytes: usize, dst_offset_bytes: usize,
size_bytes: usize);
/// Copy part of a buffer to a texture
fn copy_buffer_to_texture(&mut self,
src: R::Buffer, src_offset_bytes: usize,
dst: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo);
/// Copy part of a texture to a buffer
fn copy_texture_to_buffer(&mut self,
src: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo,
dst: R::Buffer, dst_offset_bytes: usize);
/// Update a vertex/index/uniform buffer
fn update_buffer(&mut self, R::Buffer, data: &[u8], offset: usize);
/// Update a texture
fn update_texture(&mut self, R::Texture, texture::Kind, Option<texture::CubeFace>,
data: &[u8], texture::RawImageInfo);
fn generate_mipmap(&mut self, R::ShaderResourceView);
/// Clear color target
fn clear_color(&mut self, R::RenderTargetView, ClearColor);
fn clear_depth_stencil(&mut self, R::DepthStencilView,
Option<target::Depth>, Option<target::Stencil>);
/// Draw a primitive
fn call_draw(&mut self, VertexCount, VertexCount, Option<InstanceParams>);
/// Draw a primitive with index buffer
fn call_draw_indexed(&mut self, VertexCount, VertexCount, VertexCount, Option<InstanceParams>);
}
macro_rules! impl_clear {
{ $( $ty:ty = $sub:ident[$a:expr, $b:expr, $c:expr, $d:expr], )* } => {
$(
impl From<$ty> for ClearColor {
fn from(v: $ty) -> ClearColor {
ClearColor::$sub([v[$a], v[$b], v[$c], v[$d]])
}
}
)*
}
}
impl_clear! {
[f32; 4] = Float[0, 1, 2, 3],
[f32; 3] = Float[0, 1, 2, 0],
[f32; 2] = Float[0, 1, 0, 0],
[i32; 4] = Int [0, 1, 2, 3],
[i32; 3] = Int [0, 1, 2, 0],
[i32; 2] = Int [0, 1, 0, 0],
[u32; 4] = Uint [0, 1, 2, 3],
[u32; 3] = Uint [0, 1, 2, 0],
[u32; 2] = Uint [0, 1, 0, 0],
}
impl From<f32> for ClearColor {
fn from(v: f32) -> ClearColor {
ClearColor::Float([v, 0.0, 0.0, 0.0])
}
}
impl From<i32> for ClearColor {
fn from(v: i32) -> ClearColor {
ClearColor::Int([v, 0, 0, 0])
}
}
impl From<u32> for ClearColor {
fn from(v: u32) -> ClearColor {
ClearColor::Uint([v, 0, 0, 0])
}
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informations
pub fn new() -> Self {
AccessInfo {
mapped_reads: HashSet::new(),
mapped_writes: HashSet::new(),
}
}
/// Clear access informations
pub fn clear(&mut self) {
self.mapped_reads.clear();
self.mapped_writes.clear();
}
/// Register a buffer read access
pub fn buffer_read(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_reads.insert(buffer.clone());
}
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_writes.insert(buffer.clone());
}
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> AccessInfoBuffers<R> {
self.mapped_reads.iter()
}
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads?
pub fn has_mapped_reads(&self) -> bool {
!self.mapped_reads.is_empty()
}
/// Is there any mapped buffer writes?
pub fn | (&self) -> bool {
!self.mapped_writes.is_empty()
}
/// Takes all the accesses necessary for submission
pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> {
for buffer in self.mapped_reads().chain(self.mapped_writes()) {
unsafe {
if!buffer.mapping().unwrap().take_access() {
return Err(SubmissionError::AccessOverlap);
}
}
}
Ok(AccessGuard { inner: self })
}
}
#[allow(missing_docs)]
pub type AccessInfoBuffers<'a, R> = hash_set::Iter<'a, handle::RawBuffer<R>>;
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuard<'a, R: Resources> {
inner: &'a AccessInfo<R>,
}
#[allow(missing_docs)]
impl<'a, R: Resources> AccessGuard<'a, R> {
/// Returns the mapped buffers that The GPU will read from,
/// with exclusive acces to their mapping
pub fn access_mapped_reads(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_reads()
}
}
/// Returns the mapped buffers that The GPU will write to,
/// with exclusive acces to their mapping
pub fn access_mapped_writes(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_writes()
}
}
pub fn access_mapped(&mut self) -> AccessGuardBuffersChain<R> {
AccessGuardBuffersChain {
fst: self.inner.mapped_reads(),
snd: self.inner.mapped_writes(),
}
}
}
impl<'a, R: Resources> Deref for AccessGuard<'a, R> {
type Target = AccessInfo<R>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, R: Resources> Drop for AccessGuard<'a, R> {
fn drop(&mut self) {
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffersChain<'a, R: Resources> {
fst: AccessInfoBuffers<'a, R>,
snd: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffersChain<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.fst.next().or_else(|| self.snd.next())
.map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
| has_mapped_writes | identifier_name |
transmission.rs | //! A minimal implementation of rpc client for Tranmission.
use reqwest::header::HeaderValue;
use reqwest::{self, Client, IntoUrl, StatusCode, Url};
use serde_json::Value;
use std::{fmt, result};
pub type Result<T> = result::Result<T, failure::Error>;
| #[fail(display = "failed to get SessionId from header")]
SessionIdNotFound,
#[fail(display = "unexpected status code: {}", status)]
UnexpectedStatus { status: reqwest::StatusCode },
#[fail(display = "the transmission server responded with an error: {}", error)]
ResponseError { error: String },
}
/// A enum that represents the "ids" field in request body.
#[derive(Debug, Clone, Copy)]
pub enum TorrentSelect<'a> {
Ids(&'a [String]),
All,
}
/// A struct that represents the "delete-local-data" field in request body.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DeleteLocalData(pub bool);
/// A structure that represents fields for torrent-get request.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Copy, Serialize)]
pub enum ArgGet {
#[serde(rename = "hashString")]
HashString,
#[serde(rename = "status")]
Status,
}
// https://github.com/serde-rs/serde/issues/497
macro_rules! enum_number_de {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[derive(Debug, Clone, Copy)]
pub enum $name {
$($variant = $value,)*
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = $name;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("positive integer")
}
fn visit_u64<E>(self, value: u64) -> result::Result<$name, E>
where E: serde::de::Error
{
match value {
$( $value => Ok($name::$variant), )*
_ => Err(E::custom(
format!("unknown {} value: {}",
stringify!($name), value))),
}
}
}
deserializer.deserialize_u64(Visitor)
}
}
}
}
/// A enum that represents a torrent status.
enum_number_de!(TorrentStatus {
TorrentIsStopped = 0,
QueuedToCheckFiles = 1,
CheckingFiles = 2,
QueuedToDownload = 3,
Downloading = 4,
QueuedToSeed = 5,
Seeding = 6,
});
/// A struct that represents a "torrents" object in response body.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Deserialize)]
pub struct ResponseGet {
#[serde(rename = "hashString")]
pub hash: String,
pub status: TorrentStatus,
}
/// A struct that represents a "arguments" object in response body.
#[derive(Debug, Clone, Deserialize)]
struct ResponseArgument {
#[serde(default)]
torrents: Vec<ResponseGet>,
}
/// A enum that represents a response status.
#[derive(Debug, Clone, Deserialize)]
pub enum ResponseStatus {
#[serde(rename = "success")]
Success,
Error(String),
}
/// A struct that represents a response body.
#[derive(Debug, Clone, Deserialize)]
struct Response {
arguments: ResponseArgument,
result: ResponseStatus,
}
/// RPC username and password.
#[derive(Debug)]
struct User {
name: String,
password: String,
}
/// Torrent client.
#[derive(Debug)]
pub struct Transmission {
url: Url,
user: Option<User>,
sid: HeaderValue,
http_client: Client,
}
macro_rules! requ_json {
($var:ident, $method:tt $(,$argstring:tt : $argname:ident)*) => {
match $var {
TorrentSelect::Ids(vec) => json!({"arguments":{$($argstring:$argname,)* "ids":vec}, "method":$method}),
TorrentSelect::All => json!({"arguments":{$($argstring:$argname,)*}, "method":$method}),
}
}
}
macro_rules! empty_response {
($name:ident, $method:tt $(,$argname:ident : $argtype:ident : $argstring:tt)*) => {
pub fn $name(&self, t: TorrentSelect<'_> $(,$argname:$argtype)*) -> Result<()> {
match self.request(&requ_json!(t,$method $(,$argstring:$argname)*))?.json::<Response>()?.result {
ResponseStatus::Success => Ok(()),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError{ error }.into()),
}
}
}
}
impl Transmission {
/// Crate new `Transmission` struct.
///
/// Fails if a `url` can not be parsed or if HTTP client fails.
pub fn new<U>(url: U, user: Option<(String, String)>) -> Result<Self>
where
U: IntoUrl,
{
let user = if let Some((n, p)) = user {
Some(User {
name: n,
password: p,
})
} else {
None
};
let url = url.into_url()?;
let http_client = Client::new();
let sid = http_client
.get(url.clone())
.send()?
.headers()
.get("X-Transmission-Session-Id")
.ok_or(TransmissionError::SessionIdNotFound)?
.clone();
Ok(Self {
url,
user,
sid,
http_client,
})
}
pub fn url(&self) -> &str {
self.url.as_str()
}
/// Make a request to the Transmission.
///
/// If the response status is 200, then return a response.
/// If the response status is 409, then try again with a new SID.
/// Otherwise return an error.
fn request(&self, json: &Value) -> Result<reqwest::Response> {
let resp = self
.http_client
.post(self.url.clone())
.json(json)
.header("X-Transmission-Session-Id", self.sid.clone())
.send()?;
match resp.status() {
StatusCode::OK => Ok(resp),
_ => Err(TransmissionError::UnexpectedStatus {
status: resp.status(),
}
.into()),
}
}
/// Start a list of torrents in the Transmission.
empty_response!(start, "torrent-start");
/// Stop a list of torrents in the Transmission.
empty_response!(stop, "torrent-stop");
/// Remove a list of torrents in the Transmission.
empty_response!(remove, "torrent-remove", d:DeleteLocalData:"delete-local-data");
/// Get a list of torrents from the Transmission.
pub fn get(&self, t: TorrentSelect<'_>, f: &[ArgGet]) -> Result<Vec<ResponseGet>> {
let responce = self
.request(&requ_json!(t, "torrent-get", "fields": f))?
.json::<Response>()?;
match responce.result {
ResponseStatus::Success => Ok(responce.arguments.torrents),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError { error }.into()),
}
}
} | #[derive(Debug, Fail)]
enum TransmissionError { | random_line_split |
transmission.rs | //! A minimal implementation of rpc client for Tranmission.
use reqwest::header::HeaderValue;
use reqwest::{self, Client, IntoUrl, StatusCode, Url};
use serde_json::Value;
use std::{fmt, result};
pub type Result<T> = result::Result<T, failure::Error>;
#[derive(Debug, Fail)]
enum TransmissionError {
#[fail(display = "failed to get SessionId from header")]
SessionIdNotFound,
#[fail(display = "unexpected status code: {}", status)]
UnexpectedStatus { status: reqwest::StatusCode },
#[fail(display = "the transmission server responded with an error: {}", error)]
ResponseError { error: String },
}
/// A enum that represents the "ids" field in request body.
#[derive(Debug, Clone, Copy)]
pub enum TorrentSelect<'a> {
Ids(&'a [String]),
All,
}
/// A struct that represents the "delete-local-data" field in request body.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DeleteLocalData(pub bool);
/// A structure that represents fields for torrent-get request.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Copy, Serialize)]
pub enum ArgGet {
#[serde(rename = "hashString")]
HashString,
#[serde(rename = "status")]
Status,
}
// https://github.com/serde-rs/serde/issues/497
macro_rules! enum_number_de {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[derive(Debug, Clone, Copy)]
pub enum $name {
$($variant = $value,)*
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = $name;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("positive integer")
}
fn visit_u64<E>(self, value: u64) -> result::Result<$name, E>
where E: serde::de::Error
{
match value {
$( $value => Ok($name::$variant), )*
_ => Err(E::custom(
format!("unknown {} value: {}",
stringify!($name), value))),
}
}
}
deserializer.deserialize_u64(Visitor)
}
}
}
}
/// A enum that represents a torrent status.
enum_number_de!(TorrentStatus {
TorrentIsStopped = 0,
QueuedToCheckFiles = 1,
CheckingFiles = 2,
QueuedToDownload = 3,
Downloading = 4,
QueuedToSeed = 5,
Seeding = 6,
});
/// A struct that represents a "torrents" object in response body.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Deserialize)]
pub struct ResponseGet {
#[serde(rename = "hashString")]
pub hash: String,
pub status: TorrentStatus,
}
/// A struct that represents a "arguments" object in response body.
#[derive(Debug, Clone, Deserialize)]
struct ResponseArgument {
#[serde(default)]
torrents: Vec<ResponseGet>,
}
/// A enum that represents a response status.
#[derive(Debug, Clone, Deserialize)]
pub enum ResponseStatus {
#[serde(rename = "success")]
Success,
Error(String),
}
/// A struct that represents a response body.
#[derive(Debug, Clone, Deserialize)]
struct Response {
arguments: ResponseArgument,
result: ResponseStatus,
}
/// RPC username and password.
#[derive(Debug)]
struct User {
name: String,
password: String,
}
/// Torrent client.
#[derive(Debug)]
pub struct Transmission {
url: Url,
user: Option<User>,
sid: HeaderValue,
http_client: Client,
}
macro_rules! requ_json {
($var:ident, $method:tt $(,$argstring:tt : $argname:ident)*) => {
match $var {
TorrentSelect::Ids(vec) => json!({"arguments":{$($argstring:$argname,)* "ids":vec}, "method":$method}),
TorrentSelect::All => json!({"arguments":{$($argstring:$argname,)*}, "method":$method}),
}
}
}
macro_rules! empty_response {
($name:ident, $method:tt $(,$argname:ident : $argtype:ident : $argstring:tt)*) => {
pub fn $name(&self, t: TorrentSelect<'_> $(,$argname:$argtype)*) -> Result<()> {
match self.request(&requ_json!(t,$method $(,$argstring:$argname)*))?.json::<Response>()?.result {
ResponseStatus::Success => Ok(()),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError{ error }.into()),
}
}
}
}
impl Transmission {
/// Crate new `Transmission` struct.
///
/// Fails if a `url` can not be parsed or if HTTP client fails.
pub fn new<U>(url: U, user: Option<(String, String)>) -> Result<Self>
where
U: IntoUrl,
{
let user = if let Some((n, p)) = user {
Some(User {
name: n,
password: p,
})
} else | ;
let url = url.into_url()?;
let http_client = Client::new();
let sid = http_client
.get(url.clone())
.send()?
.headers()
.get("X-Transmission-Session-Id")
.ok_or(TransmissionError::SessionIdNotFound)?
.clone();
Ok(Self {
url,
user,
sid,
http_client,
})
}
pub fn url(&self) -> &str {
self.url.as_str()
}
/// Make a request to the Transmission.
///
/// If the response status is 200, then return a response.
/// If the response status is 409, then try again with a new SID.
/// Otherwise return an error.
fn request(&self, json: &Value) -> Result<reqwest::Response> {
let resp = self
.http_client
.post(self.url.clone())
.json(json)
.header("X-Transmission-Session-Id", self.sid.clone())
.send()?;
match resp.status() {
StatusCode::OK => Ok(resp),
_ => Err(TransmissionError::UnexpectedStatus {
status: resp.status(),
}
.into()),
}
}
/// Start a list of torrents in the Transmission.
empty_response!(start, "torrent-start");
/// Stop a list of torrents in the Transmission.
empty_response!(stop, "torrent-stop");
/// Remove a list of torrents in the Transmission.
empty_response!(remove, "torrent-remove", d:DeleteLocalData:"delete-local-data");
/// Get a list of torrents from the Transmission.
pub fn get(&self, t: TorrentSelect<'_>, f: &[ArgGet]) -> Result<Vec<ResponseGet>> {
let responce = self
.request(&requ_json!(t, "torrent-get", "fields": f))?
.json::<Response>()?;
match responce.result {
ResponseStatus::Success => Ok(responce.arguments.torrents),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError { error }.into()),
}
}
}
| {
None
} | conditional_block |
transmission.rs | //! A minimal implementation of rpc client for Tranmission.
use reqwest::header::HeaderValue;
use reqwest::{self, Client, IntoUrl, StatusCode, Url};
use serde_json::Value;
use std::{fmt, result};
pub type Result<T> = result::Result<T, failure::Error>;
#[derive(Debug, Fail)]
enum TransmissionError {
#[fail(display = "failed to get SessionId from header")]
SessionIdNotFound,
#[fail(display = "unexpected status code: {}", status)]
UnexpectedStatus { status: reqwest::StatusCode },
#[fail(display = "the transmission server responded with an error: {}", error)]
ResponseError { error: String },
}
/// A enum that represents the "ids" field in request body.
#[derive(Debug, Clone, Copy)]
pub enum TorrentSelect<'a> {
Ids(&'a [String]),
All,
}
/// A struct that represents the "delete-local-data" field in request body.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DeleteLocalData(pub bool);
/// A structure that represents fields for torrent-get request.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Copy, Serialize)]
pub enum ArgGet {
#[serde(rename = "hashString")]
HashString,
#[serde(rename = "status")]
Status,
}
// https://github.com/serde-rs/serde/issues/497
macro_rules! enum_number_de {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[derive(Debug, Clone, Copy)]
pub enum $name {
$($variant = $value,)*
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = $name;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("positive integer")
}
fn visit_u64<E>(self, value: u64) -> result::Result<$name, E>
where E: serde::de::Error
{
match value {
$( $value => Ok($name::$variant), )*
_ => Err(E::custom(
format!("unknown {} value: {}",
stringify!($name), value))),
}
}
}
deserializer.deserialize_u64(Visitor)
}
}
}
}
/// A enum that represents a torrent status.
enum_number_de!(TorrentStatus {
TorrentIsStopped = 0,
QueuedToCheckFiles = 1,
CheckingFiles = 2,
QueuedToDownload = 3,
Downloading = 4,
QueuedToSeed = 5,
Seeding = 6,
});
/// A struct that represents a "torrents" object in response body.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Deserialize)]
pub struct ResponseGet {
#[serde(rename = "hashString")]
pub hash: String,
pub status: TorrentStatus,
}
/// A struct that represents a "arguments" object in response body.
#[derive(Debug, Clone, Deserialize)]
struct ResponseArgument {
#[serde(default)]
torrents: Vec<ResponseGet>,
}
/// A enum that represents a response status.
#[derive(Debug, Clone, Deserialize)]
pub enum ResponseStatus {
#[serde(rename = "success")]
Success,
Error(String),
}
/// A struct that represents a response body.
#[derive(Debug, Clone, Deserialize)]
struct Response {
arguments: ResponseArgument,
result: ResponseStatus,
}
/// RPC username and password.
#[derive(Debug)]
struct User {
name: String,
password: String,
}
/// Torrent client.
#[derive(Debug)]
pub struct Transmission {
url: Url,
user: Option<User>,
sid: HeaderValue,
http_client: Client,
}
macro_rules! requ_json {
($var:ident, $method:tt $(,$argstring:tt : $argname:ident)*) => {
match $var {
TorrentSelect::Ids(vec) => json!({"arguments":{$($argstring:$argname,)* "ids":vec}, "method":$method}),
TorrentSelect::All => json!({"arguments":{$($argstring:$argname,)*}, "method":$method}),
}
}
}
macro_rules! empty_response {
($name:ident, $method:tt $(,$argname:ident : $argtype:ident : $argstring:tt)*) => {
pub fn $name(&self, t: TorrentSelect<'_> $(,$argname:$argtype)*) -> Result<()> {
match self.request(&requ_json!(t,$method $(,$argstring:$argname)*))?.json::<Response>()?.result {
ResponseStatus::Success => Ok(()),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError{ error }.into()),
}
}
}
}
impl Transmission {
/// Crate new `Transmission` struct.
///
/// Fails if a `url` can not be parsed or if HTTP client fails.
pub fn | <U>(url: U, user: Option<(String, String)>) -> Result<Self>
where
U: IntoUrl,
{
let user = if let Some((n, p)) = user {
Some(User {
name: n,
password: p,
})
} else {
None
};
let url = url.into_url()?;
let http_client = Client::new();
let sid = http_client
.get(url.clone())
.send()?
.headers()
.get("X-Transmission-Session-Id")
.ok_or(TransmissionError::SessionIdNotFound)?
.clone();
Ok(Self {
url,
user,
sid,
http_client,
})
}
pub fn url(&self) -> &str {
self.url.as_str()
}
/// Make a request to the Transmission.
///
/// If the response status is 200, then return a response.
/// If the response status is 409, then try again with a new SID.
/// Otherwise return an error.
fn request(&self, json: &Value) -> Result<reqwest::Response> {
let resp = self
.http_client
.post(self.url.clone())
.json(json)
.header("X-Transmission-Session-Id", self.sid.clone())
.send()?;
match resp.status() {
StatusCode::OK => Ok(resp),
_ => Err(TransmissionError::UnexpectedStatus {
status: resp.status(),
}
.into()),
}
}
/// Start a list of torrents in the Transmission.
empty_response!(start, "torrent-start");
/// Stop a list of torrents in the Transmission.
empty_response!(stop, "torrent-stop");
/// Remove a list of torrents in the Transmission.
empty_response!(remove, "torrent-remove", d:DeleteLocalData:"delete-local-data");
/// Get a list of torrents from the Transmission.
pub fn get(&self, t: TorrentSelect<'_>, f: &[ArgGet]) -> Result<Vec<ResponseGet>> {
let responce = self
.request(&requ_json!(t, "torrent-get", "fields": f))?
.json::<Response>()?;
match responce.result {
ResponseStatus::Success => Ok(responce.arguments.torrents),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError { error }.into()),
}
}
}
| new | identifier_name |
main.rs | // Author: Alex Chernyakhovsky ([email protected])
// TODO(achernya): Per the documentation on doc.rust-lang.org, std::io
// is not yet ready, so use old_io until 1.0-final.
#![feature(old_io)]
// std::env contains a lot of nice functions that otherwise would
// require std::os to use; std::os has lots of deprecated functions.
#![feature(env)]
// TODO(achernya): Remove this feature when std::env moves over to
// std::path.
#![feature(old_path)]
use std::env;
use std::old_io as io;
// println_stderr is like println, but to stderr.
macro_rules! println_stderr(
($($arg:tt)*) => (
match writeln!(&mut io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
)
);
// ShellCommand is a trait that defines a runnable POSIX shell
// command. An implementation is an abstract representation of shell
// commands such as simple invocations, invocations with redirection,
// and even shell pipelines.
trait ShellCommand {
fn run(&self);
}
fn shell_loop() {
let mut stdin = io::stdin();
loop {
print!("$ ");
let line = stdin.read_line();
match line {
Ok(expr) => handle_command(&expr),
Err(_) => break,
}
}
}
fn handle_command(user_expr: &str) {
// Clean up the string by removing the newline at the end
let expr = user_expr.trim_matches('\n');
let components: Vec<&str> = expr.split(' ').collect();
if builtins(&components) {
return;
}
}
fn builtins(command: &Vec<&str>) -> bool {
match command[0] {
"cd" => cd(command),
"pwd" => pwd(),
_ => return false,
}
true
}
fn cd(command: &Vec<&str>) {
// cd is the "change directory" command. It can take either 0 or 1
// arguments. If given no arguments, then the $HOME directory is
// chosen.
let dir: Option<Path> = match command.len() {
0 => panic!("invalid cd invocation"),
1 => env::home_dir(),
_ => Some(Path::new(command[1])) | let directory = dir.unwrap();
let result = env::set_current_dir(&directory);
match result {
Err(err) => {
println_stderr!("cd: {}: {}", directory.display(), err);
},
_ => {},
}
}
fn pwd() {
let p = env::current_dir().unwrap_or(Path::new("/"));
println!("{}", p.display());
}
fn main() {
// TODO(achernya): is there any initialization we want to do
// before we enter the shell loop?
shell_loop();
} | };
if dir.is_none() {
println_stderr!("cd: no directory to change to");
return;
} | random_line_split |
main.rs | // Author: Alex Chernyakhovsky ([email protected])
// TODO(achernya): Per the documentation on doc.rust-lang.org, std::io
// is not yet ready, so use old_io until 1.0-final.
#![feature(old_io)]
// std::env contains a lot of nice functions that otherwise would
// require std::os to use; std::os has lots of deprecated functions.
#![feature(env)]
// TODO(achernya): Remove this feature when std::env moves over to
// std::path.
#![feature(old_path)]
use std::env;
use std::old_io as io;
// println_stderr is like println, but to stderr.
macro_rules! println_stderr(
($($arg:tt)*) => (
match writeln!(&mut io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
)
);
// ShellCommand is a trait that defines a runnable POSIX shell
// command. An implementation is an abstract representation of shell
// commands such as simple invocations, invocations with redirection,
// and even shell pipelines.
trait ShellCommand {
fn run(&self);
}
fn shell_loop() {
let mut stdin = io::stdin();
loop {
print!("$ ");
let line = stdin.read_line();
match line {
Ok(expr) => handle_command(&expr),
Err(_) => break,
}
}
}
fn handle_command(user_expr: &str) {
// Clean up the string by removing the newline at the end
let expr = user_expr.trim_matches('\n');
let components: Vec<&str> = expr.split(' ').collect();
if builtins(&components) {
return;
}
}
fn | (command: &Vec<&str>) -> bool {
match command[0] {
"cd" => cd(command),
"pwd" => pwd(),
_ => return false,
}
true
}
fn cd(command: &Vec<&str>) {
// cd is the "change directory" command. It can take either 0 or 1
// arguments. If given no arguments, then the $HOME directory is
// chosen.
let dir: Option<Path> = match command.len() {
0 => panic!("invalid cd invocation"),
1 => env::home_dir(),
_ => Some(Path::new(command[1]))
};
if dir.is_none() {
println_stderr!("cd: no directory to change to");
return;
}
let directory = dir.unwrap();
let result = env::set_current_dir(&directory);
match result {
Err(err) => {
println_stderr!("cd: {}: {}", directory.display(), err);
},
_ => {},
}
}
fn pwd() {
let p = env::current_dir().unwrap_or(Path::new("/"));
println!("{}", p.display());
}
fn main() {
// TODO(achernya): is there any initialization we want to do
// before we enter the shell loop?
shell_loop();
}
| builtins | identifier_name |
main.rs | // Author: Alex Chernyakhovsky ([email protected])
// TODO(achernya): Per the documentation on doc.rust-lang.org, std::io
// is not yet ready, so use old_io until 1.0-final.
#![feature(old_io)]
// std::env contains a lot of nice functions that otherwise would
// require std::os to use; std::os has lots of deprecated functions.
#![feature(env)]
// TODO(achernya): Remove this feature when std::env moves over to
// std::path.
#![feature(old_path)]
use std::env;
use std::old_io as io;
// println_stderr is like println, but to stderr.
macro_rules! println_stderr(
($($arg:tt)*) => (
match writeln!(&mut io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr: {}", x),
}
)
);
// ShellCommand is a trait that defines a runnable POSIX shell
// command. An implementation is an abstract representation of shell
// commands such as simple invocations, invocations with redirection,
// and even shell pipelines.
trait ShellCommand {
fn run(&self);
}
fn shell_loop() {
let mut stdin = io::stdin();
loop {
print!("$ ");
let line = stdin.read_line();
match line {
Ok(expr) => handle_command(&expr),
Err(_) => break,
}
}
}
fn handle_command(user_expr: &str) |
fn builtins(command: &Vec<&str>) -> bool {
match command[0] {
"cd" => cd(command),
"pwd" => pwd(),
_ => return false,
}
true
}
fn cd(command: &Vec<&str>) {
// cd is the "change directory" command. It can take either 0 or 1
// arguments. If given no arguments, then the $HOME directory is
// chosen.
let dir: Option<Path> = match command.len() {
0 => panic!("invalid cd invocation"),
1 => env::home_dir(),
_ => Some(Path::new(command[1]))
};
if dir.is_none() {
println_stderr!("cd: no directory to change to");
return;
}
let directory = dir.unwrap();
let result = env::set_current_dir(&directory);
match result {
Err(err) => {
println_stderr!("cd: {}: {}", directory.display(), err);
},
_ => {},
}
}
fn pwd() {
let p = env::current_dir().unwrap_or(Path::new("/"));
println!("{}", p.display());
}
fn main() {
// TODO(achernya): is there any initialization we want to do
// before we enter the shell loop?
shell_loop();
}
| {
// Clean up the string by removing the newline at the end
let expr = user_expr.trim_matches('\n');
let components: Vec<&str> = expr.split(' ').collect();
if builtins(&components) {
return;
}
} | identifier_body |
file_loader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use about_loader;
use mime_classifier::MIMEClassifier;
use mime_guess::guess_mime_type;
use net_traits::ProgressMsg::{Done, Payload};
use net_traits::{LoadConsumer, LoadData, Metadata};
use resource_thread::{CancellationListener, ProgressSender};
use resource_thread::{send_error, start_sending_sniffed_opt};
use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use url::Url;
use util::thread::spawn_named;
static READ_SIZE: usize = 8192;
enum ReadStatus {
Partial(Vec<u8>),
EOF,
}
enum LoadResult {
Cancelled,
Finished,
}
fn read_block(reader: &mut File) -> Result<ReadStatus, String> {
let mut buf = vec![0; READ_SIZE];
match reader.read(&mut buf) {
Ok(0) => Ok(ReadStatus::EOF),
Ok(n) => {
buf.truncate(n);
Ok(ReadStatus::Partial(buf))
}
Err(e) => Err(e.description().to_owned()),
}
}
fn read_all(reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener)
-> Result<LoadResult, String> {
loop {
if cancel_listener.is_cancelled() {
let _ = progress_chan.send(Done(Err("load cancelled".to_owned())));
return Ok(LoadResult::Cancelled);
}
match try!(read_block(reader)) {
ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(),
ReadStatus::EOF => return Ok(LoadResult::Finished),
}
}
}
fn get_progress_chan(load_data: LoadData, file_path: PathBuf,
senders: LoadConsumer, classifier: Arc<MIMEClassifier>, buf: &[u8])
-> Result<ProgressSender, ()> {
let mut metadata = Metadata::default(load_data.url);
let mime_type = guess_mime_type(file_path.as_path());
metadata.set_content_type(Some(&mime_type));
return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context);
}
pub fn factory(load_data: LoadData,
senders: LoadConsumer,
classifier: Arc<MIMEClassifier>, | cancel_listener: CancellationListener) {
assert!(&*load_data.url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let file_path: Result<PathBuf, ()> = load_data.url.to_file_path();
match file_path {
Ok(file_path) => {
match File::open(&file_path) {
Ok(ref mut reader) => {
if cancel_listener.is_cancelled() {
if let Ok(progress_chan) = get_progress_chan(load_data, file_path,
senders, classifier, &[]) {
let _ = progress_chan.send(Done(Err("load cancelled".to_owned())));
}
return;
}
match read_block(reader) {
Ok(ReadStatus::Partial(buf)) => {
let progress_chan = get_progress_chan(load_data, file_path,
senders, classifier, &buf).ok().unwrap();
progress_chan.send(Payload(buf)).unwrap();
let read_result = read_all(reader, &progress_chan, &cancel_listener);
if let Ok(load_result) = read_result {
match load_result {
LoadResult::Cancelled => return,
LoadResult::Finished => progress_chan.send(Done(Ok(()))).unwrap(),
}
}
}
Ok(ReadStatus::EOF) => {
if let Ok(chan) = get_progress_chan(load_data, file_path,
senders, classifier, &[]) {
let _ = chan.send(Done(Ok(())));
}
}
Err(e) => {
send_error(load_data.url, e, senders);
}
};
}
Err(_) => {
// this should be one of the three errors listed in
// http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open
// but, we'll go for a "file not found!"
let url = Url::parse("about:not-found").unwrap();
let load_data_404 = LoadData::new(load_data.context, url, None);
about_loader::factory(load_data_404, senders, classifier, cancel_listener)
}
}
}
Err(_) => {
send_error(load_data.url, "Could not parse path".to_owned(), senders);
}
}
});
} | random_line_split |
|
file_loader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use about_loader;
use mime_classifier::MIMEClassifier;
use mime_guess::guess_mime_type;
use net_traits::ProgressMsg::{Done, Payload};
use net_traits::{LoadConsumer, LoadData, Metadata};
use resource_thread::{CancellationListener, ProgressSender};
use resource_thread::{send_error, start_sending_sniffed_opt};
use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use url::Url;
use util::thread::spawn_named;
static READ_SIZE: usize = 8192;
enum ReadStatus {
Partial(Vec<u8>),
EOF,
}
enum LoadResult {
Cancelled,
Finished,
}
fn read_block(reader: &mut File) -> Result<ReadStatus, String> {
let mut buf = vec![0; READ_SIZE];
match reader.read(&mut buf) {
Ok(0) => Ok(ReadStatus::EOF),
Ok(n) => {
buf.truncate(n);
Ok(ReadStatus::Partial(buf))
}
Err(e) => Err(e.description().to_owned()),
}
}
fn read_all(reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener)
-> Result<LoadResult, String> {
loop {
if cancel_listener.is_cancelled() {
let _ = progress_chan.send(Done(Err("load cancelled".to_owned())));
return Ok(LoadResult::Cancelled);
}
match try!(read_block(reader)) {
ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(),
ReadStatus::EOF => return Ok(LoadResult::Finished),
}
}
}
fn get_progress_chan(load_data: LoadData, file_path: PathBuf,
senders: LoadConsumer, classifier: Arc<MIMEClassifier>, buf: &[u8])
-> Result<ProgressSender, ()> |
pub fn factory(load_data: LoadData,
senders: LoadConsumer,
classifier: Arc<MIMEClassifier>,
cancel_listener: CancellationListener) {
assert!(&*load_data.url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let file_path: Result<PathBuf, ()> = load_data.url.to_file_path();
match file_path {
Ok(file_path) => {
match File::open(&file_path) {
Ok(ref mut reader) => {
if cancel_listener.is_cancelled() {
if let Ok(progress_chan) = get_progress_chan(load_data, file_path,
senders, classifier, &[]) {
let _ = progress_chan.send(Done(Err("load cancelled".to_owned())));
}
return;
}
match read_block(reader) {
Ok(ReadStatus::Partial(buf)) => {
let progress_chan = get_progress_chan(load_data, file_path,
senders, classifier, &buf).ok().unwrap();
progress_chan.send(Payload(buf)).unwrap();
let read_result = read_all(reader, &progress_chan, &cancel_listener);
if let Ok(load_result) = read_result {
match load_result {
LoadResult::Cancelled => return,
LoadResult::Finished => progress_chan.send(Done(Ok(()))).unwrap(),
}
}
}
Ok(ReadStatus::EOF) => {
if let Ok(chan) = get_progress_chan(load_data, file_path,
senders, classifier, &[]) {
let _ = chan.send(Done(Ok(())));
}
}
Err(e) => {
send_error(load_data.url, e, senders);
}
};
}
Err(_) => {
// this should be one of the three errors listed in
// http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open
// but, we'll go for a "file not found!"
let url = Url::parse("about:not-found").unwrap();
let load_data_404 = LoadData::new(load_data.context, url, None);
about_loader::factory(load_data_404, senders, classifier, cancel_listener)
}
}
}
Err(_) => {
send_error(load_data.url, "Could not parse path".to_owned(), senders);
}
}
});
}
| {
let mut metadata = Metadata::default(load_data.url);
let mime_type = guess_mime_type(file_path.as_path());
metadata.set_content_type(Some(&mime_type));
return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context);
} | identifier_body |
file_loader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use about_loader;
use mime_classifier::MIMEClassifier;
use mime_guess::guess_mime_type;
use net_traits::ProgressMsg::{Done, Payload};
use net_traits::{LoadConsumer, LoadData, Metadata};
use resource_thread::{CancellationListener, ProgressSender};
use resource_thread::{send_error, start_sending_sniffed_opt};
use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use url::Url;
use util::thread::spawn_named;
static READ_SIZE: usize = 8192;
enum ReadStatus {
Partial(Vec<u8>),
EOF,
}
enum LoadResult {
Cancelled,
Finished,
}
fn read_block(reader: &mut File) -> Result<ReadStatus, String> {
let mut buf = vec![0; READ_SIZE];
match reader.read(&mut buf) {
Ok(0) => Ok(ReadStatus::EOF),
Ok(n) => {
buf.truncate(n);
Ok(ReadStatus::Partial(buf))
}
Err(e) => Err(e.description().to_owned()),
}
}
fn | (reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener)
-> Result<LoadResult, String> {
loop {
if cancel_listener.is_cancelled() {
let _ = progress_chan.send(Done(Err("load cancelled".to_owned())));
return Ok(LoadResult::Cancelled);
}
match try!(read_block(reader)) {
ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(),
ReadStatus::EOF => return Ok(LoadResult::Finished),
}
}
}
fn get_progress_chan(load_data: LoadData, file_path: PathBuf,
senders: LoadConsumer, classifier: Arc<MIMEClassifier>, buf: &[u8])
-> Result<ProgressSender, ()> {
let mut metadata = Metadata::default(load_data.url);
let mime_type = guess_mime_type(file_path.as_path());
metadata.set_content_type(Some(&mime_type));
return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context);
}
pub fn factory(load_data: LoadData,
senders: LoadConsumer,
classifier: Arc<MIMEClassifier>,
cancel_listener: CancellationListener) {
assert!(&*load_data.url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let file_path: Result<PathBuf, ()> = load_data.url.to_file_path();
match file_path {
Ok(file_path) => {
match File::open(&file_path) {
Ok(ref mut reader) => {
if cancel_listener.is_cancelled() {
if let Ok(progress_chan) = get_progress_chan(load_data, file_path,
senders, classifier, &[]) {
let _ = progress_chan.send(Done(Err("load cancelled".to_owned())));
}
return;
}
match read_block(reader) {
Ok(ReadStatus::Partial(buf)) => {
let progress_chan = get_progress_chan(load_data, file_path,
senders, classifier, &buf).ok().unwrap();
progress_chan.send(Payload(buf)).unwrap();
let read_result = read_all(reader, &progress_chan, &cancel_listener);
if let Ok(load_result) = read_result {
match load_result {
LoadResult::Cancelled => return,
LoadResult::Finished => progress_chan.send(Done(Ok(()))).unwrap(),
}
}
}
Ok(ReadStatus::EOF) => {
if let Ok(chan) = get_progress_chan(load_data, file_path,
senders, classifier, &[]) {
let _ = chan.send(Done(Ok(())));
}
}
Err(e) => {
send_error(load_data.url, e, senders);
}
};
}
Err(_) => {
// this should be one of the three errors listed in
// http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open
// but, we'll go for a "file not found!"
let url = Url::parse("about:not-found").unwrap();
let load_data_404 = LoadData::new(load_data.context, url, None);
about_loader::factory(load_data_404, senders, classifier, cancel_listener)
}
}
}
Err(_) => {
send_error(load_data.url, "Could not parse path".to_owned(), senders);
}
}
});
}
| read_all | identifier_name |
gpio.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::TransportWrapper;
use opentitanlib::io::gpio::{PinMode, PullMode};
use opentitanlib::transport::Capability;
#[derive(Debug, StructOpt)]
/// Reads a GPIO pin.
pub struct GpioRead {
#[structopt(name = "PIN", help = "The GPIO pin to read")]
pub pin: String,
}
#[derive(serde::Serialize)]
pub struct GpioReadResult {
pub pin: String,
pub value: bool,
}
impl CommandDispatch for GpioRead {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::GPIO).ok()?;
let gpio_pin = transport.gpio_pin(&self.pin)?;
let value = gpio_pin.read()?;
Ok(Some(Box::new(GpioReadResult {
pin: self.pin.clone(),
value,
})))
}
}
#[derive(Debug, StructOpt)]
/// Writes a GPIO pin.
pub struct GpioWrite {
#[structopt(name = "PIN", help = "The GPIO pin to write")]
pub pin: String,
#[structopt(
name = "VALUE",
parse(try_from_str),
help = "The value to write to the pin"
)]
pub value: bool,
}
impl CommandDispatch for GpioWrite {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::GPIO).ok()?;
let gpio_pin = transport.gpio_pin(&self.pin)?;
gpio_pin.write(self.value)?;
Ok(None)
}
}
#[derive(Debug, StructOpt)]
/// Set the I/O mode of a GPIO pin (Input/OpenDrain/PushPull).
pub struct GpioSetMode {
#[structopt(name = "PIN", help = "The GPIO pin to modify")]
pub pin: String,
#[structopt(
name = "MODE",
possible_values = &PinMode::variants(),
case_insensitive=true,
help = "The I/O mode of the pin"
)]
pub mode: PinMode,
}
impl CommandDispatch for GpioSetMode {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::GPIO).ok()?;
let gpio_pin = transport.gpio_pin(&self.pin)?;
gpio_pin.set_mode(self.mode)?;
Ok(None)
}
}
#[derive(Debug, StructOpt)]
/// Set the I/O weak pull mode of a GPIO pin (PullUp/PullDown/None).
pub struct GpioSetPullMode {
#[structopt(name = "PIN", help = "The GPIO pin to modify")]
pub pin: String,
#[structopt(
name = "PULLMODE",
possible_values = &PullMode::variants(),
case_insensitive=true,
help = "The weak pull mode of the pin"
)]
pub pull_mode: PullMode,
}
impl CommandDispatch for GpioSetPullMode {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::GPIO).ok()?;
let gpio_pin = transport.gpio_pin(&self.pin)?;
gpio_pin.set_pull_mode(self.pull_mode)?;
Ok(None)
} | Read(GpioRead),
Write(GpioWrite),
SetMode(GpioSetMode),
SetPullMode(GpioSetPullMode),
} | }
/// Commands for manipulating GPIO pins.
#[derive(Debug, StructOpt, CommandDispatch)]
pub enum GpioCommand { | random_line_split |
gpio.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::TransportWrapper;
use opentitanlib::io::gpio::{PinMode, PullMode};
use opentitanlib::transport::Capability;
#[derive(Debug, StructOpt)]
/// Reads a GPIO pin.
pub struct GpioRead {
#[structopt(name = "PIN", help = "The GPIO pin to read")]
pub pin: String,
}
#[derive(serde::Serialize)]
pub struct GpioReadResult {
pub pin: String,
pub value: bool,
}
impl CommandDispatch for GpioRead {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::GPIO).ok()?;
let gpio_pin = transport.gpio_pin(&self.pin)?;
let value = gpio_pin.read()?;
Ok(Some(Box::new(GpioReadResult {
pin: self.pin.clone(),
value,
})))
}
}
#[derive(Debug, StructOpt)]
/// Writes a GPIO pin.
pub struct GpioWrite {
#[structopt(name = "PIN", help = "The GPIO pin to write")]
pub pin: String,
#[structopt(
name = "VALUE",
parse(try_from_str),
help = "The value to write to the pin"
)]
pub value: bool,
}
impl CommandDispatch for GpioWrite {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::GPIO).ok()?;
let gpio_pin = transport.gpio_pin(&self.pin)?;
gpio_pin.write(self.value)?;
Ok(None)
}
}
#[derive(Debug, StructOpt)]
/// Set the I/O mode of a GPIO pin (Input/OpenDrain/PushPull).
pub struct GpioSetMode {
#[structopt(name = "PIN", help = "The GPIO pin to modify")]
pub pin: String,
#[structopt(
name = "MODE",
possible_values = &PinMode::variants(),
case_insensitive=true,
help = "The I/O mode of the pin"
)]
pub mode: PinMode,
}
impl CommandDispatch for GpioSetMode {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::GPIO).ok()?;
let gpio_pin = transport.gpio_pin(&self.pin)?;
gpio_pin.set_mode(self.mode)?;
Ok(None)
}
}
#[derive(Debug, StructOpt)]
/// Set the I/O weak pull mode of a GPIO pin (PullUp/PullDown/None).
pub struct | {
#[structopt(name = "PIN", help = "The GPIO pin to modify")]
pub pin: String,
#[structopt(
name = "PULLMODE",
possible_values = &PullMode::variants(),
case_insensitive=true,
help = "The weak pull mode of the pin"
)]
pub pull_mode: PullMode,
}
impl CommandDispatch for GpioSetPullMode {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::GPIO).ok()?;
let gpio_pin = transport.gpio_pin(&self.pin)?;
gpio_pin.set_pull_mode(self.pull_mode)?;
Ok(None)
}
}
/// Commands for manipulating GPIO pins.
#[derive(Debug, StructOpt, CommandDispatch)]
pub enum GpioCommand {
Read(GpioRead),
Write(GpioWrite),
SetMode(GpioSetMode),
SetPullMode(GpioSetPullMode),
}
| GpioSetPullMode | identifier_name |
mod.rs | pub use self::stack::Stack;
pub use self::word::Word;
use memory;
use memory::MemoryMap;
use self::opcode::{Opcode, PartialAddr, IWord};
mod alu;
mod opcode;
mod stack;
mod word;
pub struct CPU {
p: Word,
i: IWord,
a: Word,
b: Word,
dat: Stack,
ret: Stack,
mem: MemoryMap
}
impl CPU {
fn jump(&mut self, address: PartialAddr) {
let PartialAddr(partial, bits) = address;
let bits_word = Word(bits as i32);
self.p = (self.p >> bits_word << bits_word) | partial;
}
fn exec(&mut self, opcode: Opcode) {
use self::opcode::Opcode::*;
match opcode {
Unary(op) => alu::unary(op, &mut self.dat),
Binary(op) => alu::binary(op, &mut self.dat, &mut self.ret),
Stack(op) => alu::stack(op, &mut self.dat, &mut self.ret),
Register(op, inc) => self.exec_register(op, inc),
Control(op, addr) => self.exec_control(op, addr)
}
}
fn | (&mut self, op: u8, increment: bool) {
let (reg, reg_op) = match (op, increment) {
(3, true) => (&mut self.p, 1), // @p
(7, true) => (&mut self.p, 2), //!p
(0...3, _) => (&mut self.a, op & 3), // a @! a!
(4...7, _) => (&mut self.b, op & 3), // b @b!b b!
(n, f) => panic!("register op out of range: {} {}", n, f)
};
match reg_op {
0 => self.dat.push(*reg), // a b
1 => self.dat.push(self.mem.read(*reg)), // @ @b @p
2 => self.mem.write(*reg, self.dat.pop()), //!!b!p
3 => { *reg = self.dat.pop() }, // a! b!
_ => unreachable!()
}
if increment {
*reg = memory::inc_address(*reg);
}
}
fn exec_control(&mut self, operation: u8, address: PartialAddr) {
let t = self.dat.peek();
match operation {
0 => self.jump(address), // (jump)
1 => { // (call)
self.ret.push(self.p);
self.jump(address);
}
2 => if t == Word(0) { self.jump(address) }, // if
3 => if t >= Word(0) { self.jump(address) }, // -if
4 => if self.ret.next() { self.jump(address) }, // next
5 => if self.ret.next() { self.i.restart() }, // unext
6 => { // ex
let temp = self.p;
self.p = self.ret.pop();
self.ret.push(temp);
},
7 => { self.p = self.ret.pop(); }, // ;
n => panic!("control flow op out of range: {}", n)
}
}
}
| exec_register | identifier_name |
mod.rs | pub use self::stack::Stack;
pub use self::word::Word;
use memory;
use memory::MemoryMap;
use self::opcode::{Opcode, PartialAddr, IWord};
mod alu;
mod opcode;
mod stack;
mod word;
pub struct CPU {
p: Word,
i: IWord,
a: Word,
b: Word,
dat: Stack,
ret: Stack,
mem: MemoryMap
}
impl CPU {
fn jump(&mut self, address: PartialAddr) {
let PartialAddr(partial, bits) = address;
let bits_word = Word(bits as i32);
self.p = (self.p >> bits_word << bits_word) | partial;
}
fn exec(&mut self, opcode: Opcode) |
fn exec_register(&mut self, op: u8, increment: bool) {
let (reg, reg_op) = match (op, increment) {
(3, true) => (&mut self.p, 1), // @p
(7, true) => (&mut self.p, 2), //!p
(0...3, _) => (&mut self.a, op & 3), // a @! a!
(4...7, _) => (&mut self.b, op & 3), // b @b!b b!
(n, f) => panic!("register op out of range: {} {}", n, f)
};
match reg_op {
0 => self.dat.push(*reg), // a b
1 => self.dat.push(self.mem.read(*reg)), // @ @b @p
2 => self.mem.write(*reg, self.dat.pop()), //!!b!p
3 => { *reg = self.dat.pop() }, // a! b!
_ => unreachable!()
}
if increment {
*reg = memory::inc_address(*reg);
}
}
fn exec_control(&mut self, operation: u8, address: PartialAddr) {
let t = self.dat.peek();
match operation {
0 => self.jump(address), // (jump)
1 => { // (call)
self.ret.push(self.p);
self.jump(address);
}
2 => if t == Word(0) { self.jump(address) }, // if
3 => if t >= Word(0) { self.jump(address) }, // -if
4 => if self.ret.next() { self.jump(address) }, // next
5 => if self.ret.next() { self.i.restart() }, // unext
6 => { // ex
let temp = self.p;
self.p = self.ret.pop();
self.ret.push(temp);
},
7 => { self.p = self.ret.pop(); }, // ;
n => panic!("control flow op out of range: {}", n)
}
}
}
| {
use self::opcode::Opcode::*;
match opcode {
Unary(op) => alu::unary(op, &mut self.dat),
Binary(op) => alu::binary(op, &mut self.dat, &mut self.ret),
Stack(op) => alu::stack(op, &mut self.dat, &mut self.ret),
Register(op, inc) => self.exec_register(op, inc),
Control(op, addr) => self.exec_control(op, addr)
}
} | identifier_body |
mod.rs | pub use self::stack::Stack;
pub use self::word::Word;
use memory;
use memory::MemoryMap;
use self::opcode::{Opcode, PartialAddr, IWord};
mod alu;
mod opcode;
mod stack;
mod word;
pub struct CPU {
p: Word,
i: IWord,
a: Word,
b: Word,
dat: Stack,
ret: Stack,
mem: MemoryMap
}
impl CPU {
fn jump(&mut self, address: PartialAddr) {
let PartialAddr(partial, bits) = address;
let bits_word = Word(bits as i32);
self.p = (self.p >> bits_word << bits_word) | partial;
}
fn exec(&mut self, opcode: Opcode) {
use self::opcode::Opcode::*;
match opcode {
Unary(op) => alu::unary(op, &mut self.dat),
Binary(op) => alu::binary(op, &mut self.dat, &mut self.ret), | }
}
fn exec_register(&mut self, op: u8, increment: bool) {
let (reg, reg_op) = match (op, increment) {
(3, true) => (&mut self.p, 1), // @p
(7, true) => (&mut self.p, 2), //!p
(0...3, _) => (&mut self.a, op & 3), // a @! a!
(4...7, _) => (&mut self.b, op & 3), // b @b!b b!
(n, f) => panic!("register op out of range: {} {}", n, f)
};
match reg_op {
0 => self.dat.push(*reg), // a b
1 => self.dat.push(self.mem.read(*reg)), // @ @b @p
2 => self.mem.write(*reg, self.dat.pop()), //!!b!p
3 => { *reg = self.dat.pop() }, // a! b!
_ => unreachable!()
}
if increment {
*reg = memory::inc_address(*reg);
}
}
fn exec_control(&mut self, operation: u8, address: PartialAddr) {
let t = self.dat.peek();
match operation {
0 => self.jump(address), // (jump)
1 => { // (call)
self.ret.push(self.p);
self.jump(address);
}
2 => if t == Word(0) { self.jump(address) }, // if
3 => if t >= Word(0) { self.jump(address) }, // -if
4 => if self.ret.next() { self.jump(address) }, // next
5 => if self.ret.next() { self.i.restart() }, // unext
6 => { // ex
let temp = self.p;
self.p = self.ret.pop();
self.ret.push(temp);
},
7 => { self.p = self.ret.pop(); }, // ;
n => panic!("control flow op out of range: {}", n)
}
}
} | Stack(op) => alu::stack(op, &mut self.dat, &mut self.ret),
Register(op, inc) => self.exec_register(op, inc),
Control(op, addr) => self.exec_control(op, addr) | random_line_split |
fake_browser.rs | extern crate cookie;
use self::cookie::CookieJar;
extern crate regex;
use self::regex::Regex;
extern crate hyper;
use self::hyper::client::{Client, RedirectPolicy};
use self::hyper::Url;
use std::io::prelude::*;
use std::error::Error;
use std::fmt::{Display, Formatter};
use api::CallError;
/// Function that return authorization uri for Standalone client
pub fn authorization_client_uri(client_id: u64, scope: String, version: String, redirect: String) -> String {
format!("https://oauth.vk.com/authorize?client_id={}&scope={}&redirect_uri={}&display=mobile&v={}&response_type=token", client_id, scope, redirect, version)
}
use std::collections::HashMap;
// Get params send by hidden fields on auth page form
fn hidden_params(s: &String) -> HashMap<String,String> {
let mut map = HashMap::new();
let reg = Regex::new("name=\"([a-z_]*)\".*value=\"([:A-Za-z-/0-9.]+)\"").unwrap();
for cap in reg.captures_iter(&*s) {
map.insert(cap.at(1).unwrap_or("").into(), cap.at(2).unwrap_or("").into());
}
map
}
// Build POST request body for <form>
fn build_post_for_hidden_form(mut hidden_fields: HashMap<String,String>, login: String, password: String) -> String {
let mut result = String::new();
hidden_fields.insert("email".into(), login);
hidden_fields.insert("pass".into(), password);
for (key, value) in hidden_fields.iter() {
result.extend( format!("{}={}&", key,value).chars() );
}
result
}
// Find URL to send auth form
fn get_post_uri(s: &String) -> String {
let reg = Regex::new("action=\"([a-z:/?=&.0-9]*)\"").unwrap();
match reg.captures_iter(&*s).next() {
Some(x) => x.at(1).unwrap_or(""),
None => ""
}.into()
}
// Get access token and other data from response URL
fn get_token(u: &Url) -> (String, u64, u64) {
let reg = Regex::new("access_token=([a-f0-9]+)&expires_in=([0-9]+)&user_id=([0-9]+)").unwrap();
let mut token: String = String::new();
let mut expires: u64 = 0u64;
let mut user_id: u64 = 0u64;
for cap in reg.captures_iter(&u.to_string()) {
token = cap.at(1).unwrap_or("").into();
expires = cap.at(2).unwrap_or("0").parse::<u64>().unwrap();
user_id = cap.at(3).unwrap_or("0").parse::<u64>().unwrap();
}
(token, expires, user_id)
}
// Find url to confirm rights after authorization process(not always showed form)
fn find_confirmation_form(s: &String) -> String {
let mut result = String::new();
let reg = Regex::new("action=\"([A-Za-z0-9:/.?=&_%]+)\"").unwrap();
for cap in reg.captures_iter(&*s) {
result = cap.at(1).unwrap_or("").into();
}
result
}
// Stub
fn detect_captcha(s: &String) -> bool {
let reg = Regex::new("id=\"captcha\"").unwrap();
if reg.is_match(&*s) {
true
}
else{
false
}
}
/// Error returned if captcha was detected on login process
/// _Warning:_ the error isn't about 'Captcha needed' VK.com API real error.
#[derive(Debug)]
pub struct CapthaError;
impl Display for CapthaError {
fn fmt(&self,f: &mut Formatter) -> Result<(), ::std::fmt::Error> {
"Captcha was found on authorization process.".fmt(f)
}
}
impl Error for CapthaError {
fn description(&self) -> &str {
"Captha was found on authorization process."
}
} | /// The function implement login process for user without browser
/// _Warning: use the thing careful to privacy and privacy policy of vk.com_
pub fn fake_browser(login: String, password: String, url: String) -> Result<(String, u64, u64),CallError> {
use std::thread::sleep_ms;
use self::hyper::header::{Cookie,Location,SetCookie, ContentLength};
use self::hyper::client::response::Response;
let mut client = Client::new();
client.set_redirect_policy(RedirectPolicy::FollowNone);
let mut res: Response;
match client.get(&url).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(url, Some(Box::new(e))))
};
let mut jar = CookieJar::new(b"");
match res.headers.get::<SetCookie>(){
Some(setcookie) => setcookie.apply_to_cookie_jar(&mut jar),
None => return Err(CallError::new(
format!("Header of response doesn't set any cookies, {}", res.url), None))
};
let mut result = String::new();
match res.read_to_string(&mut result){
Ok(_) => { },
Err(e) => return Err(CallError::new(
format!("Failed read page to string by url: {}", res.url), Some(Box::new(e))))
};
let params = hidden_params(&result);
let post_req = build_post_for_hidden_form(params, login, password);
let post_uri = get_post_uri(&result);
sleep_ms(1000);
match client.post(&post_uri).header::<Cookie>(Cookie::from_cookie_jar(&jar)).body(&post_req).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(
format!("Can't send POST to {} with body {}",post_uri, post_req), Some(Box::new(e))))
};
while res.headers.has::<Location>() {
if res.headers.has::<SetCookie>() {
res.headers.get::<SetCookie>().unwrap().apply_to_cookie_jar(&mut jar);
}
let redirect = res.headers.get::<Location>().unwrap().clone();
res = client.get(&*redirect).header::<Cookie>(Cookie::from_cookie_jar(&jar)).send().unwrap();
let length = res.headers.get::<ContentLength>().unwrap().clone();
// Check that we've got yet one confirmation form
if length!= ContentLength(0u64) {
let mut answer = String::new();
if let Ok(_) = res.read_to_string(&mut answer) {
if detect_captcha(&answer) {
return Err(CallError::new(answer, Some(Box::new(CapthaError))));
}
let url = find_confirmation_form(&answer);
if!url.is_empty() {
match client.post(&url).header::<Cookie>(Cookie::from_cookie_jar(&jar)).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(
format!("Failed POST to url: {}", res.url), Some(Box::new(e))))
};
}
}
}
}
let result = get_token(&res.url);
if result == (String::new(), 0u64, 0u64) {
Err(CallError::new(
format!("Can't get token by url: {}", res.url),
None))
}
else {
Ok(result)
}
} | random_line_split |
|
fake_browser.rs | extern crate cookie;
use self::cookie::CookieJar;
extern crate regex;
use self::regex::Regex;
extern crate hyper;
use self::hyper::client::{Client, RedirectPolicy};
use self::hyper::Url;
use std::io::prelude::*;
use std::error::Error;
use std::fmt::{Display, Formatter};
use api::CallError;
/// Function that return authorization uri for Standalone client
pub fn | (client_id: u64, scope: String, version: String, redirect: String) -> String {
format!("https://oauth.vk.com/authorize?client_id={}&scope={}&redirect_uri={}&display=mobile&v={}&response_type=token", client_id, scope, redirect, version)
}
use std::collections::HashMap;
// Get params send by hidden fields on auth page form
fn hidden_params(s: &String) -> HashMap<String,String> {
let mut map = HashMap::new();
let reg = Regex::new("name=\"([a-z_]*)\".*value=\"([:A-Za-z-/0-9.]+)\"").unwrap();
for cap in reg.captures_iter(&*s) {
map.insert(cap.at(1).unwrap_or("").into(), cap.at(2).unwrap_or("").into());
}
map
}
// Build POST request body for <form>
fn build_post_for_hidden_form(mut hidden_fields: HashMap<String,String>, login: String, password: String) -> String {
let mut result = String::new();
hidden_fields.insert("email".into(), login);
hidden_fields.insert("pass".into(), password);
for (key, value) in hidden_fields.iter() {
result.extend( format!("{}={}&", key,value).chars() );
}
result
}
// Find URL to send auth form
fn get_post_uri(s: &String) -> String {
let reg = Regex::new("action=\"([a-z:/?=&.0-9]*)\"").unwrap();
match reg.captures_iter(&*s).next() {
Some(x) => x.at(1).unwrap_or(""),
None => ""
}.into()
}
// Get access token and other data from response URL
fn get_token(u: &Url) -> (String, u64, u64) {
let reg = Regex::new("access_token=([a-f0-9]+)&expires_in=([0-9]+)&user_id=([0-9]+)").unwrap();
let mut token: String = String::new();
let mut expires: u64 = 0u64;
let mut user_id: u64 = 0u64;
for cap in reg.captures_iter(&u.to_string()) {
token = cap.at(1).unwrap_or("").into();
expires = cap.at(2).unwrap_or("0").parse::<u64>().unwrap();
user_id = cap.at(3).unwrap_or("0").parse::<u64>().unwrap();
}
(token, expires, user_id)
}
// Find url to confirm rights after authorization process(not always showed form)
fn find_confirmation_form(s: &String) -> String {
let mut result = String::new();
let reg = Regex::new("action=\"([A-Za-z0-9:/.?=&_%]+)\"").unwrap();
for cap in reg.captures_iter(&*s) {
result = cap.at(1).unwrap_or("").into();
}
result
}
// Stub
fn detect_captcha(s: &String) -> bool {
let reg = Regex::new("id=\"captcha\"").unwrap();
if reg.is_match(&*s) {
true
}
else{
false
}
}
/// Error returned if captcha was detected on login process
/// _Warning:_ the error isn't about 'Captcha needed' VK.com API real error.
#[derive(Debug)]
pub struct CapthaError;
impl Display for CapthaError {
fn fmt(&self,f: &mut Formatter) -> Result<(), ::std::fmt::Error> {
"Captcha was found on authorization process.".fmt(f)
}
}
impl Error for CapthaError {
fn description(&self) -> &str {
"Captha was found on authorization process."
}
}
/// The function implement login process for user without browser
/// _Warning: use the thing careful to privacy and privacy policy of vk.com_
pub fn fake_browser(login: String, password: String, url: String) -> Result<(String, u64, u64),CallError> {
use std::thread::sleep_ms;
use self::hyper::header::{Cookie,Location,SetCookie, ContentLength};
use self::hyper::client::response::Response;
let mut client = Client::new();
client.set_redirect_policy(RedirectPolicy::FollowNone);
let mut res: Response;
match client.get(&url).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(url, Some(Box::new(e))))
};
let mut jar = CookieJar::new(b"");
match res.headers.get::<SetCookie>(){
Some(setcookie) => setcookie.apply_to_cookie_jar(&mut jar),
None => return Err(CallError::new(
format!("Header of response doesn't set any cookies, {}", res.url), None))
};
let mut result = String::new();
match res.read_to_string(&mut result){
Ok(_) => { },
Err(e) => return Err(CallError::new(
format!("Failed read page to string by url: {}", res.url), Some(Box::new(e))))
};
let params = hidden_params(&result);
let post_req = build_post_for_hidden_form(params, login, password);
let post_uri = get_post_uri(&result);
sleep_ms(1000);
match client.post(&post_uri).header::<Cookie>(Cookie::from_cookie_jar(&jar)).body(&post_req).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(
format!("Can't send POST to {} with body {}",post_uri, post_req), Some(Box::new(e))))
};
while res.headers.has::<Location>() {
if res.headers.has::<SetCookie>() {
res.headers.get::<SetCookie>().unwrap().apply_to_cookie_jar(&mut jar);
}
let redirect = res.headers.get::<Location>().unwrap().clone();
res = client.get(&*redirect).header::<Cookie>(Cookie::from_cookie_jar(&jar)).send().unwrap();
let length = res.headers.get::<ContentLength>().unwrap().clone();
// Check that we've got yet one confirmation form
if length!= ContentLength(0u64) {
let mut answer = String::new();
if let Ok(_) = res.read_to_string(&mut answer) {
if detect_captcha(&answer) {
return Err(CallError::new(answer, Some(Box::new(CapthaError))));
}
let url = find_confirmation_form(&answer);
if!url.is_empty() {
match client.post(&url).header::<Cookie>(Cookie::from_cookie_jar(&jar)).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(
format!("Failed POST to url: {}", res.url), Some(Box::new(e))))
};
}
}
}
}
let result = get_token(&res.url);
if result == (String::new(), 0u64, 0u64) {
Err(CallError::new(
format!("Can't get token by url: {}", res.url),
None))
}
else {
Ok(result)
}
}
| authorization_client_uri | identifier_name |
fake_browser.rs | extern crate cookie;
use self::cookie::CookieJar;
extern crate regex;
use self::regex::Regex;
extern crate hyper;
use self::hyper::client::{Client, RedirectPolicy};
use self::hyper::Url;
use std::io::prelude::*;
use std::error::Error;
use std::fmt::{Display, Formatter};
use api::CallError;
/// Function that return authorization uri for Standalone client
pub fn authorization_client_uri(client_id: u64, scope: String, version: String, redirect: String) -> String {
format!("https://oauth.vk.com/authorize?client_id={}&scope={}&redirect_uri={}&display=mobile&v={}&response_type=token", client_id, scope, redirect, version)
}
use std::collections::HashMap;
// Get params send by hidden fields on auth page form
fn hidden_params(s: &String) -> HashMap<String,String> {
let mut map = HashMap::new();
let reg = Regex::new("name=\"([a-z_]*)\".*value=\"([:A-Za-z-/0-9.]+)\"").unwrap();
for cap in reg.captures_iter(&*s) {
map.insert(cap.at(1).unwrap_or("").into(), cap.at(2).unwrap_or("").into());
}
map
}
// Build POST request body for <form>
fn build_post_for_hidden_form(mut hidden_fields: HashMap<String,String>, login: String, password: String) -> String {
let mut result = String::new();
hidden_fields.insert("email".into(), login);
hidden_fields.insert("pass".into(), password);
for (key, value) in hidden_fields.iter() {
result.extend( format!("{}={}&", key,value).chars() );
}
result
}
// Find URL to send auth form
fn get_post_uri(s: &String) -> String |
// Get access token and other data from response URL
fn get_token(u: &Url) -> (String, u64, u64) {
let reg = Regex::new("access_token=([a-f0-9]+)&expires_in=([0-9]+)&user_id=([0-9]+)").unwrap();
let mut token: String = String::new();
let mut expires: u64 = 0u64;
let mut user_id: u64 = 0u64;
for cap in reg.captures_iter(&u.to_string()) {
token = cap.at(1).unwrap_or("").into();
expires = cap.at(2).unwrap_or("0").parse::<u64>().unwrap();
user_id = cap.at(3).unwrap_or("0").parse::<u64>().unwrap();
}
(token, expires, user_id)
}
// Find url to confirm rights after authorization process(not always showed form)
fn find_confirmation_form(s: &String) -> String {
let mut result = String::new();
let reg = Regex::new("action=\"([A-Za-z0-9:/.?=&_%]+)\"").unwrap();
for cap in reg.captures_iter(&*s) {
result = cap.at(1).unwrap_or("").into();
}
result
}
// Stub
fn detect_captcha(s: &String) -> bool {
let reg = Regex::new("id=\"captcha\"").unwrap();
if reg.is_match(&*s) {
true
}
else{
false
}
}
/// Error returned if captcha was detected on login process
/// _Warning:_ the error isn't about 'Captcha needed' VK.com API real error.
#[derive(Debug)]
pub struct CapthaError;
impl Display for CapthaError {
fn fmt(&self,f: &mut Formatter) -> Result<(), ::std::fmt::Error> {
"Captcha was found on authorization process.".fmt(f)
}
}
impl Error for CapthaError {
fn description(&self) -> &str {
"Captha was found on authorization process."
}
}
/// The function implement login process for user without browser
/// _Warning: use the thing careful to privacy and privacy policy of vk.com_
pub fn fake_browser(login: String, password: String, url: String) -> Result<(String, u64, u64),CallError> {
use std::thread::sleep_ms;
use self::hyper::header::{Cookie,Location,SetCookie, ContentLength};
use self::hyper::client::response::Response;
let mut client = Client::new();
client.set_redirect_policy(RedirectPolicy::FollowNone);
let mut res: Response;
match client.get(&url).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(url, Some(Box::new(e))))
};
let mut jar = CookieJar::new(b"");
match res.headers.get::<SetCookie>(){
Some(setcookie) => setcookie.apply_to_cookie_jar(&mut jar),
None => return Err(CallError::new(
format!("Header of response doesn't set any cookies, {}", res.url), None))
};
let mut result = String::new();
match res.read_to_string(&mut result){
Ok(_) => { },
Err(e) => return Err(CallError::new(
format!("Failed read page to string by url: {}", res.url), Some(Box::new(e))))
};
let params = hidden_params(&result);
let post_req = build_post_for_hidden_form(params, login, password);
let post_uri = get_post_uri(&result);
sleep_ms(1000);
match client.post(&post_uri).header::<Cookie>(Cookie::from_cookie_jar(&jar)).body(&post_req).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(
format!("Can't send POST to {} with body {}",post_uri, post_req), Some(Box::new(e))))
};
while res.headers.has::<Location>() {
if res.headers.has::<SetCookie>() {
res.headers.get::<SetCookie>().unwrap().apply_to_cookie_jar(&mut jar);
}
let redirect = res.headers.get::<Location>().unwrap().clone();
res = client.get(&*redirect).header::<Cookie>(Cookie::from_cookie_jar(&jar)).send().unwrap();
let length = res.headers.get::<ContentLength>().unwrap().clone();
// Check that we've got yet one confirmation form
if length!= ContentLength(0u64) {
let mut answer = String::new();
if let Ok(_) = res.read_to_string(&mut answer) {
if detect_captcha(&answer) {
return Err(CallError::new(answer, Some(Box::new(CapthaError))));
}
let url = find_confirmation_form(&answer);
if!url.is_empty() {
match client.post(&url).header::<Cookie>(Cookie::from_cookie_jar(&jar)).send(){
Ok(r) => res = r,
Err(e) => return Err(CallError::new(
format!("Failed POST to url: {}", res.url), Some(Box::new(e))))
};
}
}
}
}
let result = get_token(&res.url);
if result == (String::new(), 0u64, 0u64) {
Err(CallError::new(
format!("Can't get token by url: {}", res.url),
None))
}
else {
Ok(result)
}
}
| {
let reg = Regex::new("action=\"([a-z:/?=&.0-9]*)\"").unwrap();
match reg.captures_iter(&*s).next() {
Some(x) => x.at(1).unwrap_or(""),
None => ""
}.into()
} | identifier_body |
gen.rs | use std::rand::Rng;
use std::rand;
fn main() | println!("{}", v.as_slice());
// `shuffle` shuffles a mutable slice in place
rng.shuffle(v.as_mut_slice());
println!("shuffle previous slice");
println!("{}", v.as_slice());
// `choose` will sample an slice *with* replacement
// i.e. the same element can be chosen more than one time
println!("sample previous slice *with* replacement 10 times");
for _ in range(0u, 10) {
match rng.choose(v.as_slice()) {
None => fail!("slice was empty"),
Some(x) => println!("{}", x),
}
}
}
| {
// create a task-local Random Number Generator
let mut rng = rand::task_rng();
// the `gen` methods generates values in the full range of each type using
// a uniform distribution
println!("randomly generate some values for different primitive types");
println!("u8: {}", rng.gen::<u8>());
println!("i8: {}", rng.gen::<i8>());
println!("u16: {}", rng.gen::<u16>());
println!("i16: {}", rng.gen::<i16>());
// except for floats which get generated in the range [0, 1>
println!("f32: {}", rng.gen::<f32>());
println!("f64: {}", rng.gen::<f64>());
// `gen_iter` returns an iterator that yields a infinite number of randomly
// generated numbers
let mut v: Vec<u8> = rng.gen_iter::<u8>().take(10).collect();
println!("10 randomly generated u8 values"); | identifier_body |
gen.rs | use std::rand::Rng;
use std::rand;
fn | () {
// create a task-local Random Number Generator
let mut rng = rand::task_rng();
// the `gen` methods generates values in the full range of each type using
// a uniform distribution
println!("randomly generate some values for different primitive types");
println!("u8: {}", rng.gen::<u8>());
println!("i8: {}", rng.gen::<i8>());
println!("u16: {}", rng.gen::<u16>());
println!("i16: {}", rng.gen::<i16>());
// except for floats which get generated in the range [0, 1>
println!("f32: {}", rng.gen::<f32>());
println!("f64: {}", rng.gen::<f64>());
// `gen_iter` returns an iterator that yields a infinite number of randomly
// generated numbers
let mut v: Vec<u8> = rng.gen_iter::<u8>().take(10).collect();
println!("10 randomly generated u8 values");
println!("{}", v.as_slice());
// `shuffle` shuffles a mutable slice in place
rng.shuffle(v.as_mut_slice());
println!("shuffle previous slice");
println!("{}", v.as_slice());
// `choose` will sample an slice *with* replacement
// i.e. the same element can be chosen more than one time
println!("sample previous slice *with* replacement 10 times");
for _ in range(0u, 10) {
match rng.choose(v.as_slice()) {
None => fail!("slice was empty"),
Some(x) => println!("{}", x),
}
}
}
| main | identifier_name |
gen.rs | use std::rand::Rng;
use std::rand;
fn main() {
// create a task-local Random Number Generator
let mut rng = rand::task_rng();
// the `gen` methods generates values in the full range of each type using
// a uniform distribution
println!("randomly generate some values for different primitive types");
println!("u8: {}", rng.gen::<u8>());
println!("i8: {}", rng.gen::<i8>()); | println!("f32: {}", rng.gen::<f32>());
println!("f64: {}", rng.gen::<f64>());
// `gen_iter` returns an iterator that yields a infinite number of randomly
// generated numbers
let mut v: Vec<u8> = rng.gen_iter::<u8>().take(10).collect();
println!("10 randomly generated u8 values");
println!("{}", v.as_slice());
// `shuffle` shuffles a mutable slice in place
rng.shuffle(v.as_mut_slice());
println!("shuffle previous slice");
println!("{}", v.as_slice());
// `choose` will sample an slice *with* replacement
// i.e. the same element can be chosen more than one time
println!("sample previous slice *with* replacement 10 times");
for _ in range(0u, 10) {
match rng.choose(v.as_slice()) {
None => fail!("slice was empty"),
Some(x) => println!("{}", x),
}
}
} | println!("u16: {}", rng.gen::<u16>());
println!("i16: {}", rng.gen::<i16>());
// except for floats which get generated in the range [0, 1> | random_line_split |
q_box.rs | use crate::{QObject, QPtr};
use cpp_core::{
CastFrom, CastInto, CppBox, CppDeletable, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast,
};
use std::ops::Deref;
use std::{fmt, mem};
/// An owning pointer for `QObject`-based objects.
///
/// `QBox` will delete its object on drop if it has no parent. If the object has a parent,
/// it's assumed that the parent is responsible for deleting the object, as per Qt ownership system.
/// Additionally, `QBox` will be automatically set to null when the object is deleted, similar
/// to `QPtr` (or `QPointer<T>` in C++). `QBox` will not attempt to delete null pointers.
///
/// Note that dereferencing a null `QBox` will panic, so if it's known that the object may
/// already have been deleted, you should use `is_null()`, `as_ref()`,
/// or a similar method to check
/// if the object is still alive before calling its methods.
///
/// Unlike `CppBox` (which is non-nullable), `QBox` is permitted to contain a null pointer because
/// even if a non-null pointer is provided when constructing `QBox`, it will become null
/// automatically if the object is deleted.
///
/// To prevent the object from being deleted, convert `QBox` to another type of pointer using
/// `into_q_ptr()` or `into_ptr()`. Alternatively, setting a parent for the object will prevent
/// `QBox` from deleting it.
///
/// To make sure the object is deleted regardless of its parent, convert `QBox` to `CppBox` using
/// `into_box()`.
///
/// # Safety
///
/// `QBox` has the same safety issues as `QPtr`. See `QPtr` documentation.
pub struct QBox<T: StaticUpcast<QObject> + CppDeletable>(QPtr<T>);
impl<T: StaticUpcast<QObject> + CppDeletable> QBox<T> {
/// Creates a `QBox` from a `QPtr`.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn from_q_ptr(target: QPtr<T>) -> Self {
QBox(target)
}
/// Creates a `QBox` from a `Ptr`.
///
/// ### Safety
///
/// `target` must be either a valid pointer to an object or a null pointer.
/// See type level documentation.
pub unsafe fn new(target: impl CastInto<Ptr<T>>) -> Self {
QBox::from_q_ptr(QPtr::new(target))
}
/// Creates a `QBox` from a raw pointer.
///
/// ### Safety
///
/// `target` must be either a valid pointer to an object or a null pointer.
/// See type level documentation.
pub unsafe fn from_raw(target: *const T) -> Self {
QBox::from_q_ptr(QPtr::from_raw(target))
}
/// Creates a null pointer.
///
/// Note that you can also use `NullPtr` to specify a null pointer to a function accepting
/// `impl CastInto<Ptr<_>>`. Unlike `Ptr`, `NullPtr` is not a generic type, so it will
/// not cause type inference issues.
///
/// Note that accessing the content of a null `QBox` through `Deref` will result
/// in a panic.
///
/// ### Safety
///
/// Null pointers must not be dereferenced. See type level documentation.
pub unsafe fn null() -> Self {
QBox::from_q_ptr(QPtr::<T>::null())
}
/// Returns true if the pointer is null.
pub unsafe fn is_null(&self) -> bool |
/// Returns the content as a const `Ptr`.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_ptr(&self) -> Ptr<T> {
self.0.as_ptr()
}
/// Returns the content as a raw const pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_raw_ptr(&self) -> *const T {
self.0.as_raw_ptr()
}
/// Returns the content as a raw mutable pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_mut_raw_ptr(&self) -> *mut T {
self.0.as_mut_raw_ptr()
}
/// Returns the content as a const `Ref`. Returns `None` if `self` is a null pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_ref(&self) -> Option<Ref<T>> {
self.0.as_ref()
}
/// Returns a reference to the value. Returns `None` if the pointer is null.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_raw_ref<'a>(&self) -> Option<&'a T> {
self.as_ref().map(|r| r.as_raw_ref())
}
/// Returns a mutable reference to the value. Returns `None` if the pointer is null.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_mut_raw_ref<'a>(&self) -> Option<&'a mut T> {
self.as_ref().map(|r| r.as_mut_raw_ref())
}
/// Converts the pointer to the base class type `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid or null. See type level documentation.
pub unsafe fn static_upcast<U>(&self) -> QPtr<U>
where
T: StaticUpcast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().static_upcast::<U>())
}
/// Converts the pointer to the derived class type `U`.
///
/// It's recommended to use `dynamic_cast` instead because it performs a checked conversion.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid and it's type is `U` or inherits from `U`,
/// of if `self` is a null pointer. See type level documentation.
pub unsafe fn static_downcast<U>(&self) -> QPtr<U>
where
T: StaticDowncast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().static_downcast())
}
/// Converts the pointer to the derived class type `U`. Returns `None` if the object's type
/// is not `U` and doesn't inherit `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid or null. See type level documentation.
pub unsafe fn dynamic_cast<U>(&self) -> QPtr<U>
where
T: DynamicCast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().dynamic_cast())
}
/// Converts this pointer to a `CppBox`. Returns `None` if `self`
/// is a null pointer.
///
/// Unlike `QBox`, `CppBox` will always delete the object when dropped.
///
/// ### Safety
///
/// `CppBox` will attempt to delete the object on drop. If something else also tries to
/// delete this object before or after that, the behavior is undefined.
/// See type level documentation.
pub unsafe fn into_box(self) -> Option<CppBox<T>> {
self.into_q_ptr().to_box()
}
/// Converts this `QBox` into a `QPtr`.
///
/// Unlike `QBox`, `QPtr` will never delete the object when dropped.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_q_ptr(mut self) -> QPtr<T> {
mem::replace(&mut self.0, QPtr::null())
}
/// Converts this `QBox` into a `Ptr`.
///
/// Unlike `QBox`, `Ptr` will never delete the object when dropped.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_ptr(self) -> Ptr<T> {
self.into_q_ptr().as_ptr()
}
/// Converts this `QBox` into a raw pointer without deleting the object.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_raw_ptr(self) -> *mut T {
self.into_q_ptr().as_mut_raw_ptr()
}
}
impl<T: StaticUpcast<QObject> + CppDeletable> fmt::Debug for QBox<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "QBox({:?})", unsafe { self.as_raw_ptr() })
}
}
/// Allows to call member functions of `T` and its base classes directly on the pointer.
///
/// Panics if the pointer is null.
impl<T: StaticUpcast<QObject> + CppDeletable> Deref for QBox<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe {
let ptr = self.as_raw_ptr();
if ptr.is_null() {
panic!("attempted to deref a null QBox<T>");
}
&*ptr
}
}
}
impl<'a, T, U> CastFrom<&'a QBox<U>> for Ptr<T>
where
U: StaticUpcast<T> + StaticUpcast<QObject> + CppDeletable,
{
unsafe fn cast_from(value: &'a QBox<U>) -> Self {
CastFrom::cast_from(value.as_ptr())
}
}
impl<T: StaticUpcast<QObject> + CppDeletable> Drop for QBox<T> {
fn drop(&mut self) {
unsafe {
let ptr = self.as_ptr();
if!ptr.is_null() && ptr.static_upcast().parent().is_null() {
T::delete(&*ptr.as_raw_ptr());
}
}
}
}
| {
self.0.is_null()
} | identifier_body |
q_box.rs | use crate::{QObject, QPtr};
use cpp_core::{
CastFrom, CastInto, CppBox, CppDeletable, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast,
};
use std::ops::Deref;
use std::{fmt, mem};
/// An owning pointer for `QObject`-based objects.
///
/// `QBox` will delete its object on drop if it has no parent. If the object has a parent,
/// it's assumed that the parent is responsible for deleting the object, as per Qt ownership system.
/// Additionally, `QBox` will be automatically set to null when the object is deleted, similar
/// to `QPtr` (or `QPointer<T>` in C++). `QBox` will not attempt to delete null pointers.
///
/// Note that dereferencing a null `QBox` will panic, so if it's known that the object may
/// already have been deleted, you should use `is_null()`, `as_ref()`,
/// or a similar method to check
/// if the object is still alive before calling its methods.
///
/// Unlike `CppBox` (which is non-nullable), `QBox` is permitted to contain a null pointer because
/// even if a non-null pointer is provided when constructing `QBox`, it will become null
/// automatically if the object is deleted.
///
/// To prevent the object from being deleted, convert `QBox` to another type of pointer using
/// `into_q_ptr()` or `into_ptr()`. Alternatively, setting a parent for the object will prevent
/// `QBox` from deleting it.
///
/// To make sure the object is deleted regardless of its parent, convert `QBox` to `CppBox` using
/// `into_box()`.
///
/// # Safety
///
/// `QBox` has the same safety issues as `QPtr`. See `QPtr` documentation.
pub struct QBox<T: StaticUpcast<QObject> + CppDeletable>(QPtr<T>);
impl<T: StaticUpcast<QObject> + CppDeletable> QBox<T> {
/// Creates a `QBox` from a `QPtr`.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn from_q_ptr(target: QPtr<T>) -> Self {
QBox(target)
}
/// Creates a `QBox` from a `Ptr`.
///
/// ### Safety
///
/// `target` must be either a valid pointer to an object or a null pointer.
/// See type level documentation.
pub unsafe fn new(target: impl CastInto<Ptr<T>>) -> Self {
QBox::from_q_ptr(QPtr::new(target))
}
/// Creates a `QBox` from a raw pointer.
///
/// ### Safety
///
/// `target` must be either a valid pointer to an object or a null pointer.
/// See type level documentation.
pub unsafe fn from_raw(target: *const T) -> Self {
QBox::from_q_ptr(QPtr::from_raw(target))
}
/// Creates a null pointer.
///
/// Note that you can also use `NullPtr` to specify a null pointer to a function accepting
/// `impl CastInto<Ptr<_>>`. Unlike `Ptr`, `NullPtr` is not a generic type, so it will
/// not cause type inference issues.
///
/// Note that accessing the content of a null `QBox` through `Deref` will result
/// in a panic.
///
/// ### Safety
///
/// Null pointers must not be dereferenced. See type level documentation.
pub unsafe fn null() -> Self {
QBox::from_q_ptr(QPtr::<T>::null())
}
/// Returns true if the pointer is null.
pub unsafe fn is_null(&self) -> bool {
self.0.is_null()
}
/// Returns the content as a const `Ptr`.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_ptr(&self) -> Ptr<T> {
self.0.as_ptr()
}
/// Returns the content as a raw const pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_raw_ptr(&self) -> *const T {
self.0.as_raw_ptr()
}
/// Returns the content as a raw mutable pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_mut_raw_ptr(&self) -> *mut T {
self.0.as_mut_raw_ptr()
}
/// Returns the content as a const `Ref`. Returns `None` if `self` is a null pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_ref(&self) -> Option<Ref<T>> {
self.0.as_ref()
}
/// Returns a reference to the value. Returns `None` if the pointer is null.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_raw_ref<'a>(&self) -> Option<&'a T> {
self.as_ref().map(|r| r.as_raw_ref())
}
/// Returns a mutable reference to the value. Returns `None` if the pointer is null.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_mut_raw_ref<'a>(&self) -> Option<&'a mut T> {
self.as_ref().map(|r| r.as_mut_raw_ref())
}
/// Converts the pointer to the base class type `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid or null. See type level documentation.
pub unsafe fn static_upcast<U>(&self) -> QPtr<U>
where
T: StaticUpcast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().static_upcast::<U>())
}
/// Converts the pointer to the derived class type `U`.
///
/// It's recommended to use `dynamic_cast` instead because it performs a checked conversion.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid and it's type is `U` or inherits from `U`,
/// of if `self` is a null pointer. See type level documentation.
pub unsafe fn static_downcast<U>(&self) -> QPtr<U>
where
T: StaticDowncast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().static_downcast())
}
/// Converts the pointer to the derived class type `U`. Returns `None` if the object's type
/// is not `U` and doesn't inherit `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid or null. See type level documentation.
pub unsafe fn dynamic_cast<U>(&self) -> QPtr<U>
where
T: DynamicCast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().dynamic_cast())
}
/// Converts this pointer to a `CppBox`. Returns `None` if `self`
/// is a null pointer.
///
/// Unlike `QBox`, `CppBox` will always delete the object when dropped.
///
/// ### Safety
///
/// `CppBox` will attempt to delete the object on drop. If something else also tries to
/// delete this object before or after that, the behavior is undefined.
/// See type level documentation.
pub unsafe fn into_box(self) -> Option<CppBox<T>> {
self.into_q_ptr().to_box()
}
/// Converts this `QBox` into a `QPtr`.
///
/// Unlike `QBox`, `QPtr` will never delete the object when dropped.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_q_ptr(mut self) -> QPtr<T> {
mem::replace(&mut self.0, QPtr::null())
}
/// Converts this `QBox` into a `Ptr`.
///
/// Unlike `QBox`, `Ptr` will never delete the object when dropped.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_ptr(self) -> Ptr<T> {
self.into_q_ptr().as_ptr()
}
/// Converts this `QBox` into a raw pointer without deleting the object.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_raw_ptr(self) -> *mut T {
self.into_q_ptr().as_mut_raw_ptr()
}
}
impl<T: StaticUpcast<QObject> + CppDeletable> fmt::Debug for QBox<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "QBox({:?})", unsafe { self.as_raw_ptr() })
}
}
/// Allows to call member functions of `T` and its base classes directly on the pointer.
///
/// Panics if the pointer is null.
impl<T: StaticUpcast<QObject> + CppDeletable> Deref for QBox<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe {
let ptr = self.as_raw_ptr();
if ptr.is_null() {
panic!("attempted to deref a null QBox<T>");
}
&*ptr
}
}
}
impl<'a, T, U> CastFrom<&'a QBox<U>> for Ptr<T>
where
U: StaticUpcast<T> + StaticUpcast<QObject> + CppDeletable,
{
unsafe fn cast_from(value: &'a QBox<U>) -> Self {
CastFrom::cast_from(value.as_ptr())
}
}
impl<T: StaticUpcast<QObject> + CppDeletable> Drop for QBox<T> {
fn drop(&mut self) {
unsafe {
let ptr = self.as_ptr();
if!ptr.is_null() && ptr.static_upcast().parent().is_null() |
}
}
}
| {
T::delete(&*ptr.as_raw_ptr());
} | conditional_block |
q_box.rs | use crate::{QObject, QPtr};
use cpp_core::{
CastFrom, CastInto, CppBox, CppDeletable, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast,
};
use std::ops::Deref;
use std::{fmt, mem};
/// An owning pointer for `QObject`-based objects.
///
/// `QBox` will delete its object on drop if it has no parent. If the object has a parent,
/// it's assumed that the parent is responsible for deleting the object, as per Qt ownership system.
/// Additionally, `QBox` will be automatically set to null when the object is deleted, similar
/// to `QPtr` (or `QPointer<T>` in C++). `QBox` will not attempt to delete null pointers.
///
/// Note that dereferencing a null `QBox` will panic, so if it's known that the object may
/// already have been deleted, you should use `is_null()`, `as_ref()`,
/// or a similar method to check
/// if the object is still alive before calling its methods.
///
/// Unlike `CppBox` (which is non-nullable), `QBox` is permitted to contain a null pointer because
/// even if a non-null pointer is provided when constructing `QBox`, it will become null
/// automatically if the object is deleted.
///
/// To prevent the object from being deleted, convert `QBox` to another type of pointer using
/// `into_q_ptr()` or `into_ptr()`. Alternatively, setting a parent for the object will prevent
/// `QBox` from deleting it.
///
/// To make sure the object is deleted regardless of its parent, convert `QBox` to `CppBox` using
/// `into_box()`.
///
/// # Safety
///
/// `QBox` has the same safety issues as `QPtr`. See `QPtr` documentation.
pub struct QBox<T: StaticUpcast<QObject> + CppDeletable>(QPtr<T>);
impl<T: StaticUpcast<QObject> + CppDeletable> QBox<T> {
/// Creates a `QBox` from a `QPtr`.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn from_q_ptr(target: QPtr<T>) -> Self {
QBox(target)
}
/// Creates a `QBox` from a `Ptr`.
///
/// ### Safety
///
/// `target` must be either a valid pointer to an object or a null pointer.
/// See type level documentation.
pub unsafe fn new(target: impl CastInto<Ptr<T>>) -> Self {
QBox::from_q_ptr(QPtr::new(target))
}
/// Creates a `QBox` from a raw pointer.
///
/// ### Safety
///
/// `target` must be either a valid pointer to an object or a null pointer.
/// See type level documentation.
pub unsafe fn from_raw(target: *const T) -> Self {
QBox::from_q_ptr(QPtr::from_raw(target))
}
/// Creates a null pointer.
///
/// Note that you can also use `NullPtr` to specify a null pointer to a function accepting
/// `impl CastInto<Ptr<_>>`. Unlike `Ptr`, `NullPtr` is not a generic type, so it will
/// not cause type inference issues.
///
/// Note that accessing the content of a null `QBox` through `Deref` will result
/// in a panic.
///
/// ### Safety
///
/// Null pointers must not be dereferenced. See type level documentation.
pub unsafe fn null() -> Self {
QBox::from_q_ptr(QPtr::<T>::null())
}
/// Returns true if the pointer is null.
pub unsafe fn is_null(&self) -> bool {
self.0.is_null()
}
/// Returns the content as a const `Ptr`.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_ptr(&self) -> Ptr<T> {
self.0.as_ptr()
}
/// Returns the content as a raw const pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_raw_ptr(&self) -> *const T {
self.0.as_raw_ptr()
}
/// Returns the content as a raw mutable pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_mut_raw_ptr(&self) -> *mut T {
self.0.as_mut_raw_ptr()
}
/// Returns the content as a const `Ref`. Returns `None` if `self` is a null pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_ref(&self) -> Option<Ref<T>> {
self.0.as_ref()
}
/// Returns a reference to the value. Returns `None` if the pointer is null.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_raw_ref<'a>(&self) -> Option<&'a T> {
self.as_ref().map(|r| r.as_raw_ref())
}
/// Returns a mutable reference to the value. Returns `None` if the pointer is null.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_mut_raw_ref<'a>(&self) -> Option<&'a mut T> {
self.as_ref().map(|r| r.as_mut_raw_ref())
}
/// Converts the pointer to the base class type `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid or null. See type level documentation.
pub unsafe fn static_upcast<U>(&self) -> QPtr<U>
where
T: StaticUpcast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().static_upcast::<U>())
}
/// Converts the pointer to the derived class type `U`.
///
/// It's recommended to use `dynamic_cast` instead because it performs a checked conversion.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid and it's type is `U` or inherits from `U`,
/// of if `self` is a null pointer. See type level documentation.
pub unsafe fn static_downcast<U>(&self) -> QPtr<U>
where
T: StaticDowncast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().static_downcast())
}
/// Converts the pointer to the derived class type `U`. Returns `None` if the object's type
/// is not `U` and doesn't inherit `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid or null. See type level documentation.
pub unsafe fn dynamic_cast<U>(&self) -> QPtr<U>
where
T: DynamicCast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().dynamic_cast())
}
/// Converts this pointer to a `CppBox`. Returns `None` if `self`
/// is a null pointer.
///
/// Unlike `QBox`, `CppBox` will always delete the object when dropped.
///
/// ### Safety
///
/// `CppBox` will attempt to delete the object on drop. If something else also tries to
/// delete this object before or after that, the behavior is undefined.
/// See type level documentation.
pub unsafe fn into_box(self) -> Option<CppBox<T>> {
self.into_q_ptr().to_box()
}
/// Converts this `QBox` into a `QPtr`.
///
/// Unlike `QBox`, `QPtr` will never delete the object when dropped.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_q_ptr(mut self) -> QPtr<T> {
mem::replace(&mut self.0, QPtr::null())
}
/// Converts this `QBox` into a `Ptr`.
///
/// Unlike `QBox`, `Ptr` will never delete the object when dropped.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_ptr(self) -> Ptr<T> {
self.into_q_ptr().as_ptr()
}
/// Converts this `QBox` into a raw pointer without deleting the object.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_raw_ptr(self) -> *mut T {
self.into_q_ptr().as_mut_raw_ptr()
}
}
impl<T: StaticUpcast<QObject> + CppDeletable> fmt::Debug for QBox<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "QBox({:?})", unsafe { self.as_raw_ptr() })
}
}
/// Allows to call member functions of `T` and its base classes directly on the pointer.
///
/// Panics if the pointer is null.
impl<T: StaticUpcast<QObject> + CppDeletable> Deref for QBox<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe {
let ptr = self.as_raw_ptr();
if ptr.is_null() {
panic!("attempted to deref a null QBox<T>");
}
&*ptr
}
}
}
impl<'a, T, U> CastFrom<&'a QBox<U>> for Ptr<T>
where
U: StaticUpcast<T> + StaticUpcast<QObject> + CppDeletable,
{
unsafe fn cast_from(value: &'a QBox<U>) -> Self {
CastFrom::cast_from(value.as_ptr())
}
}
impl<T: StaticUpcast<QObject> + CppDeletable> Drop for QBox<T> {
fn | (&mut self) {
unsafe {
let ptr = self.as_ptr();
if!ptr.is_null() && ptr.static_upcast().parent().is_null() {
T::delete(&*ptr.as_raw_ptr());
}
}
}
}
| drop | identifier_name |
q_box.rs | use crate::{QObject, QPtr};
use cpp_core::{
CastFrom, CastInto, CppBox, CppDeletable, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast,
};
use std::ops::Deref;
use std::{fmt, mem};
/// An owning pointer for `QObject`-based objects.
///
/// `QBox` will delete its object on drop if it has no parent. If the object has a parent,
/// it's assumed that the parent is responsible for deleting the object, as per Qt ownership system.
/// Additionally, `QBox` will be automatically set to null when the object is deleted, similar
/// to `QPtr` (or `QPointer<T>` in C++). `QBox` will not attempt to delete null pointers.
///
/// Note that dereferencing a null `QBox` will panic, so if it's known that the object may
/// already have been deleted, you should use `is_null()`, `as_ref()`,
/// or a similar method to check
/// if the object is still alive before calling its methods.
///
/// Unlike `CppBox` (which is non-nullable), `QBox` is permitted to contain a null pointer because
/// even if a non-null pointer is provided when constructing `QBox`, it will become null
/// automatically if the object is deleted.
///
/// To prevent the object from being deleted, convert `QBox` to another type of pointer using
/// `into_q_ptr()` or `into_ptr()`. Alternatively, setting a parent for the object will prevent
/// `QBox` from deleting it.
///
/// To make sure the object is deleted regardless of its parent, convert `QBox` to `CppBox` using
/// `into_box()`.
///
/// # Safety
///
/// `QBox` has the same safety issues as `QPtr`. See `QPtr` documentation.
pub struct QBox<T: StaticUpcast<QObject> + CppDeletable>(QPtr<T>);
impl<T: StaticUpcast<QObject> + CppDeletable> QBox<T> {
/// Creates a `QBox` from a `QPtr`.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn from_q_ptr(target: QPtr<T>) -> Self {
QBox(target)
}
/// Creates a `QBox` from a `Ptr`.
///
/// ### Safety
///
/// `target` must be either a valid pointer to an object or a null pointer.
/// See type level documentation.
pub unsafe fn new(target: impl CastInto<Ptr<T>>) -> Self {
QBox::from_q_ptr(QPtr::new(target))
}
/// Creates a `QBox` from a raw pointer.
///
/// ### Safety
///
/// `target` must be either a valid pointer to an object or a null pointer.
/// See type level documentation.
pub unsafe fn from_raw(target: *const T) -> Self {
QBox::from_q_ptr(QPtr::from_raw(target))
}
/// Creates a null pointer.
///
/// Note that you can also use `NullPtr` to specify a null pointer to a function accepting
/// `impl CastInto<Ptr<_>>`. Unlike `Ptr`, `NullPtr` is not a generic type, so it will
/// not cause type inference issues.
///
/// Note that accessing the content of a null `QBox` through `Deref` will result
/// in a panic.
///
/// ### Safety
///
/// Null pointers must not be dereferenced. See type level documentation.
pub unsafe fn null() -> Self {
QBox::from_q_ptr(QPtr::<T>::null())
}
/// Returns true if the pointer is null.
pub unsafe fn is_null(&self) -> bool {
self.0.is_null()
}
/// Returns the content as a const `Ptr`.
///
/// ### Safety
///
/// See type level documentation. | /// Returns the content as a raw const pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_raw_ptr(&self) -> *const T {
self.0.as_raw_ptr()
}
/// Returns the content as a raw mutable pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_mut_raw_ptr(&self) -> *mut T {
self.0.as_mut_raw_ptr()
}
/// Returns the content as a const `Ref`. Returns `None` if `self` is a null pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_ref(&self) -> Option<Ref<T>> {
self.0.as_ref()
}
/// Returns a reference to the value. Returns `None` if the pointer is null.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_raw_ref<'a>(&self) -> Option<&'a T> {
self.as_ref().map(|r| r.as_raw_ref())
}
/// Returns a mutable reference to the value. Returns `None` if the pointer is null.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_mut_raw_ref<'a>(&self) -> Option<&'a mut T> {
self.as_ref().map(|r| r.as_mut_raw_ref())
}
/// Converts the pointer to the base class type `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid or null. See type level documentation.
pub unsafe fn static_upcast<U>(&self) -> QPtr<U>
where
T: StaticUpcast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().static_upcast::<U>())
}
/// Converts the pointer to the derived class type `U`.
///
/// It's recommended to use `dynamic_cast` instead because it performs a checked conversion.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid and it's type is `U` or inherits from `U`,
/// of if `self` is a null pointer. See type level documentation.
pub unsafe fn static_downcast<U>(&self) -> QPtr<U>
where
T: StaticDowncast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().static_downcast())
}
/// Converts the pointer to the derived class type `U`. Returns `None` if the object's type
/// is not `U` and doesn't inherit `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid or null. See type level documentation.
pub unsafe fn dynamic_cast<U>(&self) -> QPtr<U>
where
T: DynamicCast<U>,
U: StaticUpcast<QObject>,
{
QPtr::<U>::new(self.as_ptr().dynamic_cast())
}
/// Converts this pointer to a `CppBox`. Returns `None` if `self`
/// is a null pointer.
///
/// Unlike `QBox`, `CppBox` will always delete the object when dropped.
///
/// ### Safety
///
/// `CppBox` will attempt to delete the object on drop. If something else also tries to
/// delete this object before or after that, the behavior is undefined.
/// See type level documentation.
pub unsafe fn into_box(self) -> Option<CppBox<T>> {
self.into_q_ptr().to_box()
}
/// Converts this `QBox` into a `QPtr`.
///
/// Unlike `QBox`, `QPtr` will never delete the object when dropped.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_q_ptr(mut self) -> QPtr<T> {
mem::replace(&mut self.0, QPtr::null())
}
/// Converts this `QBox` into a `Ptr`.
///
/// Unlike `QBox`, `Ptr` will never delete the object when dropped.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_ptr(self) -> Ptr<T> {
self.into_q_ptr().as_ptr()
}
/// Converts this `QBox` into a raw pointer without deleting the object.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn into_raw_ptr(self) -> *mut T {
self.into_q_ptr().as_mut_raw_ptr()
}
}
impl<T: StaticUpcast<QObject> + CppDeletable> fmt::Debug for QBox<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "QBox({:?})", unsafe { self.as_raw_ptr() })
}
}
/// Allows to call member functions of `T` and its base classes directly on the pointer.
///
/// Panics if the pointer is null.
impl<T: StaticUpcast<QObject> + CppDeletable> Deref for QBox<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe {
let ptr = self.as_raw_ptr();
if ptr.is_null() {
panic!("attempted to deref a null QBox<T>");
}
&*ptr
}
}
}
impl<'a, T, U> CastFrom<&'a QBox<U>> for Ptr<T>
where
U: StaticUpcast<T> + StaticUpcast<QObject> + CppDeletable,
{
unsafe fn cast_from(value: &'a QBox<U>) -> Self {
CastFrom::cast_from(value.as_ptr())
}
}
impl<T: StaticUpcast<QObject> + CppDeletable> Drop for QBox<T> {
fn drop(&mut self) {
unsafe {
let ptr = self.as_ptr();
if!ptr.is_null() && ptr.static_upcast().parent().is_null() {
T::delete(&*ptr.as_raw_ptr());
}
}
}
} | pub unsafe fn as_ptr(&self) -> Ptr<T> {
self.0.as_ptr()
}
| random_line_split |
platform.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use ::paint::{TextRuler, MathRuler};
use super::ruler::Ruler as SnapshotRuler;
use super::canvas::Canvas;
pub struct Platform {
ruler: SnapshotRuler,
}
impl Platform {
pub fn new(typeface: &str) -> Platform |
pub fn new_canvas(&self, width: f32, height: f32) -> Canvas {
Canvas::new(width.max(1.), height.max(1.),
self.ruler.get_sk_typeface())
}
}
impl ::platform::Platform for Platform {
fn get_text_ruler(&self, size: f32) -> &TextRuler {
self.ruler.set_size(size);
&self.ruler
}
fn get_math_ruler(&self, size: f32) -> &MathRuler {
self.ruler.set_size(size);
&self.ruler
}
fn px_to_du(&self, px: f32) -> f32 {
px
}
fn sp_to_du(&self, sp: f32) -> f32 {
64.*sp
}
fn dp_to_du(&self, dp: f32) -> f32 {
64.*dp
}
fn as_any(&self) -> &Any {
self
}
} | {
Platform { ruler: SnapshotRuler::new(typeface, 0) }
} | identifier_body |
platform.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use ::paint::{TextRuler, MathRuler};
use super::ruler::Ruler as SnapshotRuler;
use super::canvas::Canvas;
pub struct Platform {
ruler: SnapshotRuler,
}
impl Platform {
pub fn new(typeface: &str) -> Platform {
Platform { ruler: SnapshotRuler::new(typeface, 0) }
}
pub fn new_canvas(&self, width: f32, height: f32) -> Canvas {
Canvas::new(width.max(1.), height.max(1.),
self.ruler.get_sk_typeface())
}
}
impl ::platform::Platform for Platform {
fn | (&self, size: f32) -> &TextRuler {
self.ruler.set_size(size);
&self.ruler
}
fn get_math_ruler(&self, size: f32) -> &MathRuler {
self.ruler.set_size(size);
&self.ruler
}
fn px_to_du(&self, px: f32) -> f32 {
px
}
fn sp_to_du(&self, sp: f32) -> f32 {
64.*sp
}
fn dp_to_du(&self, dp: f32) -> f32 {
64.*dp
}
fn as_any(&self) -> &Any {
self
}
} | get_text_ruler | identifier_name |
platform.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* | * See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use ::paint::{TextRuler, MathRuler};
use super::ruler::Ruler as SnapshotRuler;
use super::canvas::Canvas;
pub struct Platform {
ruler: SnapshotRuler,
}
impl Platform {
pub fn new(typeface: &str) -> Platform {
Platform { ruler: SnapshotRuler::new(typeface, 0) }
}
pub fn new_canvas(&self, width: f32, height: f32) -> Canvas {
Canvas::new(width.max(1.), height.max(1.),
self.ruler.get_sk_typeface())
}
}
impl ::platform::Platform for Platform {
fn get_text_ruler(&self, size: f32) -> &TextRuler {
self.ruler.set_size(size);
&self.ruler
}
fn get_math_ruler(&self, size: f32) -> &MathRuler {
self.ruler.set_size(size);
&self.ruler
}
fn px_to_du(&self, px: f32) -> f32 {
px
}
fn sp_to_du(&self, sp: f32) -> f32 {
64.*sp
}
fn dp_to_du(&self, dp: f32) -> f32 {
64.*dp
}
fn as_any(&self) -> &Any {
self
}
} | * 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. | random_line_split |
lib.rs |
/// ""abc"", ""abc"
Str { terminated: bool },
/// "b"abc"", "b"abc"
ByteStr { terminated: bool },
/// "r"abc"", "r#"abc"#", "r####"ab"###"c"####", "r#"a"
RawStr { n_hashes: u16, err: Option<RawStrError> },
/// "br"abc"", "br#"abc"#", "br####"ab"###"c"####", "br#"a"
RawByteStr { n_hashes: u16, err: Option<RawStrError> },
}
/// Error produced validating a raw string. Represents cases like:
/// - `r##~"abcde"##`: `InvalidStarter`
/// - `r###"abcde"##`: `NoTerminator { expected: 3, found: 2, possible_terminator_offset: Some(11)`
/// - Too many `#`s (>65535): `TooManyDelimiters`
// perf note: It doesn't matter that this makes `Token` 36 bytes bigger. See #77629
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum RawStrError {
/// Non `#` characters exist between `r` and `"` eg. `r#~"..`
InvalidStarter { bad_char: char },
/// The string was never terminated. `possible_terminator_offset` is the number of characters after `r` or `br` where they
/// may have intended to terminate it.
NoTerminator { expected: usize, found: usize, possible_terminator_offset: Option<usize> },
/// More than 65535 `#`s exist.
TooManyDelimiters { found: usize },
}
/// Base of numeric literal encoding according to its prefix.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Base {
/// Literal starts with "0b".
Binary,
/// Literal starts with "0o".
Octal,
/// Literal starts with "0x".
Hexadecimal,
/// Literal doesn't contain a prefix.
Decimal,
}
/// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun",
/// but shebang isn't a part of rust syntax.
pub fn strip_shebang(input: &str) -> Option<usize> {
// Shebang must start with `#!` literally, without any preceding whitespace.
// For simplicity we consider any line starting with `#!` a shebang,
// regardless of restrictions put on shebangs by specific platforms.
if let Some(input_tail) = input.strip_prefix("#!") {
// Ok, this is a shebang but if the next non-whitespace token is `[`,
// then it may be valid Rust code, so consider it Rust code.
let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| {
!matches!(
tok,
TokenKind::Whitespace
| TokenKind::LineComment { doc_style: None }
| TokenKind::BlockComment { doc_style: None,.. }
)
});
if next_non_whitespace_token!= Some(TokenKind::OpenBracket) {
// No other choice than to consider this a shebang.
return Some(2 + input_tail.lines().next().unwrap_or_default().len());
}
}
None
}
/// Parses the first token from the provided input string.
pub fn first_token(input: &str) -> Token {
debug_assert!(!input.is_empty());
Cursor::new(input).advance_token()
}
/// Creates an iterator that produces tokens from the input string.
pub fn tokenize(mut input: &str) -> impl Iterator<Item = Token> + '_ {
std::iter::from_fn(move || {
if input.is_empty() {
return None;
}
let token = first_token(input);
input = &input[token.len..];
Some(token)
})
}
/// True if `c` is considered a whitespace according to Rust language definition.
/// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html)
/// for definitions of these classes.
pub fn is_whitespace(c: char) -> bool {
// This is Pattern_White_Space.
//
// Note that this set is stable (ie, it doesn't change with different
// Unicode versions), so it's ok to just hard-code the values.
matches!(
c,
// Usual ASCII suspects
'\u{0009}' // \t
| '\u{000A}' // \n
| '\u{000B}' // vertical tab
| '\u{000C}' // form feed
| '\u{000D}' // \r
| '\u{0020}' // space
// NEXT LINE from latin1
| '\u{0085}'
// Bidi markers
| '\u{200E}' // LEFT-TO-RIGHT MARK
| '\u{200F}' // RIGHT-TO-LEFT MARK
// Dedicated whitespace characters from Unicode
| '\u{2028}' // LINE SEPARATOR
| '\u{2029}' // PARAGRAPH SEPARATOR
)
}
/// True if `c` is valid as a first character of an identifier.
/// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
/// a formal definition of valid identifier name.
pub fn is_id_start(c: char) -> bool {
// This is XID_Start OR '_' (which formally is not a XID_Start).
c == '_' || unicode_xid::UnicodeXID::is_xid_start(c)
}
/// True if `c` is valid as a non-first character of an identifier.
/// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
/// a formal definition of valid identifier name.
pub fn is_id_continue(c: char) -> bool {
unicode_xid::UnicodeXID::is_xid_continue(c)
}
/// The passed string is lexically an identifier.
pub fn is_ident(string: &str) -> bool {
let mut chars = string.chars();
if let Some(start) = chars.next() {
is_id_start(start) && chars.all(is_id_continue)
} else {
false
}
}
impl Cursor<'_> {
/// Parses a token from the input string.
fn advance_token(&mut self) -> Token {
let first_char = self.bump().unwrap();
let token_kind = match first_char {
// Slash, comment or block comment.
'/' => match self.first() {
'/' => self.line_comment(),
'*' => self.block_comment(),
_ => Slash,
},
// Whitespace sequence.
c if is_whitespace(c) => self.whitespace(),
// Raw identifier, raw string literal or identifier.
'r' => match (self.first(), self.second()) {
('#', c1) if is_id_start(c1) => self.raw_ident(),
('#', _) | ('"', _) => {
let (n_hashes, err) = self.raw_double_quoted_string(1);
let suffix_start = self.len_consumed();
if err.is_none() {
self.eat_literal_suffix();
}
let kind = RawStr { n_hashes, err };
Literal { kind, suffix_start }
}
_ => self.ident_or_unknown_prefix(),
},
// Byte literal, byte string literal, raw byte string literal or identifier.
'b' => match (self.first(), self.second()) {
('\'', _) => {
self.bump();
let terminated = self.single_quoted_string();
let suffix_start = self.len_consumed();
if terminated {
self.eat_literal_suffix();
}
let kind = Byte { terminated };
Literal { kind, suffix_start }
}
('"', _) => {
self.bump();
let terminated = self.double_quoted_string();
let suffix_start = self.len_consumed();
if terminated {
self.eat_literal_suffix();
}
let kind = ByteStr { terminated };
Literal { kind, suffix_start }
}
('r', '"') | ('r', '#') => {
self.bump();
let (n_hashes, err) = self.raw_double_quoted_string(2);
let suffix_start = self.len_consumed();
if err.is_none() {
self.eat_literal_suffix();
}
let kind = RawByteStr { n_hashes, err };
Literal { kind, suffix_start }
}
_ => self.ident_or_unknown_prefix(),
},
// Identifier (this should be checked after other variant that can
// start as identifier).
c if is_id_start(c) => self.ident_or_unknown_prefix(),
// Numeric literal.
c @ '0'..='9' => {
let literal_kind = self.number(c);
let suffix_start = self.len_consumed();
self.eat_literal_suffix();
TokenKind::Literal { kind: literal_kind, suffix_start }
}
// One-symbol tokens.
';' => Semi,
',' => Comma,
'.' => Dot,
'(' => OpenParen,
')' => CloseParen,
'{' => OpenBrace,
'}' => CloseBrace,
'[' => OpenBracket,
']' => CloseBracket,
'@' => At,
'#' => Pound,
'~' => Tilde,
'?' => Question,
':' => Colon,
'$' => Dollar,
'=' => Eq,
'!' => Bang,
'<' => Lt,
'>' => Gt,
'-' => Minus,
'&' => And,
'|' => Or,
'+' => Plus,
'*' => Star,
'^' => Caret,
'%' => Percent,
// Lifetime or character literal.
'\'' => self.lifetime_or_char(),
// String literal.
'"' => {
let terminated = self.double_quoted_string();
let suffix_start = self.len_consumed();
if terminated {
self.eat_literal_suffix();
}
let kind = Str { terminated };
Literal { kind, suffix_start }
}
_ => Unknown,
};
Token::new(token_kind, self.len_consumed())
}
fn line_comment(&mut self) -> TokenKind {
debug_assert!(self.prev() == '/' && self.first() == '/');
self.bump();
let doc_style = match self.first() {
// `//!` is an inner line doc comment.
'!' => Some(DocStyle::Inner),
// `////` (more than 3 slashes) is not considered a doc comment.
'/' if self.second()!= '/' => Some(DocStyle::Outer),
_ => None,
};
self.eat_while(|c| c!= '\n');
LineComment { doc_style }
}
fn block_comment(&mut self) -> TokenKind {
debug_assert!(self.prev() == '/' && self.first() == '*');
self.bump();
let doc_style = match self.first() {
// `/*!` is an inner block doc comment.
'!' => Some(DocStyle::Inner),
// `/***` (more than 2 stars) is not considered a doc comment.
// `/**/` is not considered a doc comment.
'*' if!matches!(self.second(), '*' | '/') => Some(DocStyle::Outer),
_ => None,
};
let mut depth = 1usize;
while let Some(c) = self.bump() {
match c {
'/' if self.first() == '*' => {
self.bump();
depth += 1;
}
'*' if self.first() == '/' => {
self.bump();
depth -= 1;
if depth == 0 {
// This block comment is closed, so for a construction like "/* */ */"
// there will be a successfully parsed block comment "/* */"
// and " */" will be processed separately.
break;
}
}
_ => (),
}
}
BlockComment { doc_style, terminated: depth == 0 }
}
fn whitespace(&mut self) -> TokenKind {
debug_assert!(is_whitespace(self.prev()));
self.eat_while(is_whitespace);
Whitespace
}
fn raw_ident(&mut self) -> TokenKind {
debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second()));
// Eat "#" symbol.
self.bump();
// Eat the identifier part of RawIdent.
self.eat_identifier();
RawIdent
}
fn ident_or_unknown_prefix(&mut self) -> TokenKind {
debug_assert!(is_id_start(self.prev()));
// Start is already eaten, eat the rest of identifier.
self.eat_while(is_id_continue);
// Known prefixes must have been handled earlier. So if
// we see a prefix here, it is definitely an unknown prefix.
match self.first() {
'#' | '"' | '\'' => UnknownPrefix,
_ => Ident,
}
}
fn nu | mut self, first_digit: char) -> LiteralKind {
debug_assert!('0' <= self.prev() && self.prev() <= '9');
let mut base = Base::Decimal;
if first_digit == '0' {
// Attempt to parse encoding base.
let has_digits = match self.first() {
'b' => {
base = Base::Binary;
self.bump();
self.eat_decimal_digits()
}
'o' => {
base = Base::Octal;
self.bump();
self.eat_decimal_digits()
}
'x' => {
base = Base::Hexadecimal;
self.bump();
self.eat_hexadecimal_digits()
}
// Not a base prefix.
'0'..='9' | '_' | '.' | 'e' | 'E' => {
self.eat_decimal_digits();
true
}
// Just a 0.
_ => return Int { base, empty_int: false },
};
// Base prefix was provided, but there were no digits
// after it, e.g. "0x".
if!has_digits {
return Int { base, empty_int: true };
}
} else {
// No base prefix, parse number in the usual way.
self.eat_decimal_digits();
};
match self.first() {
// Don't be greedy if this is actually an
// integer literal followed by field/method access or a range pattern
// (`0..2` and `12.foo()`)
'.' if self.second()!= '.' &&!is_id_start(self.second()) => {
// might have stuff after the., and if it does, it needs to start
// with a number
self.bump();
let mut empty_exponent = false;
if self.first().is_digit(10) {
self.eat_decimal_digits();
match self.first() {
'e' | 'E' => {
self.bump();
empty_exponent =!self.eat_float_exponent();
}
_ => (),
}
}
Float { base, empty_exponent }
}
'e' | 'E' => {
self.bump();
let empty_exponent =!self.eat_float_exponent();
Float { base, empty_exponent }
}
_ => Int { base, empty_int: false },
}
}
fn lifetime_or_char(&mut self) -> TokenKind {
debug_assert!(self.prev() == '\'');
let can_be_a_lifetime = if self.second() == '\'' {
// It's surely not a lifetime.
false
} else {
// If the first symbol is valid for identifier, it can be a lifetime.
// Also check if it's a number for a better error reporting (so '0 will
// be reported as invalid lifetime and not as unterminated char literal).
is_id_start(self.first()) || self.first().is_digit(10)
};
if!can_be_a_lifetime {
let terminated = self.single_quoted_string();
let suffix_start = self.len_consumed();
if terminated {
self.eat_literal_suffix();
}
let kind = Char { terminated };
return Literal { kind, suffix_start };
}
// Either a lifetime or a character literal with
// length greater than 1.
let starts_with_number = self.first().is_digit(10);
// Skip the literal contents.
// First symbol can be a number (which isn't a valid identifier start),
// so skip it without any checks.
self.bump();
self.eat_while(is_id_continue);
// Check if after skipping literal contents we've met a closing
// single quote (which means that user attempted to create a
// string with single quotes).
if self.first() == '\'' {
self.bump();
let kind = Char { terminated: true };
Literal { kind, suffix_start: self.len_consumed() }
} else {
Lifetime { starts_with_number }
}
}
fn single_quoted_string(&mut self) -> bool {
debug_assert!(self.prev() == '\'');
// Check if it's a one-symbol literal.
if self.second() == '\'' && self.first()!= '\\' {
self.bump();
self.bump();
return true;
}
| mber(& | identifier_name |
lib.rs | Whitespace
| TokenKind::LineComment { doc_style: None }
| TokenKind::BlockComment { doc_style: None,.. }
)
});
if next_non_whitespace_token!= Some(TokenKind::OpenBracket) {
// No other choice than to consider this a shebang.
return Some(2 + input_tail.lines().next().unwrap_or_default().len());
}
}
None
}
/// Parses the first token from the provided input string.
pub fn first_token(input: &str) -> Token {
debug_assert!(!input.is_empty());
Cursor::new(input).advance_token()
}
/// Creates an iterator that produces tokens from the input string.
pub fn tokenize(mut input: &str) -> impl Iterator<Item = Token> + '_ {
std::iter::from_fn(move || {
if input.is_empty() {
return None;
}
let token = first_token(input);
input = &input[token.len..];
Some(token)
})
}
/// True if `c` is considered a whitespace according to Rust language definition.
/// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html)
/// for definitions of these classes.
pub fn is_whitespace(c: char) -> bool {
// This is Pattern_White_Space.
//
// Note that this set is stable (ie, it doesn't change with different
// Unicode versions), so it's ok to just hard-code the values.
matches!(
c,
// Usual ASCII suspects
'\u{0009}' // \t
| '\u{000A}' // \n
| '\u{000B}' // vertical tab
| '\u{000C}' // form feed
| '\u{000D}' // \r
| '\u{0020}' // space
// NEXT LINE from latin1
| '\u{0085}'
// Bidi markers
| '\u{200E}' // LEFT-TO-RIGHT MARK
| '\u{200F}' // RIGHT-TO-LEFT MARK
// Dedicated whitespace characters from Unicode
| '\u{2028}' // LINE SEPARATOR
| '\u{2029}' // PARAGRAPH SEPARATOR
)
}
/// True if `c` is valid as a first character of an identifier.
/// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
/// a formal definition of valid identifier name.
pub fn is_id_start(c: char) -> bool {
// This is XID_Start OR '_' (which formally is not a XID_Start).
c == '_' || unicode_xid::UnicodeXID::is_xid_start(c)
}
/// True if `c` is valid as a non-first character of an identifier.
/// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
/// a formal definition of valid identifier name.
pub fn is_id_continue(c: char) -> bool {
unicode_xid::UnicodeXID::is_xid_continue(c)
}
/// The passed string is lexically an identifier.
pub fn is_ident(string: &str) -> bool {
let mut chars = string.chars();
if let Some(start) = chars.next() {
is_id_start(start) && chars.all(is_id_continue)
} else {
false
}
}
impl Cursor<'_> {
/// Parses a token from the input string.
fn advance_token(&mut self) -> Token {
let first_char = self.bump().unwrap();
let token_kind = match first_char {
// Slash, comment or block comment.
'/' => match self.first() {
'/' => self.line_comment(),
'*' => self.block_comment(),
_ => Slash,
},
// Whitespace sequence.
c if is_whitespace(c) => self.whitespace(),
// Raw identifier, raw string literal or identifier.
'r' => match (self.first(), self.second()) {
('#', c1) if is_id_start(c1) => self.raw_ident(),
('#', _) | ('"', _) => {
let (n_hashes, err) = self.raw_double_quoted_string(1);
let suffix_start = self.len_consumed();
if err.is_none() {
self.eat_literal_suffix();
}
let kind = RawStr { n_hashes, err };
Literal { kind, suffix_start }
}
_ => self.ident_or_unknown_prefix(),
},
// Byte literal, byte string literal, raw byte string literal or identifier.
'b' => match (self.first(), self.second()) {
('\'', _) => {
self.bump();
let terminated = self.single_quoted_string();
let suffix_start = self.len_consumed();
if terminated {
self.eat_literal_suffix();
}
let kind = Byte { terminated };
Literal { kind, suffix_start }
}
('"', _) => {
self.bump();
let terminated = self.double_quoted_string();
let suffix_start = self.len_consumed();
if terminated {
self.eat_literal_suffix();
}
let kind = ByteStr { terminated };
Literal { kind, suffix_start }
}
('r', '"') | ('r', '#') => {
self.bump();
let (n_hashes, err) = self.raw_double_quoted_string(2);
let suffix_start = self.len_consumed();
if err.is_none() {
self.eat_literal_suffix();
}
let kind = RawByteStr { n_hashes, err };
Literal { kind, suffix_start }
}
_ => self.ident_or_unknown_prefix(),
},
// Identifier (this should be checked after other variant that can
// start as identifier).
c if is_id_start(c) => self.ident_or_unknown_prefix(),
// Numeric literal.
c @ '0'..='9' => {
let literal_kind = self.number(c);
let suffix_start = self.len_consumed();
self.eat_literal_suffix();
TokenKind::Literal { kind: literal_kind, suffix_start }
}
// One-symbol tokens.
';' => Semi,
',' => Comma,
'.' => Dot,
'(' => OpenParen,
')' => CloseParen,
'{' => OpenBrace,
'}' => CloseBrace,
'[' => OpenBracket,
']' => CloseBracket,
'@' => At,
'#' => Pound,
'~' => Tilde,
'?' => Question,
':' => Colon,
'$' => Dollar,
'=' => Eq,
'!' => Bang,
'<' => Lt,
'>' => Gt,
'-' => Minus,
'&' => And,
'|' => Or,
'+' => Plus,
'*' => Star,
'^' => Caret,
'%' => Percent,
// Lifetime or character literal.
'\'' => self.lifetime_or_char(),
// String literal.
'"' => {
let terminated = self.double_quoted_string();
let suffix_start = self.len_consumed();
if terminated {
self.eat_literal_suffix();
}
let kind = Str { terminated };
Literal { kind, suffix_start }
}
_ => Unknown,
};
Token::new(token_kind, self.len_consumed())
}
fn line_comment(&mut self) -> TokenKind {
debug_assert!(self.prev() == '/' && self.first() == '/');
self.bump();
let doc_style = match self.first() {
// `//!` is an inner line doc comment.
'!' => Some(DocStyle::Inner),
// `////` (more than 3 slashes) is not considered a doc comment.
'/' if self.second()!= '/' => Some(DocStyle::Outer),
_ => None,
};
self.eat_while(|c| c!= '\n');
LineComment { doc_style }
}
fn block_comment(&mut self) -> TokenKind {
debug_assert!(self.prev() == '/' && self.first() == '*');
self.bump();
let doc_style = match self.first() {
// `/*!` is an inner block doc comment.
'!' => Some(DocStyle::Inner),
// `/***` (more than 2 stars) is not considered a doc comment.
// `/**/` is not considered a doc comment.
'*' if!matches!(self.second(), '*' | '/') => Some(DocStyle::Outer),
_ => None,
};
let mut depth = 1usize;
while let Some(c) = self.bump() {
match c {
'/' if self.first() == '*' => {
self.bump();
depth += 1;
}
'*' if self.first() == '/' => {
self.bump();
depth -= 1;
if depth == 0 {
// This block comment is closed, so for a construction like "/* */ */"
// there will be a successfully parsed block comment "/* */"
// and " */" will be processed separately.
break;
}
}
_ => (),
}
}
BlockComment { doc_style, terminated: depth == 0 }
}
fn whitespace(&mut self) -> TokenKind {
debug_assert!(is_whitespace(self.prev()));
self.eat_while(is_whitespace);
Whitespace
}
fn raw_ident(&mut self) -> TokenKind {
debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second()));
// Eat "#" symbol.
self.bump();
// Eat the identifier part of RawIdent.
self.eat_identifier();
RawIdent
}
fn ident_or_unknown_prefix(&mut self) -> TokenKind {
debug_assert!(is_id_start(self.prev()));
// Start is already eaten, eat the rest of identifier.
self.eat_while(is_id_continue);
// Known prefixes must have been handled earlier. So if
// we see a prefix here, it is definitely an unknown prefix.
match self.first() {
'#' | '"' | '\'' => UnknownPrefix,
_ => Ident,
}
}
fn number(&mut self, first_digit: char) -> LiteralKind {
debug_assert!('0' <= self.prev() && self.prev() <= '9');
let mut base = Base::Decimal;
if first_digit == '0' {
// Attempt to parse encoding base.
let has_digits = match self.first() {
'b' => {
base = Base::Binary;
self.bump();
self.eat_decimal_digits()
}
'o' => {
base = Base::Octal;
self.bump();
self.eat_decimal_digits()
}
'x' => {
base = Base::Hexadecimal;
self.bump();
self.eat_hexadecimal_digits()
}
// Not a base prefix.
'0'..='9' | '_' | '.' | 'e' | 'E' => {
self.eat_decimal_digits();
true
}
// Just a 0.
_ => return Int { base, empty_int: false },
};
// Base prefix was provided, but there were no digits
// after it, e.g. "0x".
if!has_digits {
return Int { base, empty_int: true };
}
} else {
// No base prefix, parse number in the usual way.
self.eat_decimal_digits();
};
match self.first() {
// Don't be greedy if this is actually an
// integer literal followed by field/method access or a range pattern
// (`0..2` and `12.foo()`)
'.' if self.second()!= '.' &&!is_id_start(self.second()) => {
// might have stuff after the., and if it does, it needs to start
// with a number
self.bump();
let mut empty_exponent = false;
if self.first().is_digit(10) {
self.eat_decimal_digits();
match self.first() {
'e' | 'E' => {
self.bump();
empty_exponent =!self.eat_float_exponent();
}
_ => (),
}
}
Float { base, empty_exponent }
}
'e' | 'E' => {
self.bump();
let empty_exponent =!self.eat_float_exponent();
Float { base, empty_exponent }
}
_ => Int { base, empty_int: false },
}
}
fn lifetime_or_char(&mut self) -> TokenKind {
debug_assert!(self.prev() == '\'');
let can_be_a_lifetime = if self.second() == '\'' {
// It's surely not a lifetime.
false
} else {
// If the first symbol is valid for identifier, it can be a lifetime.
// Also check if it's a number for a better error reporting (so '0 will
// be reported as invalid lifetime and not as unterminated char literal).
is_id_start(self.first()) || self.first().is_digit(10)
};
if!can_be_a_lifetime {
let terminated = self.single_quoted_string();
let suffix_start = self.len_consumed();
if terminated {
self.eat_literal_suffix();
}
let kind = Char { terminated };
return Literal { kind, suffix_start };
}
// Either a lifetime or a character literal with
// length greater than 1.
let starts_with_number = self.first().is_digit(10);
// Skip the literal contents.
// First symbol can be a number (which isn't a valid identifier start),
// so skip it without any checks.
self.bump();
self.eat_while(is_id_continue);
// Check if after skipping literal contents we've met a closing
// single quote (which means that user attempted to create a
// string with single quotes).
if self.first() == '\'' {
self.bump();
let kind = Char { terminated: true };
Literal { kind, suffix_start: self.len_consumed() }
} else {
Lifetime { starts_with_number }
}
}
fn single_quoted_string(&mut self) -> bool {
debug_assert!(self.prev() == '\'');
// Check if it's a one-symbol literal.
if self.second() == '\'' && self.first()!= '\\' {
self.bump();
self.bump();
return true;
}
// Literal has more than one symbol.
// Parse until either quotes are terminated or error is detected.
loop {
match self.first() {
// Quotes are terminated, finish parsing.
'\'' => {
self.bump();
return true;
}
// Probably beginning of the comment, which we don't want to include
// to the error report.
'/' => break,
// Newline without following '\'' means unclosed quote, stop parsing.
'\n' if self.second()!= '\'' => break,
// End of file, stop parsing.
EOF_CHAR if self.is_eof() => break,
// Escaped slash is considered one character, so bump twice.
'\\' => {
self.bump();
self.bump();
}
// Skip the character.
_ => {
self.bump();
}
}
}
// String was not terminated.
false
}
/// Eats double-quoted string and returns true
/// if string is terminated.
fn double_quoted_string(&mut self) -> bool {
debug_assert!(self.prev() == '"');
while let Some(c) = self.bump() {
match c {
'"' => {
return true;
}
'\\' if self.first() == '\\' || self.first() == '"' => { | // Bump again to skip escaped character. | random_line_split |
|
portal.rs | use crate::compat::Mutex;
use crate::screen::{Screen, ScreenBuffer};
use alloc::sync::Arc;
use core::mem;
use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer};
use graphics_base::system::{DeletedIndex, System};
use graphics_base::types::Rect;
use graphics_base::Result;
use hecs::World;
#[cfg(target_os = "rust_os")]
mod rust_os {
use alloc::sync::Arc;
use graphics_base::ipc;
use graphics_base::types::{Event, EventInput};
use graphics_base::Result;
use os::{File, Mutex};
#[derive(Clone)]
pub struct PortalRef {
pub server2client: Arc<Mutex<File>>,
pub portal_id: usize,
}
impl PartialEq for PortalRef {
fn eq(&self, other: &Self) -> bool {
self.portal_id == other.portal_id && Arc::ptr_eq(&self.server2client, &other.server2client)
}
}
impl PortalRef {
pub fn send_input(&self, input: EventInput) -> Result<()> {
let mut server2client = self.server2client.lock();
ipc::send_message(
&mut *server2client,
&Event::Input {
portal_id: self.portal_id,
input,
},
)
}
}
}
#[cfg(not(target_os = "rust_os"))]
mod posix {
use graphics_base::types::{Event, EventInput};
use graphics_base::Result;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
#[derive(Clone)]
pub struct PortalRef {
pub portal_id: usize,
pub events: Rc<RefCell<VecDeque<Event>>>,
}
impl PartialEq for PortalRef {
fn eq(&self, other: &Self) -> bool {
self.portal_id == other.portal_id && Rc::ptr_eq(&self.events, &other.events)
}
}
impl PortalRef {
pub fn send_input(&self, input: EventInput) -> Result<()> {
let event = Event::Input {
portal_id: self.portal_id,
input,
};
self.events.borrow_mut().push_back(event);
Ok(())
}
}
}
#[cfg(target_os = "rust_os")]
pub use rust_os::PortalRef;
#[cfg(not(target_os = "rust_os"))]
pub use posix::PortalRef;
pub struct ServerPortal {
portal_ref: PortalRef,
pos: Rect,
prev_pos: Rect,
z_index: usize,
frame_buffer_id: usize,
frame_buffer_size: (u16, u16),
frame_buffer: Arc<FrameBuffer>,
needs_paint: bool,
}
impl ServerPortal {
pub fn new(
world: &World,
portal_ref: PortalRef,
pos: Rect,
frame_buffer_id: usize,
frame_buffer_size: (u16, u16),
frame_buffer: FrameBuffer,
) -> Self {
let z_index = world
.query::<&Self>()
.iter()
.map(|(_, portal)| &portal.z_index)
.max()
.cloned()
.unwrap_or(0);
Self {
portal_ref,
pos,
prev_pos: pos,
z_index,
frame_buffer_id,
frame_buffer_size,
frame_buffer: Arc::new(frame_buffer),
needs_paint: true,
}
}
}
impl ServerPortal {
pub fn move_to(&mut self, pos: Rect) {
self.pos = pos;
}
pub fn draw(&mut self, frame_buffer_id: usize, frame_buffer_size: (u16, u16), frame_buffer: FrameBuffer) -> usize {
self.frame_buffer_size = frame_buffer_size;
self.frame_buffer = Arc::new(frame_buffer);
self.needs_paint = true;
mem::replace(&mut self.frame_buffer_id, frame_buffer_id)
}
}
impl ServerPortal {
fn as_screen_buffer(&self) -> ScreenBuffer {
ScreenBuffer {
pos: self.pos,
frame_buffer_size: self.frame_buffer_size,
frame_buffer: Arc::downgrade(&self.frame_buffer),
portal_ref: self.portal_ref.clone(),
}
}
}
pub struct | <S> {
screen: Arc<Mutex<Screen<S>>>,
input_state: Arc<Mutex<Option<PortalRef>>>,
deleted_index: DeletedIndex<()>,
}
impl<S> ServerPortalSystem<S> {
pub fn new(screen: Arc<Mutex<Screen<S>>>, input_state: Arc<Mutex<Option<PortalRef>>>) -> Self {
ServerPortalSystem {
screen,
input_state,
deleted_index: DeletedIndex::new(),
}
}
}
impl<S> System for ServerPortalSystem<S>
where
S: AsSurfaceMut,
{
fn run(&mut self, world: &mut World) -> Result<()> {
let mut portals_borrow = world.query::<&mut ServerPortal>();
let mut portals = portals_borrow.iter().map(|(_, portal)| portal).collect::<Vec<_>>();
portals.sort_by(|a, b| a.z_index.cmp(&b.z_index));
for portal in portals.iter_mut() {
if portal.prev_pos!= portal.pos {
portal.prev_pos = portal.pos;
portal.needs_paint = true;
}
}
*self.input_state.lock() = portals.last().map(|p| p.portal_ref.clone());
let deleted_entities = self
.deleted_index
.update(world.query::<()>().with::<ServerPortal>().iter());
if!deleted_entities.is_empty() || portals.iter().any(|p| p.needs_paint) {
self.screen
.lock()
.update_buffers(portals.iter_mut().rev().map(|portal| {
portal.needs_paint = false;
portal.as_screen_buffer()
}));
}
Ok(())
}
}
| ServerPortalSystem | identifier_name |
portal.rs | use crate::compat::Mutex;
use crate::screen::{Screen, ScreenBuffer};
use alloc::sync::Arc;
use core::mem;
use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer};
use graphics_base::system::{DeletedIndex, System};
use graphics_base::types::Rect;
use graphics_base::Result;
use hecs::World;
#[cfg(target_os = "rust_os")]
mod rust_os {
use alloc::sync::Arc;
use graphics_base::ipc;
use graphics_base::types::{Event, EventInput};
use graphics_base::Result;
use os::{File, Mutex};
#[derive(Clone)]
pub struct PortalRef {
pub server2client: Arc<Mutex<File>>,
pub portal_id: usize,
}
impl PartialEq for PortalRef {
fn eq(&self, other: &Self) -> bool {
self.portal_id == other.portal_id && Arc::ptr_eq(&self.server2client, &other.server2client)
}
}
impl PortalRef {
pub fn send_input(&self, input: EventInput) -> Result<()> {
let mut server2client = self.server2client.lock();
ipc::send_message(
&mut *server2client,
&Event::Input {
portal_id: self.portal_id,
input,
},
)
}
}
}
#[cfg(not(target_os = "rust_os"))]
mod posix {
use graphics_base::types::{Event, EventInput};
use graphics_base::Result;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
#[derive(Clone)]
pub struct PortalRef {
pub portal_id: usize,
pub events: Rc<RefCell<VecDeque<Event>>>,
}
impl PartialEq for PortalRef {
fn eq(&self, other: &Self) -> bool {
self.portal_id == other.portal_id && Rc::ptr_eq(&self.events, &other.events)
}
}
impl PortalRef {
pub fn send_input(&self, input: EventInput) -> Result<()> {
let event = Event::Input {
portal_id: self.portal_id,
input,
};
self.events.borrow_mut().push_back(event);
Ok(())
}
}
}
#[cfg(target_os = "rust_os")]
pub use rust_os::PortalRef;
#[cfg(not(target_os = "rust_os"))]
pub use posix::PortalRef;
pub struct ServerPortal {
portal_ref: PortalRef,
pos: Rect,
prev_pos: Rect,
z_index: usize,
frame_buffer_id: usize,
frame_buffer_size: (u16, u16),
frame_buffer: Arc<FrameBuffer>,
needs_paint: bool,
}
impl ServerPortal {
pub fn new(
world: &World,
portal_ref: PortalRef,
pos: Rect,
frame_buffer_id: usize,
frame_buffer_size: (u16, u16),
frame_buffer: FrameBuffer,
) -> Self {
let z_index = world
.query::<&Self>()
.iter()
.map(|(_, portal)| &portal.z_index)
.max()
.cloned()
.unwrap_or(0);
Self {
portal_ref,
pos,
prev_pos: pos,
z_index,
frame_buffer_id,
frame_buffer_size,
frame_buffer: Arc::new(frame_buffer),
needs_paint: true,
}
}
}
impl ServerPortal {
pub fn move_to(&mut self, pos: Rect) {
self.pos = pos;
}
pub fn draw(&mut self, frame_buffer_id: usize, frame_buffer_size: (u16, u16), frame_buffer: FrameBuffer) -> usize {
self.frame_buffer_size = frame_buffer_size;
self.frame_buffer = Arc::new(frame_buffer);
self.needs_paint = true;
mem::replace(&mut self.frame_buffer_id, frame_buffer_id)
}
}
impl ServerPortal {
fn as_screen_buffer(&self) -> ScreenBuffer {
ScreenBuffer {
pos: self.pos,
frame_buffer_size: self.frame_buffer_size,
frame_buffer: Arc::downgrade(&self.frame_buffer),
portal_ref: self.portal_ref.clone(),
}
}
}
pub struct ServerPortalSystem<S> {
screen: Arc<Mutex<Screen<S>>>,
input_state: Arc<Mutex<Option<PortalRef>>>,
deleted_index: DeletedIndex<()>,
}
impl<S> ServerPortalSystem<S> {
pub fn new(screen: Arc<Mutex<Screen<S>>>, input_state: Arc<Mutex<Option<PortalRef>>>) -> Self {
ServerPortalSystem {
screen,
input_state,
deleted_index: DeletedIndex::new(),
}
}
}
impl<S> System for ServerPortalSystem<S>
where
S: AsSurfaceMut,
{
fn run(&mut self, world: &mut World) -> Result<()> {
let mut portals_borrow = world.query::<&mut ServerPortal>();
let mut portals = portals_borrow.iter().map(|(_, portal)| portal).collect::<Vec<_>>();
portals.sort_by(|a, b| a.z_index.cmp(&b.z_index));
for portal in portals.iter_mut() {
if portal.prev_pos!= portal.pos |
}
*self.input_state.lock() = portals.last().map(|p| p.portal_ref.clone());
let deleted_entities = self
.deleted_index
.update(world.query::<()>().with::<ServerPortal>().iter());
if!deleted_entities.is_empty() || portals.iter().any(|p| p.needs_paint) {
self.screen
.lock()
.update_buffers(portals.iter_mut().rev().map(|portal| {
portal.needs_paint = false;
portal.as_screen_buffer()
}));
}
Ok(())
}
}
| {
portal.prev_pos = portal.pos;
portal.needs_paint = true;
} | conditional_block |
portal.rs | use crate::compat::Mutex;
use crate::screen::{Screen, ScreenBuffer};
use alloc::sync::Arc;
use core::mem;
use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer};
use graphics_base::system::{DeletedIndex, System};
use graphics_base::types::Rect;
use graphics_base::Result;
use hecs::World;
#[cfg(target_os = "rust_os")]
mod rust_os {
use alloc::sync::Arc;
use graphics_base::ipc;
use graphics_base::types::{Event, EventInput};
use graphics_base::Result;
use os::{File, Mutex};
#[derive(Clone)]
pub struct PortalRef {
pub server2client: Arc<Mutex<File>>,
pub portal_id: usize,
}
impl PartialEq for PortalRef {
fn eq(&self, other: &Self) -> bool {
self.portal_id == other.portal_id && Arc::ptr_eq(&self.server2client, &other.server2client)
}
}
impl PortalRef {
pub fn send_input(&self, input: EventInput) -> Result<()> {
let mut server2client = self.server2client.lock();
ipc::send_message(
&mut *server2client,
&Event::Input {
portal_id: self.portal_id,
input,
},
)
}
}
}
#[cfg(not(target_os = "rust_os"))]
mod posix {
use graphics_base::types::{Event, EventInput};
use graphics_base::Result;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc; | pub events: Rc<RefCell<VecDeque<Event>>>,
}
impl PartialEq for PortalRef {
fn eq(&self, other: &Self) -> bool {
self.portal_id == other.portal_id && Rc::ptr_eq(&self.events, &other.events)
}
}
impl PortalRef {
pub fn send_input(&self, input: EventInput) -> Result<()> {
let event = Event::Input {
portal_id: self.portal_id,
input,
};
self.events.borrow_mut().push_back(event);
Ok(())
}
}
}
#[cfg(target_os = "rust_os")]
pub use rust_os::PortalRef;
#[cfg(not(target_os = "rust_os"))]
pub use posix::PortalRef;
pub struct ServerPortal {
portal_ref: PortalRef,
pos: Rect,
prev_pos: Rect,
z_index: usize,
frame_buffer_id: usize,
frame_buffer_size: (u16, u16),
frame_buffer: Arc<FrameBuffer>,
needs_paint: bool,
}
impl ServerPortal {
pub fn new(
world: &World,
portal_ref: PortalRef,
pos: Rect,
frame_buffer_id: usize,
frame_buffer_size: (u16, u16),
frame_buffer: FrameBuffer,
) -> Self {
let z_index = world
.query::<&Self>()
.iter()
.map(|(_, portal)| &portal.z_index)
.max()
.cloned()
.unwrap_or(0);
Self {
portal_ref,
pos,
prev_pos: pos,
z_index,
frame_buffer_id,
frame_buffer_size,
frame_buffer: Arc::new(frame_buffer),
needs_paint: true,
}
}
}
impl ServerPortal {
pub fn move_to(&mut self, pos: Rect) {
self.pos = pos;
}
pub fn draw(&mut self, frame_buffer_id: usize, frame_buffer_size: (u16, u16), frame_buffer: FrameBuffer) -> usize {
self.frame_buffer_size = frame_buffer_size;
self.frame_buffer = Arc::new(frame_buffer);
self.needs_paint = true;
mem::replace(&mut self.frame_buffer_id, frame_buffer_id)
}
}
impl ServerPortal {
fn as_screen_buffer(&self) -> ScreenBuffer {
ScreenBuffer {
pos: self.pos,
frame_buffer_size: self.frame_buffer_size,
frame_buffer: Arc::downgrade(&self.frame_buffer),
portal_ref: self.portal_ref.clone(),
}
}
}
pub struct ServerPortalSystem<S> {
screen: Arc<Mutex<Screen<S>>>,
input_state: Arc<Mutex<Option<PortalRef>>>,
deleted_index: DeletedIndex<()>,
}
impl<S> ServerPortalSystem<S> {
pub fn new(screen: Arc<Mutex<Screen<S>>>, input_state: Arc<Mutex<Option<PortalRef>>>) -> Self {
ServerPortalSystem {
screen,
input_state,
deleted_index: DeletedIndex::new(),
}
}
}
impl<S> System for ServerPortalSystem<S>
where
S: AsSurfaceMut,
{
fn run(&mut self, world: &mut World) -> Result<()> {
let mut portals_borrow = world.query::<&mut ServerPortal>();
let mut portals = portals_borrow.iter().map(|(_, portal)| portal).collect::<Vec<_>>();
portals.sort_by(|a, b| a.z_index.cmp(&b.z_index));
for portal in portals.iter_mut() {
if portal.prev_pos!= portal.pos {
portal.prev_pos = portal.pos;
portal.needs_paint = true;
}
}
*self.input_state.lock() = portals.last().map(|p| p.portal_ref.clone());
let deleted_entities = self
.deleted_index
.update(world.query::<()>().with::<ServerPortal>().iter());
if!deleted_entities.is_empty() || portals.iter().any(|p| p.needs_paint) {
self.screen
.lock()
.update_buffers(portals.iter_mut().rev().map(|portal| {
portal.needs_paint = false;
portal.as_screen_buffer()
}));
}
Ok(())
}
} |
#[derive(Clone)]
pub struct PortalRef {
pub portal_id: usize, | random_line_split |
memory.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/>.
use util::U256;
pub trait Memory {
/// Retrieve current size of the memory
fn size(&self) -> usize;
/// Resize (shrink or expand) the memory to specified size (fills 0)
fn resize(&mut self, new_size: usize);
/// Resize the memory only if its smaller
fn expand(&mut self, new_size: usize);
/// Write single byte to memory
fn write_byte(&mut self, offset: U256, value: U256);
/// Write a word to memory. Does not resize memory!
fn write(&mut self, offset: U256, value: U256);
/// Read a word from memory
fn read(&self, offset: U256) -> U256;
/// Write slice of bytes to memory. Does not resize memory!
fn write_slice(&mut self, offset: U256, &[u8]);
/// Retrieve part of the memory between offset and offset + size
fn read_slice(&self, offset: U256, size: U256) -> &[u8];
/// Retrieve writeable part of memory
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8];
fn dump(&self);
}
/// Checks whether offset and size is valid memory range
fn is_valid_range(off: usize, size: usize) -> bool {
// When size is zero we haven't actually expanded the memory
let overflow = off.overflowing_add(size).1;
size > 0 &&!overflow
}
impl Memory for Vec<u8> {
fn dump(&self) {
println!("MemoryDump:");
for i in self.iter() {
println!("{:02x} ", i);
}
println!("");
}
fn size(&self) -> usize {
self.len()
}
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
let off = init_off_u.low_u64() as usize;
let size = init_size_u.low_u64() as usize;
if!is_valid_range(off, size) { &self[0..0] } else { &self[off..off + size] }
}
fn read(&self, offset: U256) -> U256 {
let off = offset.low_u64() as usize;
U256::from(&self[off..off + 32])
}
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] {
let off = offset.low_u64() as usize;
let s = size.low_u64() as usize;
if!is_valid_range(off, s) { &mut self[0..0] } else { &mut self[off..off + s] }
}
fn | (&mut self, offset: U256, slice: &[u8]) {
let off = offset.low_u64() as usize;
// TODO [todr] Optimize?
for pos in off..off + slice.len() {
self[pos] = slice[pos - off];
}
}
fn write(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
value.to_big_endian(&mut self[off..off + 32]);
}
fn write_byte(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
let val = value.low_u64() as u64;
self[off] = val as u8;
}
fn resize(&mut self, new_size: usize) {
self.resize(new_size, 0);
}
fn expand(&mut self, size: usize) {
if size > self.len() {
Memory::resize(self, size)
}
}
}
#[test]
fn test_memory_read_and_write() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(0x80 + 32);
// when
mem.write(U256::from(0x80), U256::from(0xabcdef));
// then
assert_eq!(mem.read(U256::from(0x80)), U256::from(0xabcdef));
}
#[test]
fn test_memory_read_and_write_byte() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(32);
// when
mem.write_byte(U256::from(0x1d), U256::from(0xab));
mem.write_byte(U256::from(0x1e), U256::from(0xcd));
mem.write_byte(U256::from(0x1f), U256::from(0xef));
// then
assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef));
}
| write_slice | identifier_name |
memory.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/>.
use util::U256;
pub trait Memory {
/// Retrieve current size of the memory
fn size(&self) -> usize;
/// Resize (shrink or expand) the memory to specified size (fills 0)
fn resize(&mut self, new_size: usize);
/// Resize the memory only if its smaller
fn expand(&mut self, new_size: usize);
/// Write single byte to memory
fn write_byte(&mut self, offset: U256, value: U256);
/// Write a word to memory. Does not resize memory!
fn write(&mut self, offset: U256, value: U256);
/// Read a word from memory
fn read(&self, offset: U256) -> U256;
/// Write slice of bytes to memory. Does not resize memory!
fn write_slice(&mut self, offset: U256, &[u8]);
/// Retrieve part of the memory between offset and offset + size
fn read_slice(&self, offset: U256, size: U256) -> &[u8];
/// Retrieve writeable part of memory
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8];
fn dump(&self);
}
/// Checks whether offset and size is valid memory range
fn is_valid_range(off: usize, size: usize) -> bool {
// When size is zero we haven't actually expanded the memory
let overflow = off.overflowing_add(size).1;
size > 0 &&!overflow
}
impl Memory for Vec<u8> {
fn dump(&self) {
println!("MemoryDump:");
for i in self.iter() {
println!("{:02x} ", i);
}
println!("");
}
fn size(&self) -> usize |
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
let off = init_off_u.low_u64() as usize;
let size = init_size_u.low_u64() as usize;
if!is_valid_range(off, size) { &self[0..0] } else { &self[off..off + size] }
}
fn read(&self, offset: U256) -> U256 {
let off = offset.low_u64() as usize;
U256::from(&self[off..off + 32])
}
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] {
let off = offset.low_u64() as usize;
let s = size.low_u64() as usize;
if!is_valid_range(off, s) { &mut self[0..0] } else { &mut self[off..off + s] }
}
fn write_slice(&mut self, offset: U256, slice: &[u8]) {
let off = offset.low_u64() as usize;
// TODO [todr] Optimize?
for pos in off..off + slice.len() {
self[pos] = slice[pos - off];
}
}
fn write(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
value.to_big_endian(&mut self[off..off + 32]);
}
fn write_byte(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
let val = value.low_u64() as u64;
self[off] = val as u8;
}
fn resize(&mut self, new_size: usize) {
self.resize(new_size, 0);
}
fn expand(&mut self, size: usize) {
if size > self.len() {
Memory::resize(self, size)
}
}
}
#[test]
fn test_memory_read_and_write() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(0x80 + 32);
// when
mem.write(U256::from(0x80), U256::from(0xabcdef));
// then
assert_eq!(mem.read(U256::from(0x80)), U256::from(0xabcdef));
}
#[test]
fn test_memory_read_and_write_byte() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(32);
// when
mem.write_byte(U256::from(0x1d), U256::from(0xab));
mem.write_byte(U256::from(0x1e), U256::from(0xcd));
mem.write_byte(U256::from(0x1f), U256::from(0xef));
// then
assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef));
}
| {
self.len()
} | identifier_body |
memory.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/>.
use util::U256;
pub trait Memory {
/// Retrieve current size of the memory
fn size(&self) -> usize;
/// Resize (shrink or expand) the memory to specified size (fills 0)
fn resize(&mut self, new_size: usize);
/// Resize the memory only if its smaller
fn expand(&mut self, new_size: usize);
/// Write single byte to memory
fn write_byte(&mut self, offset: U256, value: U256);
/// Write a word to memory. Does not resize memory!
fn write(&mut self, offset: U256, value: U256);
/// Read a word from memory
fn read(&self, offset: U256) -> U256;
/// Write slice of bytes to memory. Does not resize memory!
fn write_slice(&mut self, offset: U256, &[u8]);
/// Retrieve part of the memory between offset and offset + size
fn read_slice(&self, offset: U256, size: U256) -> &[u8];
/// Retrieve writeable part of memory
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8];
fn dump(&self);
}
/// Checks whether offset and size is valid memory range
fn is_valid_range(off: usize, size: usize) -> bool {
// When size is zero we haven't actually expanded the memory
let overflow = off.overflowing_add(size).1;
size > 0 &&!overflow
}
impl Memory for Vec<u8> {
fn dump(&self) {
println!("MemoryDump:");
for i in self.iter() {
println!("{:02x} ", i);
}
println!("");
}
fn size(&self) -> usize {
self.len()
}
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
let off = init_off_u.low_u64() as usize;
let size = init_size_u.low_u64() as usize;
if!is_valid_range(off, size) { &self[0..0] } else { &self[off..off + size] }
}
fn read(&self, offset: U256) -> U256 {
let off = offset.low_u64() as usize;
U256::from(&self[off..off + 32])
}
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] {
let off = offset.low_u64() as usize;
let s = size.low_u64() as usize;
if!is_valid_range(off, s) { &mut self[0..0] } else |
}
fn write_slice(&mut self, offset: U256, slice: &[u8]) {
let off = offset.low_u64() as usize;
// TODO [todr] Optimize?
for pos in off..off + slice.len() {
self[pos] = slice[pos - off];
}
}
fn write(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
value.to_big_endian(&mut self[off..off + 32]);
}
fn write_byte(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
let val = value.low_u64() as u64;
self[off] = val as u8;
}
fn resize(&mut self, new_size: usize) {
self.resize(new_size, 0);
}
fn expand(&mut self, size: usize) {
if size > self.len() {
Memory::resize(self, size)
}
}
}
#[test]
fn test_memory_read_and_write() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(0x80 + 32);
// when
mem.write(U256::from(0x80), U256::from(0xabcdef));
// then
assert_eq!(mem.read(U256::from(0x80)), U256::from(0xabcdef));
}
#[test]
fn test_memory_read_and_write_byte() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(32);
// when
mem.write_byte(U256::from(0x1d), U256::from(0xab));
mem.write_byte(U256::from(0x1e), U256::from(0xcd));
mem.write_byte(U256::from(0x1f), U256::from(0xef));
// then
assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef));
}
| { &mut self[off..off + s] } | conditional_block |
memory.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/>.
use util::U256;
pub trait Memory {
/// Retrieve current size of the memory
fn size(&self) -> usize;
/// Resize (shrink or expand) the memory to specified size (fills 0)
fn resize(&mut self, new_size: usize);
/// Resize the memory only if its smaller
fn expand(&mut self, new_size: usize);
/// Write single byte to memory
fn write_byte(&mut self, offset: U256, value: U256);
/// Write a word to memory. Does not resize memory!
fn write(&mut self, offset: U256, value: U256);
/// Read a word from memory
fn read(&self, offset: U256) -> U256;
/// Write slice of bytes to memory. Does not resize memory!
fn write_slice(&mut self, offset: U256, &[u8]);
/// Retrieve part of the memory between offset and offset + size
fn read_slice(&self, offset: U256, size: U256) -> &[u8];
/// Retrieve writeable part of memory
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8];
fn dump(&self);
}
/// Checks whether offset and size is valid memory range
fn is_valid_range(off: usize, size: usize) -> bool {
// When size is zero we haven't actually expanded the memory
let overflow = off.overflowing_add(size).1;
size > 0 &&!overflow
}
impl Memory for Vec<u8> {
fn dump(&self) {
println!("MemoryDump:");
for i in self.iter() {
println!("{:02x} ", i);
}
println!("");
}
fn size(&self) -> usize {
self.len()
}
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
let off = init_off_u.low_u64() as usize;
let size = init_size_u.low_u64() as usize;
if!is_valid_range(off, size) { &self[0..0] } else { &self[off..off + size] }
}
fn read(&self, offset: U256) -> U256 {
let off = offset.low_u64() as usize;
U256::from(&self[off..off + 32])
}
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] {
let off = offset.low_u64() as usize;
let s = size.low_u64() as usize;
if!is_valid_range(off, s) { &mut self[0..0] } else { &mut self[off..off + s] }
}
fn write_slice(&mut self, offset: U256, slice: &[u8]) {
let off = offset.low_u64() as usize;
// TODO [todr] Optimize?
for pos in off..off + slice.len() {
self[pos] = slice[pos - off];
}
}
fn write(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
value.to_big_endian(&mut self[off..off + 32]);
}
fn write_byte(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
let val = value.low_u64() as u64;
self[off] = val as u8;
}
fn resize(&mut self, new_size: usize) {
self.resize(new_size, 0);
}
fn expand(&mut self, size: usize) {
if size > self.len() {
Memory::resize(self, size)
}
}
}
#[test]
fn test_memory_read_and_write() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(0x80 + 32);
// when
mem.write(U256::from(0x80), U256::from(0xabcdef));
// then
assert_eq!(mem.read(U256::from(0x80)), U256::from(0xabcdef));
}
#[test]
fn test_memory_read_and_write_byte() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(32);
// when
mem.write_byte(U256::from(0x1d), U256::from(0xab));
mem.write_byte(U256::from(0x1e), U256::from(0xcd));
mem.write_byte(U256::from(0x1f), U256::from(0xef));
// then
assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef));
} | random_line_split |
|
hibernate_state.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::metapb::Region;
use pd_client::{Feature, FeatureGate};
use serde_derive::{Deserialize, Serialize};
/// Because negotiation protocol can't be recognized by old version of binaries,
/// so enabling it directly can cause a lot of connection reset.
const NEGOTIATION_HIBERNATE: Feature = Feature::require(5, 0, 0);
/// Represents state of the group.
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum GroupState {
/// The group is working generally, leader keeps
/// replicating data to followers.
Ordered,
/// The group is out of order. Leadership may not be hold.
Chaos,
/// The group is about to be out of order. It leave some
/// safe space to avoid stepping chaos too often.
PreChaos,
/// The group is hibernated.
Idle,
}
#[derive(PartialEq, Debug)]
pub enum LeaderState {
Awaken,
Poll(Vec<u64>),
Hibernated,
}
#[derive(Debug)]
pub struct HibernateState {
group: GroupState,
leader: LeaderState,
}
impl HibernateState {
pub fn ordered() -> HibernateState {
HibernateState {
group: GroupState::Ordered,
leader: LeaderState::Awaken,
}
}
pub fn group_state(&self) -> GroupState {
self.group
}
pub fn reset(&mut self, group_state: GroupState) {
self.group = group_state;
if group_state!= GroupState::Idle {
self.leader = LeaderState::Awaken;
}
}
pub fn count_vote(&mut self, from: u64) |
pub fn should_bcast(&self, gate: &FeatureGate) -> bool {
gate.can_enable(NEGOTIATION_HIBERNATE)
}
pub fn maybe_hibernate(&mut self, my_id: u64, region: &Region) -> bool {
let peers = region.get_peers();
let v = match &mut self.leader {
LeaderState::Awaken => {
self.leader = LeaderState::Poll(Vec::with_capacity(peers.len()));
return false;
}
LeaderState::Poll(v) => v,
LeaderState::Hibernated => return true,
};
// 1 is for leader itself, which is not counted into votes.
if v.len() + 1 < peers.len() {
return false;
}
if peers
.iter()
.all(|p| p.get_id() == my_id || v.contains(&p.get_id()))
{
self.leader = LeaderState::Hibernated;
true
} else {
false
}
}
}
| {
if let LeaderState::Poll(v) = &mut self.leader {
if !v.contains(&from) {
v.push(from);
}
}
} | identifier_body |
hibernate_state.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::metapb::Region;
use pd_client::{Feature, FeatureGate};
use serde_derive::{Deserialize, Serialize};
/// Because negotiation protocol can't be recognized by old version of binaries,
/// so enabling it directly can cause a lot of connection reset.
const NEGOTIATION_HIBERNATE: Feature = Feature::require(5, 0, 0);
/// Represents state of the group.
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum GroupState {
/// The group is working generally, leader keeps
/// replicating data to followers.
Ordered,
/// The group is out of order. Leadership may not be hold.
Chaos,
/// The group is about to be out of order. It leave some
/// safe space to avoid stepping chaos too often.
PreChaos,
/// The group is hibernated.
Idle,
}
#[derive(PartialEq, Debug)]
pub enum LeaderState {
Awaken,
Poll(Vec<u64>),
Hibernated,
}
#[derive(Debug)]
pub struct HibernateState {
group: GroupState,
leader: LeaderState,
}
impl HibernateState {
pub fn ordered() -> HibernateState {
HibernateState {
group: GroupState::Ordered,
leader: LeaderState::Awaken,
}
}
pub fn group_state(&self) -> GroupState {
self.group
}
pub fn reset(&mut self, group_state: GroupState) {
self.group = group_state;
if group_state!= GroupState::Idle {
self.leader = LeaderState::Awaken;
}
}
pub fn count_vote(&mut self, from: u64) {
if let LeaderState::Poll(v) = &mut self.leader {
if!v.contains(&from) {
v.push(from);
}
}
}
pub fn should_bcast(&self, gate: &FeatureGate) -> bool {
gate.can_enable(NEGOTIATION_HIBERNATE)
}
pub fn maybe_hibernate(&mut self, my_id: u64, region: &Region) -> bool {
let peers = region.get_peers();
let v = match &mut self.leader {
LeaderState::Awaken => {
self.leader = LeaderState::Poll(Vec::with_capacity(peers.len()));
return false;
}
LeaderState::Poll(v) => v,
LeaderState::Hibernated => return true,
};
// 1 is for leader itself, which is not counted into votes.
if v.len() + 1 < peers.len() {
return false;
}
if peers
.iter()
.all(|p| p.get_id() == my_id || v.contains(&p.get_id()))
{
self.leader = LeaderState::Hibernated;
true | }
}
} | } else {
false | random_line_split |
hibernate_state.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::metapb::Region;
use pd_client::{Feature, FeatureGate};
use serde_derive::{Deserialize, Serialize};
/// Because negotiation protocol can't be recognized by old version of binaries,
/// so enabling it directly can cause a lot of connection reset.
const NEGOTIATION_HIBERNATE: Feature = Feature::require(5, 0, 0);
/// Represents state of the group.
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum GroupState {
/// The group is working generally, leader keeps
/// replicating data to followers.
Ordered,
/// The group is out of order. Leadership may not be hold.
Chaos,
/// The group is about to be out of order. It leave some
/// safe space to avoid stepping chaos too often.
PreChaos,
/// The group is hibernated.
Idle,
}
#[derive(PartialEq, Debug)]
pub enum LeaderState {
Awaken,
Poll(Vec<u64>),
Hibernated,
}
#[derive(Debug)]
pub struct | {
group: GroupState,
leader: LeaderState,
}
impl HibernateState {
pub fn ordered() -> HibernateState {
HibernateState {
group: GroupState::Ordered,
leader: LeaderState::Awaken,
}
}
pub fn group_state(&self) -> GroupState {
self.group
}
pub fn reset(&mut self, group_state: GroupState) {
self.group = group_state;
if group_state!= GroupState::Idle {
self.leader = LeaderState::Awaken;
}
}
pub fn count_vote(&mut self, from: u64) {
if let LeaderState::Poll(v) = &mut self.leader {
if!v.contains(&from) {
v.push(from);
}
}
}
pub fn should_bcast(&self, gate: &FeatureGate) -> bool {
gate.can_enable(NEGOTIATION_HIBERNATE)
}
pub fn maybe_hibernate(&mut self, my_id: u64, region: &Region) -> bool {
let peers = region.get_peers();
let v = match &mut self.leader {
LeaderState::Awaken => {
self.leader = LeaderState::Poll(Vec::with_capacity(peers.len()));
return false;
}
LeaderState::Poll(v) => v,
LeaderState::Hibernated => return true,
};
// 1 is for leader itself, which is not counted into votes.
if v.len() + 1 < peers.len() {
return false;
}
if peers
.iter()
.all(|p| p.get_id() == my_id || v.contains(&p.get_id()))
{
self.leader = LeaderState::Hibernated;
true
} else {
false
}
}
}
| HibernateState | identifier_name |
hibernate_state.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::metapb::Region;
use pd_client::{Feature, FeatureGate};
use serde_derive::{Deserialize, Serialize};
/// Because negotiation protocol can't be recognized by old version of binaries,
/// so enabling it directly can cause a lot of connection reset.
const NEGOTIATION_HIBERNATE: Feature = Feature::require(5, 0, 0);
/// Represents state of the group.
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum GroupState {
/// The group is working generally, leader keeps
/// replicating data to followers.
Ordered,
/// The group is out of order. Leadership may not be hold.
Chaos,
/// The group is about to be out of order. It leave some
/// safe space to avoid stepping chaos too often.
PreChaos,
/// The group is hibernated.
Idle,
}
#[derive(PartialEq, Debug)]
pub enum LeaderState {
Awaken,
Poll(Vec<u64>),
Hibernated,
}
#[derive(Debug)]
pub struct HibernateState {
group: GroupState,
leader: LeaderState,
}
impl HibernateState {
pub fn ordered() -> HibernateState {
HibernateState {
group: GroupState::Ordered,
leader: LeaderState::Awaken,
}
}
pub fn group_state(&self) -> GroupState {
self.group
}
pub fn reset(&mut self, group_state: GroupState) {
self.group = group_state;
if group_state!= GroupState::Idle {
self.leader = LeaderState::Awaken;
}
}
pub fn count_vote(&mut self, from: u64) {
if let LeaderState::Poll(v) = &mut self.leader {
if!v.contains(&from) {
v.push(from);
}
}
}
pub fn should_bcast(&self, gate: &FeatureGate) -> bool {
gate.can_enable(NEGOTIATION_HIBERNATE)
}
pub fn maybe_hibernate(&mut self, my_id: u64, region: &Region) -> bool {
let peers = region.get_peers();
let v = match &mut self.leader {
LeaderState::Awaken => {
self.leader = LeaderState::Poll(Vec::with_capacity(peers.len()));
return false;
}
LeaderState::Poll(v) => v,
LeaderState::Hibernated => return true,
};
// 1 is for leader itself, which is not counted into votes.
if v.len() + 1 < peers.len() {
return false;
}
if peers
.iter()
.all(|p| p.get_id() == my_id || v.contains(&p.get_id()))
| else {
false
}
}
}
| {
self.leader = LeaderState::Hibernated;
true
} | conditional_block |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread::Thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in all.iter() {
for bb in all.iter() {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
enum Color {
Red,
Yellow,
Blue,
}
impl Copy for Color {}
impl fmt::Show for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
struct CreatureInfo {
name: uint,
color: Color
}
impl Copy for CreatureInfo {}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in set.iter() {
out.push(' ');
out.push_str(format!("{:?}", col).as_slice());
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Show for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn | (
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let mut to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
Thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in range(0, nn) {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args().as_slice()
.get(1)
.and_then(|arg| arg.parse())
.unwrap_or(600u)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
}
| creature | identifier_name |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread::Thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in all.iter() {
for bb in all.iter() {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
enum Color {
Red,
Yellow,
Blue,
}
impl Copy for Color {}
impl fmt::Show for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
struct CreatureInfo {
name: uint,
color: Color
}
impl Copy for CreatureInfo {}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in set.iter() {
out.push(' ');
out.push_str(format!("{:?}", col).as_slice());
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => |
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Show for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let mut to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
Thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in range(0, nn) {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args().as_slice()
.get(1)
.and_then(|arg| arg.parse())
.unwrap_or(600u)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
}
| {" six"} | conditional_block |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread::Thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in all.iter() {
for bb in all.iter() {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
enum Color {
Red,
Yellow,
Blue,
}
impl Copy for Color {}
impl fmt::Show for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
struct CreatureInfo {
name: uint,
color: Color
}
impl Copy for CreatureInfo {}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in set.iter() {
out.push(' ');
out.push_str(format!("{:?}", col).as_slice());
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Show for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let mut to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
Thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in range(0, nn) {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args().as_slice()
.get(1)
.and_then(|arg| arg.parse())
.unwrap_or(600u)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
} | random_line_split |
|
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread::Thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in all.iter() {
for bb in all.iter() {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
enum Color {
Red,
Yellow,
Blue,
}
impl Copy for Color {}
impl fmt::Show for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
struct CreatureInfo {
name: uint,
color: Color
}
impl Copy for CreatureInfo {}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in set.iter() {
out.push(' ');
out.push_str(format!("{:?}", col).as_slice());
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Show for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let mut to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
Thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in range(0, nn) {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() | {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args().as_slice()
.get(1)
.and_then(|arg| arg.parse())
.unwrap_or(600u)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
} | identifier_body |
|
ws_impl.rs | use flate2::read::ZlibDecoder;
use serde_json;
use websocket::message::OwnedMessage;
use websocket::sync::stream::{TcpStream, TlsStream};
use websocket::sync::Client as WsClient;
use gateway::GatewayError;
use internal::prelude::*;
pub trait ReceiverExt {
fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where F: Fn(Value) -> Result<T>;
}
pub trait SenderExt {
fn send_json(&mut self, value: &Value) -> Result<()>;
}
impl ReceiverExt for WsClient<TlsStream<TcpStream>> {
fn recv_json<F, T>(&mut self, decode: F) -> Result<T>
where F: Fn(Value) -> Result<T> {
let message = self.recv_message()?;
let res = match message {
OwnedMessage::Binary(bytes) => {
let value = serde_json::from_reader(ZlibDecoder::new(&bytes[..]))?;
Some(decode(value).map_err(|why| {
let s = String::from_utf8_lossy(&bytes);
warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", s); | OwnedMessage::Text(payload) => {
let value = serde_json::from_str(&payload)?;
Some(decode(value).map_err(|why| {
warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", payload);
why
}))
},
OwnedMessage::Ping(x) => {
self.send_message(&OwnedMessage::Pong(x)).map_err(
Error::from,
)?;
None
},
OwnedMessage::Pong(_) => None,
};
// As to ignore the `None`s returned from `Ping` and `Pong`.
// Since they're essentially useless to us anyway.
match res {
Some(data) => data,
None => self.recv_json(decode),
}
}
}
impl SenderExt for WsClient<TlsStream<TcpStream>> {
fn send_json(&mut self, value: &Value) -> Result<()> {
serde_json::to_string(value)
.map(OwnedMessage::Text)
.map_err(Error::from)
.and_then(|m| self.send_message(&m).map_err(Error::from))
}
} |
why
}))
},
OwnedMessage::Close(data) => Some(Err(Error::Gateway(GatewayError::Closed(data)))), | random_line_split |
ws_impl.rs | use flate2::read::ZlibDecoder;
use serde_json;
use websocket::message::OwnedMessage;
use websocket::sync::stream::{TcpStream, TlsStream};
use websocket::sync::Client as WsClient;
use gateway::GatewayError;
use internal::prelude::*;
pub trait ReceiverExt {
fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where F: Fn(Value) -> Result<T>;
}
pub trait SenderExt {
fn send_json(&mut self, value: &Value) -> Result<()>;
}
impl ReceiverExt for WsClient<TlsStream<TcpStream>> {
fn recv_json<F, T>(&mut self, decode: F) -> Result<T>
where F: Fn(Value) -> Result<T> | warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", payload);
why
}))
},
OwnedMessage::Ping(x) => {
self.send_message(&OwnedMessage::Pong(x)).map_err(
Error::from,
)?;
None
},
OwnedMessage::Pong(_) => None,
};
// As to ignore the `None`s returned from `Ping` and `Pong`.
// Since they're essentially useless to us anyway.
match res {
Some(data) => data,
None => self.recv_json(decode),
}
}
}
impl SenderExt for WsClient<TlsS
tream<TcpStream>> {
fn send_json(&mut self, value: &Value) -> Result<()> {
serde_json::to_string(value)
.map(OwnedMessage::Text)
.map_err(Error::from)
.and_then(|m| self.send_message(&m).map_err(Error::from))
}
}
| {
let message = self.recv_message()?;
let res = match message {
OwnedMessage::Binary(bytes) => {
let value = serde_json::from_reader(ZlibDecoder::new(&bytes[..]))?;
Some(decode(value).map_err(|why| {
let s = String::from_utf8_lossy(&bytes);
warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", s);
why
}))
},
OwnedMessage::Close(data) => Some(Err(Error::Gateway(GatewayError::Closed(data)))),
OwnedMessage::Text(payload) => {
let value = serde_json::from_str(&payload)?;
Some(decode(value).map_err(|why| { | identifier_body |
ws_impl.rs | use flate2::read::ZlibDecoder;
use serde_json;
use websocket::message::OwnedMessage;
use websocket::sync::stream::{TcpStream, TlsStream};
use websocket::sync::Client as WsClient;
use gateway::GatewayError;
use internal::prelude::*;
pub trait ReceiverExt {
fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where F: Fn(Value) -> Result<T>;
}
pub trait SenderExt {
fn send_json(&mut self, value: &Value) -> Result<()>;
}
impl ReceiverExt for WsClient<TlsStream<TcpStream>> {
fn recv_json<F, T>(&mut self, decode: F) -> Result<T>
where F: Fn(Value) -> Result<T> {
let message = self.recv_message()?;
let res = match message {
OwnedMessage::Binary(bytes) => {
let value = serde_json::from_reader(ZlibDecoder::new(&bytes[..]))?;
Some(decode(value).map_err(|why| {
let s = String::from_utf8_lossy(&bytes);
warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", s);
why
}))
},
OwnedMessage::Close(data) => Some(Err(Error::Gateway(GatewayError::Closed(data)))),
OwnedMessage::Text(payload) => {
let value = serde_json::from_str(&payload)?;
Some(decode(value).map_err(|why| {
warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", payload);
why
}))
},
OwnedMessage::Ping(x) => {
self.send_message(&OwnedMessage::Pong(x)).map_err(
Error::from,
)?;
None
},
OwnedMessage::Pong(_) => None,
};
// As to ignore the `None`s returned from `Ping` and `Pong`.
// Since they're essentially useless to us anyway.
match res {
Some(data) => data,
None => self.recv_json(decode),
}
}
}
impl SenderExt for WsClient<TlsStream<TcpStream>> {
fn send_json(&mut self, value: &Value) | <()> {
serde_json::to_string(value)
.map(OwnedMessage::Text)
.map_err(Error::from)
.and_then(|m| self.send_message(&m).map_err(Error::from))
}
}
| -> Result | identifier_name |
service.rs | use crate::protocol;
#[cfg(windows)]
use core::os::process::windows_child::{ChildStderr,
ChildStdout,
ExitStatus};
use core::util::BufReadLossy;
use habitat_common::output::{self,
StructuredOutput};
#[cfg(unix)]
use std::process::{ChildStderr,
ChildStdout,
ExitStatus};
use std::{fmt,
io::{self,
BufReader,
Read},
thread};
pub use crate::sys::service::*;
pub struct Service {
args: protocol::Spawn,
process: Process,
}
impl Service {
pub fn new(spawn: protocol::Spawn,
process: Process,
stdout: Option<ChildStdout>,
stderr: Option<ChildStderr>)
-> Self {
if let Some(stdout) = stdout {
let id = spawn.id.to_string();
thread::Builder::new().name(format!("{}-out", spawn.id))
.spawn(move || pipe_stdout(stdout, &id))
.ok();
}
if let Some(stderr) = stderr {
let id = spawn.id.to_string();
thread::Builder::new().name(format!("{}-err", spawn.id))
.spawn(move || pipe_stderr(stderr, &id))
.ok();
}
Service { args: spawn,
process }
}
pub fn args(&self) -> &protocol::Spawn { &self.args }
pub fn | (&self) -> u32 { self.process.id() }
/// Attempt to gracefully terminate a proccess and then forcefully kill it after
/// 8 seconds if it has not terminated.
pub fn kill(&mut self) -> protocol::ShutdownMethod { self.process.kill() }
pub fn name(&self) -> &str { &self.args.id }
pub fn take_args(self) -> protocol::Spawn { self.args }
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { self.process.try_wait() }
pub fn wait(&mut self) -> io::Result<ExitStatus> { self.process.wait() }
}
impl fmt::Debug for Service {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Service {{ pid: {:?} }}", self.process.id())
}
}
/// Consume output from a child process until EOF, then finish
fn pipe_stdout<T>(out: T, id: &str)
where T: Read
{
for line in BufReader::new(out).lines_lossy() {
match line {
Ok(line) => {
let so = StructuredOutput::succinct(id, "O", output::get_format(), &line);
if let Err(e) = so.println() {
println!("printing output: '{}' to stdout resulted in error: {}",
&line, e);
}
}
Err(e) => {
println!("reading output from to stdout resulted in error: {}", e);
break;
}
}
}
}
/// Consume standard error from a child process until EOF, then finish
fn pipe_stderr<T>(err: T, id: &str)
where T: Read
{
for line in BufReader::new(err).lines_lossy() {
match line {
Ok(line) => {
let so = StructuredOutput::succinct(id, "E", output::get_format(), &line);
if let Err(e) = so.eprintln() {
println!("printing output: '{}' to stderr resulted in error: {}",
&line, e);
}
}
Err(e) => {
println!("reading output from to stderr resulted in error: {}", e);
break;
}
}
}
}
| id | identifier_name |
service.rs | use crate::protocol;
#[cfg(windows)]
use core::os::process::windows_child::{ChildStderr,
ChildStdout,
ExitStatus};
use core::util::BufReadLossy;
use habitat_common::output::{self,
StructuredOutput};
#[cfg(unix)]
use std::process::{ChildStderr,
ChildStdout,
ExitStatus};
use std::{fmt,
io::{self,
BufReader,
Read},
thread};
pub use crate::sys::service::*;
pub struct Service {
args: protocol::Spawn,
process: Process,
}
impl Service {
pub fn new(spawn: protocol::Spawn,
process: Process,
stdout: Option<ChildStdout>,
stderr: Option<ChildStderr>)
-> Self {
if let Some(stdout) = stdout {
let id = spawn.id.to_string();
thread::Builder::new().name(format!("{}-out", spawn.id))
.spawn(move || pipe_stdout(stdout, &id))
.ok();
}
if let Some(stderr) = stderr {
let id = spawn.id.to_string();
thread::Builder::new().name(format!("{}-err", spawn.id))
.spawn(move || pipe_stderr(stderr, &id))
.ok();
}
Service { args: spawn,
process }
}
pub fn args(&self) -> &protocol::Spawn { &self.args }
pub fn id(&self) -> u32 { self.process.id() }
/// Attempt to gracefully terminate a proccess and then forcefully kill it after
/// 8 seconds if it has not terminated.
pub fn kill(&mut self) -> protocol::ShutdownMethod { self.process.kill() }
pub fn name(&self) -> &str { &self.args.id }
pub fn take_args(self) -> protocol::Spawn { self.args }
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { self.process.try_wait() }
pub fn wait(&mut self) -> io::Result<ExitStatus> { self.process.wait() }
}
impl fmt::Debug for Service {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Service {{ pid: {:?} }}", self.process.id())
}
}
/// Consume output from a child process until EOF, then finish
fn pipe_stdout<T>(out: T, id: &str)
where T: Read
|
/// Consume standard error from a child process until EOF, then finish
fn pipe_stderr<T>(err: T, id: &str)
where T: Read
{
for line in BufReader::new(err).lines_lossy() {
match line {
Ok(line) => {
let so = StructuredOutput::succinct(id, "E", output::get_format(), &line);
if let Err(e) = so.eprintln() {
println!("printing output: '{}' to stderr resulted in error: {}",
&line, e);
}
}
Err(e) => {
println!("reading output from to stderr resulted in error: {}", e);
break;
}
}
}
}
| {
for line in BufReader::new(out).lines_lossy() {
match line {
Ok(line) => {
let so = StructuredOutput::succinct(id, "O", output::get_format(), &line);
if let Err(e) = so.println() {
println!("printing output: '{}' to stdout resulted in error: {}",
&line, e);
}
}
Err(e) => {
println!("reading output from to stdout resulted in error: {}", e);
break;
}
}
}
} | identifier_body |
service.rs | use crate::protocol;
#[cfg(windows)]
use core::os::process::windows_child::{ChildStderr,
ChildStdout,
ExitStatus};
use core::util::BufReadLossy;
use habitat_common::output::{self,
StructuredOutput};
#[cfg(unix)]
use std::process::{ChildStderr,
ChildStdout,
ExitStatus};
use std::{fmt,
io::{self,
BufReader,
Read},
thread};
pub use crate::sys::service::*;
pub struct Service {
args: protocol::Spawn,
process: Process,
} | impl Service {
pub fn new(spawn: protocol::Spawn,
process: Process,
stdout: Option<ChildStdout>,
stderr: Option<ChildStderr>)
-> Self {
if let Some(stdout) = stdout {
let id = spawn.id.to_string();
thread::Builder::new().name(format!("{}-out", spawn.id))
.spawn(move || pipe_stdout(stdout, &id))
.ok();
}
if let Some(stderr) = stderr {
let id = spawn.id.to_string();
thread::Builder::new().name(format!("{}-err", spawn.id))
.spawn(move || pipe_stderr(stderr, &id))
.ok();
}
Service { args: spawn,
process }
}
pub fn args(&self) -> &protocol::Spawn { &self.args }
pub fn id(&self) -> u32 { self.process.id() }
/// Attempt to gracefully terminate a proccess and then forcefully kill it after
/// 8 seconds if it has not terminated.
pub fn kill(&mut self) -> protocol::ShutdownMethod { self.process.kill() }
pub fn name(&self) -> &str { &self.args.id }
pub fn take_args(self) -> protocol::Spawn { self.args }
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { self.process.try_wait() }
pub fn wait(&mut self) -> io::Result<ExitStatus> { self.process.wait() }
}
impl fmt::Debug for Service {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Service {{ pid: {:?} }}", self.process.id())
}
}
/// Consume output from a child process until EOF, then finish
fn pipe_stdout<T>(out: T, id: &str)
where T: Read
{
for line in BufReader::new(out).lines_lossy() {
match line {
Ok(line) => {
let so = StructuredOutput::succinct(id, "O", output::get_format(), &line);
if let Err(e) = so.println() {
println!("printing output: '{}' to stdout resulted in error: {}",
&line, e);
}
}
Err(e) => {
println!("reading output from to stdout resulted in error: {}", e);
break;
}
}
}
}
/// Consume standard error from a child process until EOF, then finish
fn pipe_stderr<T>(err: T, id: &str)
where T: Read
{
for line in BufReader::new(err).lines_lossy() {
match line {
Ok(line) => {
let so = StructuredOutput::succinct(id, "E", output::get_format(), &line);
if let Err(e) = so.eprintln() {
println!("printing output: '{}' to stderr resulted in error: {}",
&line, e);
}
}
Err(e) => {
println!("reading output from to stderr resulted in error: {}", e);
break;
}
}
}
} | random_line_split |
|
bind-by-move-neither-can-live-while-the-other-survives-4.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.
struct | { x: (), }
impl Drop for X {
fn drop(&mut self) {
println!("destructor runs");
}
}
fn main() {
let x = Some((X { x: () }, X { x: () }));
match x {
Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
None => fail!()
}
}
| X | identifier_name |
bind-by-move-neither-can-live-while-the-other-survives-4.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.
struct X { x: (), }
impl Drop for X {
fn drop(&mut self) {
println!("destructor runs");
}
}
fn main() | {
let x = Some((X { x: () }, X { x: () }));
match x {
Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
None => fail!()
}
} | identifier_body |
|
bind-by-move-neither-can-live-while-the-other-survives-4.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 | impl Drop for X {
fn drop(&mut self) {
println!("destructor runs");
}
}
fn main() {
let x = Some((X { x: () }, X { x: () }));
match x {
Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
None => fail!()
}
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
struct X { x: (), }
| random_line_split |
p011.rs | //! [Problem 11](https://projecteuler.net/problem=11) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(iter_arith)]
#[macro_use(problem)] extern crate common;
const INPUT: &'static str = "
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
";
fn compute(prod_len: usize) -> u32 {
let grid: Vec<Vec<u32>> = INPUT
.trim()
.lines()
.map(|line| {
line.split_whitespace().filter_map(|s| s.parse().ok()).collect()
})
.collect(); | let h = grid.len();
let mut lines: Vec<Vec<_>> = vec![];
// rows
lines.extend((0.. h).map(|y| (0.. w).map(|x| (x, y)).collect()));
// cols
lines.extend((0.. w).map(|x| (0.. h).map(|y| (x, y)).collect()));
// top 2 right diagonal
lines.extend((0.. w).map(|i| {
let (x0, y0) = (i, 0);
(0.. w - x0).map(|j| (x0 + j, y0 + j)).collect()
}));
// left 2 bottom diagonal
lines.extend((0.. h - 1).map(|i| {
let (x0, y0) = (0, i + 1);
(0.. h - y0).map(|j| (x0 + j, y0 + j)).collect()
}));
// top 2 left diagonal
lines.extend((0.. w).map(|i| {
let (x0, y0) = (i, 0);
(0.. x0 + 1).map(|j| (x0 - j, y0 + j)).collect()
}));
// right 2 bottom diagonal
lines.extend((0.. h - 1).map(|i| {
let (x0, y0) = (w - 1, i + 1);
(0.. h - y0).map(|j| (x0 - j, y0 + j)).collect()
}));
lines.iter()
.map(|cells| {
cells.windows(prod_len)
.map(|ns| ns.iter().map(|&(x, y)| grid[y][x]).product())
.max()
.unwrap_or(0)
}).max()
.unwrap()
}
fn solve() -> String { compute(4).to_string() }
problem!("70600674", solve); |
let w = grid[0].len(); | random_line_split |
p011.rs | //! [Problem 11](https://projecteuler.net/problem=11) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(iter_arith)]
#[macro_use(problem)] extern crate common;
const INPUT: &'static str = "
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
";
fn compute(prod_len: usize) -> u32 {
let grid: Vec<Vec<u32>> = INPUT
.trim()
.lines()
.map(|line| {
line.split_whitespace().filter_map(|s| s.parse().ok()).collect()
})
.collect();
let w = grid[0].len();
let h = grid.len();
let mut lines: Vec<Vec<_>> = vec![];
// rows
lines.extend((0.. h).map(|y| (0.. w).map(|x| (x, y)).collect()));
// cols
lines.extend((0.. w).map(|x| (0.. h).map(|y| (x, y)).collect()));
// top 2 right diagonal
lines.extend((0.. w).map(|i| {
let (x0, y0) = (i, 0);
(0.. w - x0).map(|j| (x0 + j, y0 + j)).collect()
}));
// left 2 bottom diagonal
lines.extend((0.. h - 1).map(|i| {
let (x0, y0) = (0, i + 1);
(0.. h - y0).map(|j| (x0 + j, y0 + j)).collect()
}));
// top 2 left diagonal
lines.extend((0.. w).map(|i| {
let (x0, y0) = (i, 0);
(0.. x0 + 1).map(|j| (x0 - j, y0 + j)).collect()
}));
// right 2 bottom diagonal
lines.extend((0.. h - 1).map(|i| {
let (x0, y0) = (w - 1, i + 1);
(0.. h - y0).map(|j| (x0 - j, y0 + j)).collect()
}));
lines.iter()
.map(|cells| {
cells.windows(prod_len)
.map(|ns| ns.iter().map(|&(x, y)| grid[y][x]).product())
.max()
.unwrap_or(0)
}).max()
.unwrap()
}
fn | () -> String { compute(4).to_string() }
problem!("70600674", solve);
| solve | identifier_name |
p011.rs | //! [Problem 11](https://projecteuler.net/problem=11) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(iter_arith)]
#[macro_use(problem)] extern crate common;
const INPUT: &'static str = "
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
";
fn compute(prod_len: usize) -> u32 | (0.. w - x0).map(|j| (x0 + j, y0 + j)).collect()
}));
// left 2 bottom diagonal
lines.extend((0.. h - 1).map(|i| {
let (x0, y0) = (0, i + 1);
(0.. h - y0).map(|j| (x0 + j, y0 + j)).collect()
}));
// top 2 left diagonal
lines.extend((0.. w).map(|i| {
let (x0, y0) = (i, 0);
(0.. x0 + 1).map(|j| (x0 - j, y0 + j)).collect()
}));
// right 2 bottom diagonal
lines.extend((0.. h - 1).map(|i| {
let (x0, y0) = (w - 1, i + 1);
(0.. h - y0).map(|j| (x0 - j, y0 + j)).collect()
}));
lines.iter()
.map(|cells| {
cells.windows(prod_len)
.map(|ns| ns.iter().map(|&(x, y)| grid[y][x]).product())
.max()
.unwrap_or(0)
}).max()
.unwrap()
}
fn solve() -> String { compute(4).to_string() }
problem!("70600674", solve);
| {
let grid: Vec<Vec<u32>> = INPUT
.trim()
.lines()
.map(|line| {
line.split_whitespace().filter_map(|s| s.parse().ok()).collect()
})
.collect();
let w = grid[0].len();
let h = grid.len();
let mut lines: Vec<Vec<_>> = vec![];
// rows
lines.extend((0 .. h).map(|y| (0 .. w).map(|x| (x, y)).collect()));
// cols
lines.extend((0 .. w).map(|x| (0 .. h).map(|y| (x, y)).collect()));
// top 2 right diagonal
lines.extend((0 .. w).map(|i| {
let (x0, y0) = (i, 0); | identifier_body |
lib.rs | // Copyright 2017 Kam Y. Tse
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
#![deny(warnings)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate uuid;
extern crate serde;
extern crate chrono;
extern crate reqwest;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate serde_derive;
mod account;
mod pomo;
mod todo;
mod client;
pub use self::account::Account; | pub use self::client::Client;
/// The Errors that may occur when communicating with Pomotodo server.
pub mod errors {
error_chain! {
types {
Error, ErrorKind, ResultExt;
}
foreign_links {
ReqError(::reqwest::Error);
}
}
} | pub use self::pomo::{Pomo, PomoBuilder, PomoParameter};
pub use self::todo::{Todo, SubTodo, TodoBuilder, SubTodoBuilder, TodoParameter}; | random_line_split |
main.rs | // Copyright 2016 Gomez Guillaume
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs;
use std::path::Path;
use std::str::FromStr;
struct CleanOptions {
recursive: bool,
verbose: bool,
confirmation: bool,
level: u32
}
fn ask_confirmation(file: &Path) -> bool {
if let Some(filename) = file.to_str() {
loop {
print!("clean: remove \x1b[37;1m'{}'\x1b[0m (y/n)? ", filename);
let mut s = String::new();
match std::io::stdin().read_line(&mut s) {
Ok(_) => {
let tmp_s = s.replace("\r\n", "").replace("\n", "");
if tmp_s == "y" || tmp_s == "yes" {
return true;
} else if tmp_s == "n" || tmp_s == "no" {
return false;
}
}
Err(_) => {}
}
}
} else {
println!("Unknown error on '{:?}'...", file);
false
}
}
fn start_clean(options: &CleanOptions, entry: &Path, level: u32) {
let m = match ::std::fs::metadata(&entry) {
Ok(e) => e,
Err(e) => {
println!("An error occured on '{:?}': {}", entry, e);
return
}
};
let entry_name = match entry.to_str() {
Some(n) => n,
None => {
println!("Invalid entry '{:?}'", entry);
return
}
};
if m.is_file() || m.is_dir() {
if m.is_dir() {
if (options.recursive || entry_name == ".") &&
(options.level == 0 || level <= options.level) {
match fs::read_dir(entry) {
Ok(res) => {
if options.verbose {
println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name);
}
for tmp in res {
match tmp {
Ok(current) => {
start_clean(options, ¤t.path(), level + 1);
},
Err(e) => println!("Error: {:?}", e)
};
}
if options.verbose |
}
Err(e) => {
println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e);
}
}
}
} else {
match entry.file_name() {
Some(s) => {
match s.to_str() {
Some(ss) => if ss.ends_with("~") {
if!options.confirmation || ask_confirmation(&Path::new(s)) {
match fs::remove_file(entry) {
Ok(_) => {
if options.verbose {
println!("\x1b[32;1m{} deleted\x1b[0m", entry_name);
}
}
Err(e) => {
println!("\x1b[31;1mProblem with this file: {} -> {}\x1b[0m", entry_name, e);
}
}
}
},
_ => {}
}
}
None => {
println!("\x1b[31;1mProblem with this file: {}\x1b[0m", entry_name);
}
}
}
} else {
println!("\x1b[31;1mProblem with this entry: {}\x1b[0m", entry_name);
}
}
fn print_help() {
println!("./clean [options] [files | dirs]");
println!(" -r : recursive mode");
println!(" -v : verbose mode");
println!(" -i : prompt before every removal");
println!(" -l=[number] : Add a level for recursive mode");
println!("--help : print this help");
}
fn main() {
let mut args = Vec::new();
for argument in std::env::args() {
args.push(argument);
}
let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0};
let mut files = Vec::new();
args.remove(0);
for tmp in args.iter() {
if tmp.clone().into_bytes()[0] == '-' as u8 {
let mut tmp_arg = tmp.to_owned();
tmp_arg.remove(0);
if tmp_arg.len() > 0 {
for character in tmp_arg.into_bytes().iter() {
match *character as char {
'-' => {
if &*tmp == "--help" {
print_help();
return;
}
}
'r' => {
options.recursive = true;
}
'v' => {
options.verbose = true;
}
'i' => {
options.confirmation = true;
}
'l' => {
if tmp.len() < 4 || &tmp[0..3]!= "-l=" {
println!("The \"-l\" option has to be used like this:");
println!("clean -r -l=2");
return;
}
options.level = match u32::from_str(&tmp[3..]) {
Ok(u) => u,
Err(_) => {
println!("Please enter a valid number!");
return;
}
};
println!("Level is set to {}", options.level);
break;
}
_ => {
println!("Unknown option: '{}', to have the options list, please launch with '-h' option", *character as char);
return;
}
}
}
}/* else {
files.push(Path::new(tmp));
}*/
} else {
files.push(Path::new(tmp));
}
}
if files.len() == 0 {
files.push(Path::new("."));
}
if options.verbose {
println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m");
}
for tmp in files.iter() {
start_clean(&options, tmp, 0);
}
if options.verbose {
println!("\x1b[33;1mEnd of execution\x1b[0m");
}
} | {
println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name);
} | conditional_block |
main.rs | // Copyright 2016 Gomez Guillaume
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs;
use std::path::Path;
use std::str::FromStr;
struct CleanOptions {
recursive: bool,
verbose: bool,
confirmation: bool,
level: u32
}
fn ask_confirmation(file: &Path) -> bool {
if let Some(filename) = file.to_str() {
loop {
print!("clean: remove \x1b[37;1m'{}'\x1b[0m (y/n)? ", filename);
let mut s = String::new();
match std::io::stdin().read_line(&mut s) {
Ok(_) => {
let tmp_s = s.replace("\r\n", "").replace("\n", "");
if tmp_s == "y" || tmp_s == "yes" {
return true;
} else if tmp_s == "n" || tmp_s == "no" {
return false;
}
}
Err(_) => {}
}
}
} else {
println!("Unknown error on '{:?}'...", file);
false
}
}
fn start_clean(options: &CleanOptions, entry: &Path, level: u32) {
let m = match ::std::fs::metadata(&entry) {
Ok(e) => e,
Err(e) => {
println!("An error occured on '{:?}': {}", entry, e);
return
}
};
let entry_name = match entry.to_str() {
Some(n) => n,
None => {
println!("Invalid entry '{:?}'", entry);
return
}
};
if m.is_file() || m.is_dir() {
if m.is_dir() {
if (options.recursive || entry_name == ".") &&
(options.level == 0 || level <= options.level) {
match fs::read_dir(entry) {
Ok(res) => {
if options.verbose {
println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name);
}
for tmp in res {
match tmp {
Ok(current) => {
start_clean(options, ¤t.path(), level + 1);
},
Err(e) => println!("Error: {:?}", e)
};
}
if options.verbose {
println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name);
}
}
Err(e) => {
println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e);
}
}
}
} else {
match entry.file_name() {
Some(s) => {
match s.to_str() {
Some(ss) => if ss.ends_with("~") {
if!options.confirmation || ask_confirmation(&Path::new(s)) {
match fs::remove_file(entry) {
Ok(_) => {
if options.verbose {
println!("\x1b[32;1m{} deleted\x1b[0m", entry_name);
}
}
Err(e) => {
println!("\x1b[31;1mProblem with this file: {} -> {}\x1b[0m", entry_name, e);
}
}
}
},
_ => {}
}
}
None => {
println!("\x1b[31;1mProblem with this file: {}\x1b[0m", entry_name);
}
}
}
} else {
println!("\x1b[31;1mProblem with this entry: {}\x1b[0m", entry_name);
}
}
fn print_help() {
println!("./clean [options] [files | dirs]");
println!(" -r : recursive mode");
println!(" -v : verbose mode");
println!(" -i : prompt before every removal");
println!(" -l=[number] : Add a level for recursive mode");
println!("--help : print this help");
}
fn main() {
let mut args = Vec::new();
for argument in std::env::args() {
args.push(argument);
}
let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0};
let mut files = Vec::new();
args.remove(0);
for tmp in args.iter() {
if tmp.clone().into_bytes()[0] == '-' as u8 {
let mut tmp_arg = tmp.to_owned();
tmp_arg.remove(0);
if tmp_arg.len() > 0 {
for character in tmp_arg.into_bytes().iter() {
match *character as char {
'-' => {
if &*tmp == "--help" {
print_help();
return;
}
}
'r' => {
options.recursive = true;
}
'v' => {
options.verbose = true;
}
'i' => {
options.confirmation = true;
}
'l' => {
if tmp.len() < 4 || &tmp[0..3]!= "-l=" {
println!("The \"-l\" option has to be used like this:");
println!("clean -r -l=2");
return;
}
options.level = match u32::from_str(&tmp[3..]) {
Ok(u) => u,
Err(_) => {
println!("Please enter a valid number!");
return;
}
};
println!("Level is set to {}", options.level);
break;
}
_ => {
println!("Unknown option: '{}', to have the options list, please launch with '-h' option", *character as char);
return;
}
}
}
}/* else {
files.push(Path::new(tmp));
}*/
} else {
files.push(Path::new(tmp)); | if files.len() == 0 {
files.push(Path::new("."));
}
if options.verbose {
println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m");
}
for tmp in files.iter() {
start_clean(&options, tmp, 0);
}
if options.verbose {
println!("\x1b[33;1mEnd of execution\x1b[0m");
}
} | }
} | random_line_split |
main.rs | // Copyright 2016 Gomez Guillaume
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs;
use std::path::Path;
use std::str::FromStr;
struct CleanOptions {
recursive: bool,
verbose: bool,
confirmation: bool,
level: u32
}
fn ask_confirmation(file: &Path) -> bool {
if let Some(filename) = file.to_str() {
loop {
print!("clean: remove \x1b[37;1m'{}'\x1b[0m (y/n)? ", filename);
let mut s = String::new();
match std::io::stdin().read_line(&mut s) {
Ok(_) => {
let tmp_s = s.replace("\r\n", "").replace("\n", "");
if tmp_s == "y" || tmp_s == "yes" {
return true;
} else if tmp_s == "n" || tmp_s == "no" {
return false;
}
}
Err(_) => {}
}
}
} else {
println!("Unknown error on '{:?}'...", file);
false
}
}
fn start_clean(options: &CleanOptions, entry: &Path, level: u32) | match fs::read_dir(entry) {
Ok(res) => {
if options.verbose {
println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name);
}
for tmp in res {
match tmp {
Ok(current) => {
start_clean(options, ¤t.path(), level + 1);
},
Err(e) => println!("Error: {:?}", e)
};
}
if options.verbose {
println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name);
}
}
Err(e) => {
println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e);
}
}
}
} else {
match entry.file_name() {
Some(s) => {
match s.to_str() {
Some(ss) => if ss.ends_with("~") {
if!options.confirmation || ask_confirmation(&Path::new(s)) {
match fs::remove_file(entry) {
Ok(_) => {
if options.verbose {
println!("\x1b[32;1m{} deleted\x1b[0m", entry_name);
}
}
Err(e) => {
println!("\x1b[31;1mProblem with this file: {} -> {}\x1b[0m", entry_name, e);
}
}
}
},
_ => {}
}
}
None => {
println!("\x1b[31;1mProblem with this file: {}\x1b[0m", entry_name);
}
}
}
} else {
println!("\x1b[31;1mProblem with this entry: {}\x1b[0m", entry_name);
}
}
fn print_help() {
println!("./clean [options] [files | dirs]");
println!(" -r : recursive mode");
println!(" -v : verbose mode");
println!(" -i : prompt before every removal");
println!(" -l=[number] : Add a level for recursive mode");
println!("--help : print this help");
}
fn main() {
let mut args = Vec::new();
for argument in std::env::args() {
args.push(argument);
}
let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0};
let mut files = Vec::new();
args.remove(0);
for tmp in args.iter() {
if tmp.clone().into_bytes()[0] == '-' as u8 {
let mut tmp_arg = tmp.to_owned();
tmp_arg.remove(0);
if tmp_arg.len() > 0 {
for character in tmp_arg.into_bytes().iter() {
match *character as char {
'-' => {
if &*tmp == "--help" {
print_help();
return;
}
}
'r' => {
options.recursive = true;
}
'v' => {
options.verbose = true;
}
'i' => {
options.confirmation = true;
}
'l' => {
if tmp.len() < 4 || &tmp[0..3]!= "-l=" {
println!("The \"-l\" option has to be used like this:");
println!("clean -r -l=2");
return;
}
options.level = match u32::from_str(&tmp[3..]) {
Ok(u) => u,
Err(_) => {
println!("Please enter a valid number!");
return;
}
};
println!("Level is set to {}", options.level);
break;
}
_ => {
println!("Unknown option: '{}', to have the options list, please launch with '-h' option", *character as char);
return;
}
}
}
}/* else {
files.push(Path::new(tmp));
}*/
} else {
files.push(Path::new(tmp));
}
}
if files.len() == 0 {
files.push(Path::new("."));
}
if options.verbose {
println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m");
}
for tmp in files.iter() {
start_clean(&options, tmp, 0);
}
if options.verbose {
println!("\x1b[33;1mEnd of execution\x1b[0m");
}
} | {
let m = match ::std::fs::metadata(&entry) {
Ok(e) => e,
Err(e) => {
println!("An error occured on '{:?}': {}", entry, e);
return
}
};
let entry_name = match entry.to_str() {
Some(n) => n,
None => {
println!("Invalid entry '{:?}'", entry);
return
}
};
if m.is_file() || m.is_dir() {
if m.is_dir() {
if (options.recursive || entry_name == ".") &&
(options.level == 0 || level <= options.level) { | identifier_body |
main.rs | // Copyright 2016 Gomez Guillaume
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs;
use std::path::Path;
use std::str::FromStr;
struct CleanOptions {
recursive: bool,
verbose: bool,
confirmation: bool,
level: u32
}
fn ask_confirmation(file: &Path) -> bool {
if let Some(filename) = file.to_str() {
loop {
print!("clean: remove \x1b[37;1m'{}'\x1b[0m (y/n)? ", filename);
let mut s = String::new();
match std::io::stdin().read_line(&mut s) {
Ok(_) => {
let tmp_s = s.replace("\r\n", "").replace("\n", "");
if tmp_s == "y" || tmp_s == "yes" {
return true;
} else if tmp_s == "n" || tmp_s == "no" {
return false;
}
}
Err(_) => {}
}
}
} else {
println!("Unknown error on '{:?}'...", file);
false
}
}
fn start_clean(options: &CleanOptions, entry: &Path, level: u32) {
let m = match ::std::fs::metadata(&entry) {
Ok(e) => e,
Err(e) => {
println!("An error occured on '{:?}': {}", entry, e);
return
}
};
let entry_name = match entry.to_str() {
Some(n) => n,
None => {
println!("Invalid entry '{:?}'", entry);
return
}
};
if m.is_file() || m.is_dir() {
if m.is_dir() {
if (options.recursive || entry_name == ".") &&
(options.level == 0 || level <= options.level) {
match fs::read_dir(entry) {
Ok(res) => {
if options.verbose {
println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name);
}
for tmp in res {
match tmp {
Ok(current) => {
start_clean(options, ¤t.path(), level + 1);
},
Err(e) => println!("Error: {:?}", e)
};
}
if options.verbose {
println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name);
}
}
Err(e) => {
println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e);
}
}
}
} else {
match entry.file_name() {
Some(s) => {
match s.to_str() {
Some(ss) => if ss.ends_with("~") {
if!options.confirmation || ask_confirmation(&Path::new(s)) {
match fs::remove_file(entry) {
Ok(_) => {
if options.verbose {
println!("\x1b[32;1m{} deleted\x1b[0m", entry_name);
}
}
Err(e) => {
println!("\x1b[31;1mProblem with this file: {} -> {}\x1b[0m", entry_name, e);
}
}
}
},
_ => {}
}
}
None => {
println!("\x1b[31;1mProblem with this file: {}\x1b[0m", entry_name);
}
}
}
} else {
println!("\x1b[31;1mProblem with this entry: {}\x1b[0m", entry_name);
}
}
fn print_help() {
println!("./clean [options] [files | dirs]");
println!(" -r : recursive mode");
println!(" -v : verbose mode");
println!(" -i : prompt before every removal");
println!(" -l=[number] : Add a level for recursive mode");
println!("--help : print this help");
}
fn | () {
let mut args = Vec::new();
for argument in std::env::args() {
args.push(argument);
}
let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0};
let mut files = Vec::new();
args.remove(0);
for tmp in args.iter() {
if tmp.clone().into_bytes()[0] == '-' as u8 {
let mut tmp_arg = tmp.to_owned();
tmp_arg.remove(0);
if tmp_arg.len() > 0 {
for character in tmp_arg.into_bytes().iter() {
match *character as char {
'-' => {
if &*tmp == "--help" {
print_help();
return;
}
}
'r' => {
options.recursive = true;
}
'v' => {
options.verbose = true;
}
'i' => {
options.confirmation = true;
}
'l' => {
if tmp.len() < 4 || &tmp[0..3]!= "-l=" {
println!("The \"-l\" option has to be used like this:");
println!("clean -r -l=2");
return;
}
options.level = match u32::from_str(&tmp[3..]) {
Ok(u) => u,
Err(_) => {
println!("Please enter a valid number!");
return;
}
};
println!("Level is set to {}", options.level);
break;
}
_ => {
println!("Unknown option: '{}', to have the options list, please launch with '-h' option", *character as char);
return;
}
}
}
}/* else {
files.push(Path::new(tmp));
}*/
} else {
files.push(Path::new(tmp));
}
}
if files.len() == 0 {
files.push(Path::new("."));
}
if options.verbose {
println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m");
}
for tmp in files.iter() {
start_clean(&options, tmp, 0);
}
if options.verbose {
println!("\x1b[33;1mEnd of execution\x1b[0m");
}
} | main | identifier_name |
sha3.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/>.
//! Wrapper around tiny-keccak crate as well as common hash constants.
extern crate sha3 as sha3_ext;
use std::io;
use tiny_keccak::Keccak;
use hash::{H256, FixedHash};
use self::sha3_ext::*;
/// Get the SHA3 (i.e. Keccak) hash of the empty bytes string.
pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] );
/// The SHA3 of the RLP encoding of empty data.
pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] );
/// The SHA3 of the RLP encoding of empty list.
pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] );
/// Types implementing this trait are sha3able.
///
/// ```
/// extern crate ethcore_util as util;
/// use std::str::FromStr;
/// use util::sha3::*;
/// use util::hash::*;
///
/// fn main() {
/// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
/// }
/// ```
pub trait Hashable {
/// Calculate SHA3 of this object.
fn sha3(&self) -> H256;
/// Calculate SHA3 of this object and place result into dest.
fn sha3_into(&self, dest: &mut [u8]) {
self.sha3().copy_to(dest);
}
}
impl<T> Hashable for T where T: AsRef<[u8]> {
fn sha3(&self) -> H256 {
let mut ret: H256 = H256::zero();
self.sha3_into(&mut *ret);
ret
}
fn sha3_into(&self, dest: &mut [u8]) {
let input: &[u8] = self.as_ref();
unsafe {
sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len());
}
}
}
/// Calculate SHA3 of given stream.
pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> {
let mut output = [0u8; 32];
let mut input = [0u8; 1024];
let mut sha3 = Keccak::new_keccak256();
// read file
loop {
let some = try!(r.read(&mut input));
if some == 0 {
break;
}
sha3.update(&input[0..some]);
}
sha3.finalize(&mut output);
Ok(output.into())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::io::{Write, BufReader};
use super::*;
#[test]
fn sha3_empty() {
assert_eq!([0u8; 0].sha3(), SHA3_EMPTY);
}
#[test]
fn sha3_as() {
assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8"));
}
#[test]
fn should_sha3_a_file() {
// given
use devtools::RandomTempPath;
let path = RandomTempPath::new();
// Prepare file
{
let mut file = fs::File::create(&path).unwrap();
file.write_all(b"something").unwrap();
}
let mut file = BufReader::new(fs::File::open(&path).unwrap()); | // when
let hash = sha3(&mut file).unwrap();
// then
assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87");
}
} | random_line_split |
|
sha3.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/>.
//! Wrapper around tiny-keccak crate as well as common hash constants.
extern crate sha3 as sha3_ext;
use std::io;
use tiny_keccak::Keccak;
use hash::{H256, FixedHash};
use self::sha3_ext::*;
/// Get the SHA3 (i.e. Keccak) hash of the empty bytes string.
pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] );
/// The SHA3 of the RLP encoding of empty data.
pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] );
/// The SHA3 of the RLP encoding of empty list.
pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] );
/// Types implementing this trait are sha3able.
///
/// ```
/// extern crate ethcore_util as util;
/// use std::str::FromStr;
/// use util::sha3::*;
/// use util::hash::*;
///
/// fn main() {
/// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
/// }
/// ```
pub trait Hashable {
/// Calculate SHA3 of this object.
fn sha3(&self) -> H256;
/// Calculate SHA3 of this object and place result into dest.
fn sha3_into(&self, dest: &mut [u8]) {
self.sha3().copy_to(dest);
}
}
impl<T> Hashable for T where T: AsRef<[u8]> {
fn sha3(&self) -> H256 {
let mut ret: H256 = H256::zero();
self.sha3_into(&mut *ret);
ret
}
fn sha3_into(&self, dest: &mut [u8]) {
let input: &[u8] = self.as_ref();
unsafe {
sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len());
}
}
}
/// Calculate SHA3 of given stream.
pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> {
let mut output = [0u8; 32];
let mut input = [0u8; 1024];
let mut sha3 = Keccak::new_keccak256();
// read file
loop {
let some = try!(r.read(&mut input));
if some == 0 {
break;
}
sha3.update(&input[0..some]);
}
sha3.finalize(&mut output);
Ok(output.into())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::io::{Write, BufReader};
use super::*;
#[test]
fn sha3_empty() {
assert_eq!([0u8; 0].sha3(), SHA3_EMPTY);
}
#[test]
fn sha3_as() {
assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8"));
}
#[test]
fn | () {
// given
use devtools::RandomTempPath;
let path = RandomTempPath::new();
// Prepare file
{
let mut file = fs::File::create(&path).unwrap();
file.write_all(b"something").unwrap();
}
let mut file = BufReader::new(fs::File::open(&path).unwrap());
// when
let hash = sha3(&mut file).unwrap();
// then
assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87");
}
}
| should_sha3_a_file | identifier_name |
sha3.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/>.
//! Wrapper around tiny-keccak crate as well as common hash constants.
extern crate sha3 as sha3_ext;
use std::io;
use tiny_keccak::Keccak;
use hash::{H256, FixedHash};
use self::sha3_ext::*;
/// Get the SHA3 (i.e. Keccak) hash of the empty bytes string.
pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] );
/// The SHA3 of the RLP encoding of empty data.
pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] );
/// The SHA3 of the RLP encoding of empty list.
pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] );
/// Types implementing this trait are sha3able.
///
/// ```
/// extern crate ethcore_util as util;
/// use std::str::FromStr;
/// use util::sha3::*;
/// use util::hash::*;
///
/// fn main() {
/// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
/// }
/// ```
pub trait Hashable {
/// Calculate SHA3 of this object.
fn sha3(&self) -> H256;
/// Calculate SHA3 of this object and place result into dest.
fn sha3_into(&self, dest: &mut [u8]) {
self.sha3().copy_to(dest);
}
}
impl<T> Hashable for T where T: AsRef<[u8]> {
fn sha3(&self) -> H256 {
let mut ret: H256 = H256::zero();
self.sha3_into(&mut *ret);
ret
}
fn sha3_into(&self, dest: &mut [u8]) {
let input: &[u8] = self.as_ref();
unsafe {
sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len());
}
}
}
/// Calculate SHA3 of given stream.
pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> {
let mut output = [0u8; 32];
let mut input = [0u8; 1024];
let mut sha3 = Keccak::new_keccak256();
// read file
loop {
let some = try!(r.read(&mut input));
if some == 0 |
sha3.update(&input[0..some]);
}
sha3.finalize(&mut output);
Ok(output.into())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::io::{Write, BufReader};
use super::*;
#[test]
fn sha3_empty() {
assert_eq!([0u8; 0].sha3(), SHA3_EMPTY);
}
#[test]
fn sha3_as() {
assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8"));
}
#[test]
fn should_sha3_a_file() {
// given
use devtools::RandomTempPath;
let path = RandomTempPath::new();
// Prepare file
{
let mut file = fs::File::create(&path).unwrap();
file.write_all(b"something").unwrap();
}
let mut file = BufReader::new(fs::File::open(&path).unwrap());
// when
let hash = sha3(&mut file).unwrap();
// then
assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87");
}
}
| {
break;
} | conditional_block |
sha3.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/>.
//! Wrapper around tiny-keccak crate as well as common hash constants.
extern crate sha3 as sha3_ext;
use std::io;
use tiny_keccak::Keccak;
use hash::{H256, FixedHash};
use self::sha3_ext::*;
/// Get the SHA3 (i.e. Keccak) hash of the empty bytes string.
pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] );
/// The SHA3 of the RLP encoding of empty data.
pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] );
/// The SHA3 of the RLP encoding of empty list.
pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] );
/// Types implementing this trait are sha3able.
///
/// ```
/// extern crate ethcore_util as util;
/// use std::str::FromStr;
/// use util::sha3::*;
/// use util::hash::*;
///
/// fn main() {
/// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
/// }
/// ```
pub trait Hashable {
/// Calculate SHA3 of this object.
fn sha3(&self) -> H256;
/// Calculate SHA3 of this object and place result into dest.
fn sha3_into(&self, dest: &mut [u8]) {
self.sha3().copy_to(dest);
}
}
impl<T> Hashable for T where T: AsRef<[u8]> {
fn sha3(&self) -> H256 |
fn sha3_into(&self, dest: &mut [u8]) {
let input: &[u8] = self.as_ref();
unsafe {
sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len());
}
}
}
/// Calculate SHA3 of given stream.
pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> {
let mut output = [0u8; 32];
let mut input = [0u8; 1024];
let mut sha3 = Keccak::new_keccak256();
// read file
loop {
let some = try!(r.read(&mut input));
if some == 0 {
break;
}
sha3.update(&input[0..some]);
}
sha3.finalize(&mut output);
Ok(output.into())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::io::{Write, BufReader};
use super::*;
#[test]
fn sha3_empty() {
assert_eq!([0u8; 0].sha3(), SHA3_EMPTY);
}
#[test]
fn sha3_as() {
assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8"));
}
#[test]
fn should_sha3_a_file() {
// given
use devtools::RandomTempPath;
let path = RandomTempPath::new();
// Prepare file
{
let mut file = fs::File::create(&path).unwrap();
file.write_all(b"something").unwrap();
}
let mut file = BufReader::new(fs::File::open(&path).unwrap());
// when
let hash = sha3(&mut file).unwrap();
// then
assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87");
}
}
| {
let mut ret: H256 = H256::zero();
self.sha3_into(&mut *ret);
ret
} | identifier_body |
mod.rs | #[cfg(test)]
use game;
use ai;
use ai::run_match;
use constants::LINES;
use std::sync::Arc; | fn match_mc() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player = ai::mc::MonteCarloAI::new(1000);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn match_mc_tree() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn match_tree() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn subset_coherence() {
// This is a property based test, see QuickCheck for more information.
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
for _ in 0..10000 {
// Ensure that all positions returned by the Subset iterator are
// contained in the Subset.
let subset = game::Subset(rng.next_u64());
for position in subset.iter() {
println!("{:?}", position);
assert!(subset.contains(position));
}
}
} |
#[test] | random_line_split |
mod.rs | #[cfg(test)]
use game;
use ai;
use ai::run_match;
use constants::LINES;
use std::sync::Arc;
#[test]
fn match_mc() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player = ai::mc::MonteCarloAI::new(1000);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn match_mc_tree() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn match_tree() |
#[test]
fn subset_coherence() {
// This is a property based test, see QuickCheck for more information.
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
for _ in 0..10000 {
// Ensure that all positions returned by the Subset iterator are
// contained in the Subset.
let subset = game::Subset(rng.next_u64());
for position in subset.iter() {
println!("{:?}", position);
assert!(subset.contains(position));
}
}
}
| {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure, &mut white_player, &mut black_player);
} | identifier_body |
mod.rs | #[cfg(test)]
use game;
use ai;
use ai::run_match;
use constants::LINES;
use std::sync::Arc;
#[test]
fn match_mc() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player = ai::mc::MonteCarloAI::new(1000);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn match_mc_tree() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn | () {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn subset_coherence() {
// This is a property based test, see QuickCheck for more information.
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
for _ in 0..10000 {
// Ensure that all positions returned by the Subset iterator are
// contained in the Subset.
let subset = game::Subset(rng.next_u64());
for position in subset.iter() {
println!("{:?}", position);
assert!(subset.contains(position));
}
}
}
| match_tree | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.