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 |
---|---|---|---|---|
trait-inheritance-visibility.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.
mod traits {
pub trait Foo { fn f(&self) -> isize; }
impl Foo for isize { fn f(&self) -> isize { 10 } }
}
trait Quux: traits::Foo { }
impl<T:traits::Foo> Quux for T { }
// Foo is not in scope but because Quux is we can still access
// Foo's methods on a Quux bound typaram
fn f<T:Quux>(x: &T) |
pub fn main() {
f(&0)
}
| {
assert_eq!(x.f(), 10);
} | identifier_body |
trait-inheritance-visibility.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.
mod traits {
pub trait Foo { fn f(&self) -> isize; }
| }
trait Quux: traits::Foo { }
impl<T:traits::Foo> Quux for T { }
// Foo is not in scope but because Quux is we can still access
// Foo's methods on a Quux bound typaram
fn f<T:Quux>(x: &T) {
assert_eq!(x.f(), 10);
}
pub fn main() {
f(&0)
} | impl Foo for isize { fn f(&self) -> isize { 10 } } | random_line_split |
trait-inheritance-visibility.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.
mod traits {
pub trait Foo { fn f(&self) -> isize; }
impl Foo for isize { fn | (&self) -> isize { 10 } }
}
trait Quux: traits::Foo { }
impl<T:traits::Foo> Quux for T { }
// Foo is not in scope but because Quux is we can still access
// Foo's methods on a Quux bound typaram
fn f<T:Quux>(x: &T) {
assert_eq!(x.f(), 10);
}
pub fn main() {
f(&0)
}
| f | identifier_name |
message_queue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use std::sync::Arc;
use std::sync::mpsc_queue as mpsc;
pub use self::PopResult::{Inconsistent, Empty, Data};
pub enum PopResult<T> {
Inconsistent,
Empty,
Data(T),
}
pub fn queue<T: Send>() -> (Consumer<T>, Producer<T>) {
let a = Arc::new(mpsc::Queue::new());
(Consumer { inner: a.clone(), noshare: marker::NoSync },
Producer { inner: a, noshare: marker::NoSync })
}
pub struct | <T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
pub struct Consumer<T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
impl<T: Send> Consumer<T> {
pub fn pop(&self) -> PopResult<T> {
match self.inner.pop() {
mpsc::Inconsistent => Inconsistent,
mpsc::Empty => Empty,
mpsc::Data(t) => Data(t),
}
}
pub fn casual_pop(&self) -> Option<T> {
match self.inner.pop() {
mpsc::Inconsistent => None,
mpsc::Empty => None,
mpsc::Data(t) => Some(t),
}
}
}
impl<T: Send> Producer<T> {
pub fn push(&self, t: T) {
self.inner.push(t);
}
}
impl<T: Send> Clone for Producer<T> {
fn clone(&self) -> Producer<T> {
Producer { inner: self.inner.clone(), noshare: marker::NoSync }
}
}
| Producer | identifier_name |
message_queue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
use std::kinds::marker;
use std::sync::Arc;
use std::sync::mpsc_queue as mpsc;
pub use self::PopResult::{Inconsistent, Empty, Data};
pub enum PopResult<T> {
Inconsistent,
Empty,
Data(T),
}
pub fn queue<T: Send>() -> (Consumer<T>, Producer<T>) {
let a = Arc::new(mpsc::Queue::new());
(Consumer { inner: a.clone(), noshare: marker::NoSync },
Producer { inner: a, noshare: marker::NoSync })
}
pub struct Producer<T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
pub struct Consumer<T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
impl<T: Send> Consumer<T> {
pub fn pop(&self) -> PopResult<T> {
match self.inner.pop() {
mpsc::Inconsistent => Inconsistent,
mpsc::Empty => Empty,
mpsc::Data(t) => Data(t),
}
}
pub fn casual_pop(&self) -> Option<T> {
match self.inner.pop() {
mpsc::Inconsistent => None,
mpsc::Empty => None,
mpsc::Data(t) => Some(t),
}
}
}
impl<T: Send> Producer<T> {
pub fn push(&self, t: T) {
self.inner.push(t);
}
}
impl<T: Send> Clone for Producer<T> {
fn clone(&self) -> Producer<T> {
Producer { inner: self.inner.clone(), noshare: marker::NoSync }
}
} | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
message_queue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use std::sync::Arc;
use std::sync::mpsc_queue as mpsc;
pub use self::PopResult::{Inconsistent, Empty, Data};
pub enum PopResult<T> {
Inconsistent,
Empty,
Data(T),
}
pub fn queue<T: Send>() -> (Consumer<T>, Producer<T>) |
pub struct Producer<T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
pub struct Consumer<T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
impl<T: Send> Consumer<T> {
pub fn pop(&self) -> PopResult<T> {
match self.inner.pop() {
mpsc::Inconsistent => Inconsistent,
mpsc::Empty => Empty,
mpsc::Data(t) => Data(t),
}
}
pub fn casual_pop(&self) -> Option<T> {
match self.inner.pop() {
mpsc::Inconsistent => None,
mpsc::Empty => None,
mpsc::Data(t) => Some(t),
}
}
}
impl<T: Send> Producer<T> {
pub fn push(&self, t: T) {
self.inner.push(t);
}
}
impl<T: Send> Clone for Producer<T> {
fn clone(&self) -> Producer<T> {
Producer { inner: self.inner.clone(), noshare: marker::NoSync }
}
}
| {
let a = Arc::new(mpsc::Queue::new());
(Consumer { inner: a.clone(), noshare: marker::NoSync },
Producer { inner: a, noshare: marker::NoSync })
} | identifier_body |
client.rs | #![feature(core, io, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::old_io::net::ip::Ipv4Addr;
use hyper::server::{Request, Response, Server};
use hyper::header::Headers;
use hyper::Client;
fn listen() -> hyper::server::Listening {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
server.listen(handle).unwrap()
}
macro_rules! try_return(
($e:expr) => {{
match $e {
Ok(v) => v,
Err(..) => return
}
}}
);
fn | (_r: Request, res: Response) {
static BODY: &'static [u8] = b"Benchmarking hyper vs others!";
let mut res = try_return!(res.start());
try_return!(res.write_all(BODY));
try_return!(res.end());
}
#[derive(Clone)]
struct Foo;
impl hyper::header::Header for Foo {
fn header_name() -> &'static str {
"x-foo"
}
fn parse_header(_: &[Vec<u8>]) -> Option<Foo> {
None
}
}
impl hyper::header::HeaderFormat for Foo {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("Bar")
}
}
#[bench]
fn bench_hyper(b: &mut test::Bencher) {
let mut listening = listen();
let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
let mut client = Client::new();
let mut headers = Headers::new();
headers.set(Foo);
b.iter(|| {
client.get(url).header(Foo).send().unwrap().read_to_string().unwrap();
});
listening.close().unwrap()
}
| handle | identifier_name |
client.rs | #![feature(core, io, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::old_io::net::ip::Ipv4Addr;
use hyper::server::{Request, Response, Server};
use hyper::header::Headers;
use hyper::Client;
fn listen() -> hyper::server::Listening {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
server.listen(handle).unwrap()
}
macro_rules! try_return(
($e:expr) => {{
match $e {
Ok(v) => v,
Err(..) => return
}
}}
);
fn handle(_r: Request, res: Response) {
static BODY: &'static [u8] = b"Benchmarking hyper vs others!";
let mut res = try_return!(res.start());
try_return!(res.write_all(BODY));
try_return!(res.end());
}
#[derive(Clone)]
struct Foo;
impl hyper::header::Header for Foo {
fn header_name() -> &'static str {
"x-foo"
}
fn parse_header(_: &[Vec<u8>]) -> Option<Foo> {
None
}
}
impl hyper::header::HeaderFormat for Foo {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("Bar")
}
}
#[bench]
fn bench_hyper(b: &mut test::Bencher) | {
let mut listening = listen();
let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
let mut client = Client::new();
let mut headers = Headers::new();
headers.set(Foo);
b.iter(|| {
client.get(url).header(Foo).send().unwrap().read_to_string().unwrap();
});
listening.close().unwrap()
} | identifier_body |
|
client.rs | #![feature(core, io, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::old_io::net::ip::Ipv4Addr;
use hyper::server::{Request, Response, Server};
use hyper::header::Headers;
use hyper::Client;
fn listen() -> hyper::server::Listening {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
server.listen(handle).unwrap()
}
macro_rules! try_return(
($e:expr) => {{
match $e {
Ok(v) => v,
Err(..) => return
}
}}
);
fn handle(_r: Request, res: Response) {
static BODY: &'static [u8] = b"Benchmarking hyper vs others!";
let mut res = try_return!(res.start());
try_return!(res.write_all(BODY));
try_return!(res.end());
}
#[derive(Clone)]
struct Foo;
impl hyper::header::Header for Foo {
fn header_name() -> &'static str {
"x-foo"
}
fn parse_header(_: &[Vec<u8>]) -> Option<Foo> {
None
}
}
impl hyper::header::HeaderFormat for Foo {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("Bar")
} | }
#[bench]
fn bench_hyper(b: &mut test::Bencher) {
let mut listening = listen();
let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
let mut client = Client::new();
let mut headers = Headers::new();
headers.set(Foo);
b.iter(|| {
client.get(url).header(Foo).send().unwrap().read_to_string().unwrap();
});
listening.close().unwrap()
} | random_line_split |
|
raw.rs | use std::borrow::Cow;
use std::fmt;
use http::buf::MemSlice;
/// A raw header value.
#[derive(Clone, PartialEq, Eq)]
pub struct Raw(Lines);
impl Raw {
/// Returns the amount of lines.
#[inline]
pub fn len(&self) -> usize {
match self.0 {
Lines::One(..) => 1,
Lines::Many(ref lines) => lines.len()
}
}
/// Returns the line if there is only 1.
#[inline]
pub fn one(&self) -> Option<&[u8]> {
match self.0 {
Lines::One(ref line) => Some(line.as_ref()),
Lines::Many(ref lines) if lines.len() == 1 => Some(lines[0].as_ref()),
_ => None
}
}
/// Iterate the lines of raw bytes.
#[inline]
pub fn iter(&self) -> RawLines {
RawLines {
inner: &self.0,
pos: 0,
}
}
/// Append a line to this `Raw` header value.
pub fn push(&mut self, val: &[u8]) {
self.push_line(maybe_literal(val.into()));
}
fn push_line(&mut self, line: Line) {
let lines = ::std::mem::replace(&mut self.0, Lines::Many(Vec::new()));
match lines {
Lines::One(one) => {
self.0 = Lines::Many(vec![one, line]);
}
Lines::Many(mut lines) => {
lines.push(line);
self.0 = Lines::Many(lines);
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Lines {
One(Line),
Many(Vec<Line>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Line {
Static(&'static [u8]),
Owned(Vec<u8>),
Shared(MemSlice),
}
fn eq<A: AsRef<[u8]>, B: AsRef<[u8]>>(a: &[A], b: &[B]) -> bool {
if a.len()!= b.len() {
false
} else {
for (a, b) in a.iter().zip(b.iter()) {
if a.as_ref()!= b.as_ref() {
return false
}
}
true
}
}
impl PartialEq<[Vec<u8>]> for Raw {
fn eq(&self, bytes: &[Vec<u8>]) -> bool {
match self.0 {
Lines::One(ref line) => eq(&[line], bytes),
Lines::Many(ref lines) => eq(lines, bytes)
}
}
}
impl PartialEq<[u8]> for Raw {
fn eq(&self, bytes: &[u8]) -> bool {
match self.0 {
Lines::One(ref line) => line.as_ref() == bytes,
Lines::Many(..) => false
}
}
}
impl PartialEq<str> for Raw {
fn eq(&self, s: &str) -> bool {
match self.0 {
Lines::One(ref line) => line.as_ref() == s.as_bytes(),
Lines::Many(..) => false
}
}
}
impl From<Vec<Vec<u8>>> for Raw {
#[inline]
fn from(val: Vec<Vec<u8>>) -> Raw {
Raw(Lines::Many(
val.into_iter()
.map(|vec| maybe_literal(vec.into()))
.collect()
))
}
}
impl From<String> for Raw {
#[inline]
fn from(val: String) -> Raw {
let vec: Vec<u8> = val.into();
vec.into()
}
}
impl From<Vec<u8>> for Raw {
#[inline]
fn | (val: Vec<u8>) -> Raw {
Raw(Lines::One(Line::from(val)))
}
}
impl From<&'static str> for Raw {
fn from(val: &'static str) -> Raw {
Raw(Lines::One(Line::Static(val.as_bytes())))
}
}
impl From<&'static [u8]> for Raw {
fn from(val: &'static [u8]) -> Raw {
Raw(Lines::One(Line::Static(val)))
}
}
impl From<MemSlice> for Raw {
#[inline]
fn from(val: MemSlice) -> Raw {
Raw(Lines::One(Line::Shared(val)))
}
}
impl From<Vec<u8>> for Line {
#[inline]
fn from(val: Vec<u8>) -> Line {
Line::Owned(val)
}
}
impl From<MemSlice> for Line {
#[inline]
fn from(val: MemSlice) -> Line {
Line::Shared(val)
}
}
impl AsRef<[u8]> for Line {
fn as_ref(&self) -> &[u8] {
match *self {
Line::Static(ref s) => s,
Line::Owned(ref v) => v.as_ref(),
Line::Shared(ref m) => m.as_ref(),
}
}
}
pub fn parsed(val: MemSlice) -> Raw {
Raw(Lines::One(From::from(val)))
}
pub fn push(raw: &mut Raw, val: MemSlice) {
raw.push_line(Line::from(val));
}
impl fmt::Debug for Raw {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
Lines::One(ref line) => fmt::Debug::fmt(&[line], f),
Lines::Many(ref lines) => fmt::Debug::fmt(lines, f)
}
}
}
impl ::std::ops::Index<usize> for Raw {
type Output = [u8];
fn index(&self, idx: usize) -> &[u8] {
match self.0 {
Lines::One(ref line) => if idx == 0 {
line.as_ref()
} else {
panic!("index out of bounds: {}", idx)
},
Lines::Many(ref lines) => lines[idx].as_ref()
}
}
}
macro_rules! literals {
($($len:expr => $($value:expr),+;)+) => (
fn maybe_literal<'a>(s: Cow<'a, [u8]>) -> Line {
match s.len() {
$($len => {
$(
if s.as_ref() == $value {
return Line::Static($value);
}
)+
})+
_ => ()
}
Line::from(s.into_owned())
}
#[test]
fn test_literal_lens() {
$(
$({
let s = $value;
assert!(s.len() == $len, "{:?} has len of {}, listed as {}", s, s.len(), $len);
})+
)+
}
);
}
literals! {
1 => b"*", b"0";
3 => b"*/*";
4 => b"gzip";
5 => b"close";
7 => b"chunked";
10 => b"keep-alive";
}
impl<'a> IntoIterator for &'a Raw {
type IntoIter = RawLines<'a>;
type Item = &'a [u8];
fn into_iter(self) -> RawLines<'a> {
self.iter()
}
}
#[derive(Debug)]
pub struct RawLines<'a> {
inner: &'a Lines,
pos: usize,
}
impl<'a> Iterator for RawLines<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
let current_pos = self.pos;
self.pos += 1;
match *self.inner {
Lines::One(ref line) => {
if current_pos == 0 {
Some(line.as_ref())
} else {
None
}
}
Lines::Many(ref lines) => lines.get(current_pos).map(|l| l.as_ref()),
}
}
}
| from | identifier_name |
raw.rs | use std::borrow::Cow;
use std::fmt;
use http::buf::MemSlice;
/// A raw header value.
#[derive(Clone, PartialEq, Eq)]
pub struct Raw(Lines);
impl Raw {
/// Returns the amount of lines.
#[inline]
pub fn len(&self) -> usize {
match self.0 {
Lines::One(..) => 1,
Lines::Many(ref lines) => lines.len()
}
}
/// Returns the line if there is only 1.
#[inline]
pub fn one(&self) -> Option<&[u8]> {
match self.0 {
Lines::One(ref line) => Some(line.as_ref()),
Lines::Many(ref lines) if lines.len() == 1 => Some(lines[0].as_ref()),
_ => None
}
}
/// Iterate the lines of raw bytes.
#[inline]
pub fn iter(&self) -> RawLines {
RawLines {
inner: &self.0,
pos: 0,
}
}
/// Append a line to this `Raw` header value.
pub fn push(&mut self, val: &[u8]) {
self.push_line(maybe_literal(val.into()));
}
fn push_line(&mut self, line: Line) {
let lines = ::std::mem::replace(&mut self.0, Lines::Many(Vec::new()));
match lines {
Lines::One(one) => {
self.0 = Lines::Many(vec![one, line]);
}
Lines::Many(mut lines) => {
lines.push(line);
self.0 = Lines::Many(lines);
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)] | #[derive(Debug, Clone, PartialEq, Eq)]
enum Line {
Static(&'static [u8]),
Owned(Vec<u8>),
Shared(MemSlice),
}
fn eq<A: AsRef<[u8]>, B: AsRef<[u8]>>(a: &[A], b: &[B]) -> bool {
if a.len()!= b.len() {
false
} else {
for (a, b) in a.iter().zip(b.iter()) {
if a.as_ref()!= b.as_ref() {
return false
}
}
true
}
}
impl PartialEq<[Vec<u8>]> for Raw {
fn eq(&self, bytes: &[Vec<u8>]) -> bool {
match self.0 {
Lines::One(ref line) => eq(&[line], bytes),
Lines::Many(ref lines) => eq(lines, bytes)
}
}
}
impl PartialEq<[u8]> for Raw {
fn eq(&self, bytes: &[u8]) -> bool {
match self.0 {
Lines::One(ref line) => line.as_ref() == bytes,
Lines::Many(..) => false
}
}
}
impl PartialEq<str> for Raw {
fn eq(&self, s: &str) -> bool {
match self.0 {
Lines::One(ref line) => line.as_ref() == s.as_bytes(),
Lines::Many(..) => false
}
}
}
impl From<Vec<Vec<u8>>> for Raw {
#[inline]
fn from(val: Vec<Vec<u8>>) -> Raw {
Raw(Lines::Many(
val.into_iter()
.map(|vec| maybe_literal(vec.into()))
.collect()
))
}
}
impl From<String> for Raw {
#[inline]
fn from(val: String) -> Raw {
let vec: Vec<u8> = val.into();
vec.into()
}
}
impl From<Vec<u8>> for Raw {
#[inline]
fn from(val: Vec<u8>) -> Raw {
Raw(Lines::One(Line::from(val)))
}
}
impl From<&'static str> for Raw {
fn from(val: &'static str) -> Raw {
Raw(Lines::One(Line::Static(val.as_bytes())))
}
}
impl From<&'static [u8]> for Raw {
fn from(val: &'static [u8]) -> Raw {
Raw(Lines::One(Line::Static(val)))
}
}
impl From<MemSlice> for Raw {
#[inline]
fn from(val: MemSlice) -> Raw {
Raw(Lines::One(Line::Shared(val)))
}
}
impl From<Vec<u8>> for Line {
#[inline]
fn from(val: Vec<u8>) -> Line {
Line::Owned(val)
}
}
impl From<MemSlice> for Line {
#[inline]
fn from(val: MemSlice) -> Line {
Line::Shared(val)
}
}
impl AsRef<[u8]> for Line {
fn as_ref(&self) -> &[u8] {
match *self {
Line::Static(ref s) => s,
Line::Owned(ref v) => v.as_ref(),
Line::Shared(ref m) => m.as_ref(),
}
}
}
pub fn parsed(val: MemSlice) -> Raw {
Raw(Lines::One(From::from(val)))
}
pub fn push(raw: &mut Raw, val: MemSlice) {
raw.push_line(Line::from(val));
}
impl fmt::Debug for Raw {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
Lines::One(ref line) => fmt::Debug::fmt(&[line], f),
Lines::Many(ref lines) => fmt::Debug::fmt(lines, f)
}
}
}
impl ::std::ops::Index<usize> for Raw {
type Output = [u8];
fn index(&self, idx: usize) -> &[u8] {
match self.0 {
Lines::One(ref line) => if idx == 0 {
line.as_ref()
} else {
panic!("index out of bounds: {}", idx)
},
Lines::Many(ref lines) => lines[idx].as_ref()
}
}
}
macro_rules! literals {
($($len:expr => $($value:expr),+;)+) => (
fn maybe_literal<'a>(s: Cow<'a, [u8]>) -> Line {
match s.len() {
$($len => {
$(
if s.as_ref() == $value {
return Line::Static($value);
}
)+
})+
_ => ()
}
Line::from(s.into_owned())
}
#[test]
fn test_literal_lens() {
$(
$({
let s = $value;
assert!(s.len() == $len, "{:?} has len of {}, listed as {}", s, s.len(), $len);
})+
)+
}
);
}
literals! {
1 => b"*", b"0";
3 => b"*/*";
4 => b"gzip";
5 => b"close";
7 => b"chunked";
10 => b"keep-alive";
}
impl<'a> IntoIterator for &'a Raw {
type IntoIter = RawLines<'a>;
type Item = &'a [u8];
fn into_iter(self) -> RawLines<'a> {
self.iter()
}
}
#[derive(Debug)]
pub struct RawLines<'a> {
inner: &'a Lines,
pos: usize,
}
impl<'a> Iterator for RawLines<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
let current_pos = self.pos;
self.pos += 1;
match *self.inner {
Lines::One(ref line) => {
if current_pos == 0 {
Some(line.as_ref())
} else {
None
}
}
Lines::Many(ref lines) => lines.get(current_pos).map(|l| l.as_ref()),
}
}
} | enum Lines {
One(Line),
Many(Vec<Line>),
}
| random_line_split |
raw.rs | use std::borrow::Cow;
use std::fmt;
use http::buf::MemSlice;
/// A raw header value.
#[derive(Clone, PartialEq, Eq)]
pub struct Raw(Lines);
impl Raw {
/// Returns the amount of lines.
#[inline]
pub fn len(&self) -> usize {
match self.0 {
Lines::One(..) => 1,
Lines::Many(ref lines) => lines.len()
}
}
/// Returns the line if there is only 1.
#[inline]
pub fn one(&self) -> Option<&[u8]> {
match self.0 {
Lines::One(ref line) => Some(line.as_ref()),
Lines::Many(ref lines) if lines.len() == 1 => Some(lines[0].as_ref()),
_ => None
}
}
/// Iterate the lines of raw bytes.
#[inline]
pub fn iter(&self) -> RawLines |
/// Append a line to this `Raw` header value.
pub fn push(&mut self, val: &[u8]) {
self.push_line(maybe_literal(val.into()));
}
fn push_line(&mut self, line: Line) {
let lines = ::std::mem::replace(&mut self.0, Lines::Many(Vec::new()));
match lines {
Lines::One(one) => {
self.0 = Lines::Many(vec![one, line]);
}
Lines::Many(mut lines) => {
lines.push(line);
self.0 = Lines::Many(lines);
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Lines {
One(Line),
Many(Vec<Line>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Line {
Static(&'static [u8]),
Owned(Vec<u8>),
Shared(MemSlice),
}
fn eq<A: AsRef<[u8]>, B: AsRef<[u8]>>(a: &[A], b: &[B]) -> bool {
if a.len()!= b.len() {
false
} else {
for (a, b) in a.iter().zip(b.iter()) {
if a.as_ref()!= b.as_ref() {
return false
}
}
true
}
}
impl PartialEq<[Vec<u8>]> for Raw {
fn eq(&self, bytes: &[Vec<u8>]) -> bool {
match self.0 {
Lines::One(ref line) => eq(&[line], bytes),
Lines::Many(ref lines) => eq(lines, bytes)
}
}
}
impl PartialEq<[u8]> for Raw {
fn eq(&self, bytes: &[u8]) -> bool {
match self.0 {
Lines::One(ref line) => line.as_ref() == bytes,
Lines::Many(..) => false
}
}
}
impl PartialEq<str> for Raw {
fn eq(&self, s: &str) -> bool {
match self.0 {
Lines::One(ref line) => line.as_ref() == s.as_bytes(),
Lines::Many(..) => false
}
}
}
impl From<Vec<Vec<u8>>> for Raw {
#[inline]
fn from(val: Vec<Vec<u8>>) -> Raw {
Raw(Lines::Many(
val.into_iter()
.map(|vec| maybe_literal(vec.into()))
.collect()
))
}
}
impl From<String> for Raw {
#[inline]
fn from(val: String) -> Raw {
let vec: Vec<u8> = val.into();
vec.into()
}
}
impl From<Vec<u8>> for Raw {
#[inline]
fn from(val: Vec<u8>) -> Raw {
Raw(Lines::One(Line::from(val)))
}
}
impl From<&'static str> for Raw {
fn from(val: &'static str) -> Raw {
Raw(Lines::One(Line::Static(val.as_bytes())))
}
}
impl From<&'static [u8]> for Raw {
fn from(val: &'static [u8]) -> Raw {
Raw(Lines::One(Line::Static(val)))
}
}
impl From<MemSlice> for Raw {
#[inline]
fn from(val: MemSlice) -> Raw {
Raw(Lines::One(Line::Shared(val)))
}
}
impl From<Vec<u8>> for Line {
#[inline]
fn from(val: Vec<u8>) -> Line {
Line::Owned(val)
}
}
impl From<MemSlice> for Line {
#[inline]
fn from(val: MemSlice) -> Line {
Line::Shared(val)
}
}
impl AsRef<[u8]> for Line {
fn as_ref(&self) -> &[u8] {
match *self {
Line::Static(ref s) => s,
Line::Owned(ref v) => v.as_ref(),
Line::Shared(ref m) => m.as_ref(),
}
}
}
pub fn parsed(val: MemSlice) -> Raw {
Raw(Lines::One(From::from(val)))
}
pub fn push(raw: &mut Raw, val: MemSlice) {
raw.push_line(Line::from(val));
}
impl fmt::Debug for Raw {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
Lines::One(ref line) => fmt::Debug::fmt(&[line], f),
Lines::Many(ref lines) => fmt::Debug::fmt(lines, f)
}
}
}
impl ::std::ops::Index<usize> for Raw {
type Output = [u8];
fn index(&self, idx: usize) -> &[u8] {
match self.0 {
Lines::One(ref line) => if idx == 0 {
line.as_ref()
} else {
panic!("index out of bounds: {}", idx)
},
Lines::Many(ref lines) => lines[idx].as_ref()
}
}
}
macro_rules! literals {
($($len:expr => $($value:expr),+;)+) => (
fn maybe_literal<'a>(s: Cow<'a, [u8]>) -> Line {
match s.len() {
$($len => {
$(
if s.as_ref() == $value {
return Line::Static($value);
}
)+
})+
_ => ()
}
Line::from(s.into_owned())
}
#[test]
fn test_literal_lens() {
$(
$({
let s = $value;
assert!(s.len() == $len, "{:?} has len of {}, listed as {}", s, s.len(), $len);
})+
)+
}
);
}
literals! {
1 => b"*", b"0";
3 => b"*/*";
4 => b"gzip";
5 => b"close";
7 => b"chunked";
10 => b"keep-alive";
}
impl<'a> IntoIterator for &'a Raw {
type IntoIter = RawLines<'a>;
type Item = &'a [u8];
fn into_iter(self) -> RawLines<'a> {
self.iter()
}
}
#[derive(Debug)]
pub struct RawLines<'a> {
inner: &'a Lines,
pos: usize,
}
impl<'a> Iterator for RawLines<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
let current_pos = self.pos;
self.pos += 1;
match *self.inner {
Lines::One(ref line) => {
if current_pos == 0 {
Some(line.as_ref())
} else {
None
}
}
Lines::Many(ref lines) => lines.get(current_pos).map(|l| l.as_ref()),
}
}
}
| {
RawLines {
inner: &self.0,
pos: 0,
}
} | identifier_body |
request.rs | #[derive(RustcDecodable, RustcEncodable)] | Ping,
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct UserFlagPair {
pub id: usize,
pub flag: String,
pub user: String,
}
impl CTFRequest {
pub fn verify_flag(id: usize, flag: String, user: String) -> Self {
CTFRequest::FlagOffer(UserFlagPair::new(id, flag, user))
}
pub fn view_leaderboard(start: usize, stop: usize) -> Self {
CTFRequest::Leaderboard(start, stop)
}
}
impl UserFlagPair {
pub fn new(id: usize, flag: String, user: String) -> Self {
UserFlagPair {
id: id,
flag: flag,
user: user,
}
}
} | pub enum CTFRequest {
FlagOffer(UserFlagPair),
Leaderboard(usize, usize), | random_line_split |
request.rs | #[derive(RustcDecodable, RustcEncodable)]
pub enum | {
FlagOffer(UserFlagPair),
Leaderboard(usize, usize),
Ping,
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct UserFlagPair {
pub id: usize,
pub flag: String,
pub user: String,
}
impl CTFRequest {
pub fn verify_flag(id: usize, flag: String, user: String) -> Self {
CTFRequest::FlagOffer(UserFlagPair::new(id, flag, user))
}
pub fn view_leaderboard(start: usize, stop: usize) -> Self {
CTFRequest::Leaderboard(start, stop)
}
}
impl UserFlagPair {
pub fn new(id: usize, flag: String, user: String) -> Self {
UserFlagPair {
id: id,
flag: flag,
user: user,
}
}
}
| CTFRequest | identifier_name |
stream.rs | use std::io::Read;
use std::fmt::{self, Debug};
use response::{Response, Responder, DEFAULT_CHUNK_SIZE};
use http::Status;
/// Streams a response to a client from an arbitrary `Read`er type.
///
/// The client is sent a "chunked" response, where the chunk size is at most
/// 4KiB. This means that at most 4KiB are stored in memory while the response
/// is being sent. This type should be used when sending responses that are
/// arbitrarily large in size, such as when streaming from a local socket.
pub struct Stream<T: Read>(T, u64);
impl<T: Read> Stream<T> {
/// Create a new stream from the given `reader`.
///
/// # Example
///
/// Stream a response from whatever is in `stdin`. Note: you probably
/// shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::from(io::stdin());
/// ```
pub fn from(reader: T) -> Stream<T> |
/// Create a new stream from the given `reader` and sets the chunk size for
/// each streamed chunk to `chunk_size` bytes.
///
/// # Example
///
/// Stream a response from whatever is in `stdin` with a chunk size of 10
/// bytes. Note: you probably shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::chunked(io::stdin(), 10);
/// ```
pub fn chunked(reader: T, chunk_size: u64) -> Stream<T> {
Stream(reader, chunk_size)
}
}
impl<T: Read + Debug> Debug for Stream<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Stream({:?})", self.0)
}
}
/// Sends a response to the client using the "Chunked" transfer encoding. The
/// maximum chunk size is 4KiB.
///
/// # Failure
///
/// If reading from the input stream fails at any point during the response, the
/// response is abandoned, and the response ends abruptly. An error is printed
/// to the console with an indication of what went wrong.
impl<'r, T: Read + 'r> Responder<'r> for Stream<T> {
fn respond(self) -> Result<Response<'r>, Status> {
Response::build().chunked_body(self.0, self.1).ok()
}
}
| {
Stream(reader, DEFAULT_CHUNK_SIZE)
} | identifier_body |
stream.rs | use std::io::Read;
use std::fmt::{self, Debug};
use response::{Response, Responder, DEFAULT_CHUNK_SIZE};
use http::Status;
/// Streams a response to a client from an arbitrary `Read`er type.
///
/// The client is sent a "chunked" response, where the chunk size is at most
/// 4KiB. This means that at most 4KiB are stored in memory while the response
/// is being sent. This type should be used when sending responses that are
/// arbitrarily large in size, such as when streaming from a local socket.
pub struct Stream<T: Read>(T, u64);
impl<T: Read> Stream<T> {
/// Create a new stream from the given `reader`.
///
/// # Example
///
/// Stream a response from whatever is in `stdin`. Note: you probably
/// shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::from(io::stdin());
/// ```
pub fn from(reader: T) -> Stream<T> {
Stream(reader, DEFAULT_CHUNK_SIZE)
}
/// Create a new stream from the given `reader` and sets the chunk size for
/// each streamed chunk to `chunk_size` bytes.
///
/// # Example
///
/// Stream a response from whatever is in `stdin` with a chunk size of 10
/// bytes. Note: you probably shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::chunked(io::stdin(), 10);
/// ```
pub fn | (reader: T, chunk_size: u64) -> Stream<T> {
Stream(reader, chunk_size)
}
}
impl<T: Read + Debug> Debug for Stream<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Stream({:?})", self.0)
}
}
/// Sends a response to the client using the "Chunked" transfer encoding. The
/// maximum chunk size is 4KiB.
///
/// # Failure
///
/// If reading from the input stream fails at any point during the response, the
/// response is abandoned, and the response ends abruptly. An error is printed
/// to the console with an indication of what went wrong.
impl<'r, T: Read + 'r> Responder<'r> for Stream<T> {
fn respond(self) -> Result<Response<'r>, Status> {
Response::build().chunked_body(self.0, self.1).ok()
}
}
| chunked | identifier_name |
stream.rs | use std::io::Read;
use std::fmt::{self, Debug};
use response::{Response, Responder, DEFAULT_CHUNK_SIZE};
use http::Status;
/// Streams a response to a client from an arbitrary `Read`er type.
///
/// The client is sent a "chunked" response, where the chunk size is at most
/// 4KiB. This means that at most 4KiB are stored in memory while the response
/// is being sent. This type should be used when sending responses that are
/// arbitrarily large in size, such as when streaming from a local socket.
pub struct Stream<T: Read>(T, u64);
impl<T: Read> Stream<T> {
/// Create a new stream from the given `reader`.
///
/// # Example
///
/// Stream a response from whatever is in `stdin`. Note: you probably
/// shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::from(io::stdin());
/// ```
pub fn from(reader: T) -> Stream<T> {
Stream(reader, DEFAULT_CHUNK_SIZE)
}
/// Create a new stream from the given `reader` and sets the chunk size for
/// each streamed chunk to `chunk_size` bytes.
///
/// # Example
///
/// Stream a response from whatever is in `stdin` with a chunk size of 10
/// bytes. Note: you probably shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::chunked(io::stdin(), 10);
/// ```
pub fn chunked(reader: T, chunk_size: u64) -> Stream<T> {
Stream(reader, chunk_size)
}
}
impl<T: Read + Debug> Debug for Stream<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Stream({:?})", self.0)
}
}
/// Sends a response to the client using the "Chunked" transfer encoding. The
/// maximum chunk size is 4KiB. | /// response is abandoned, and the response ends abruptly. An error is printed
/// to the console with an indication of what went wrong.
impl<'r, T: Read + 'r> Responder<'r> for Stream<T> {
fn respond(self) -> Result<Response<'r>, Status> {
Response::build().chunked_body(self.0, self.1).ok()
}
} | ///
/// # Failure
///
/// If reading from the input stream fails at any point during the response, the | random_line_split |
match-beginning-vert.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
enum Foo {
A,
B,
C,
D,
E,
}
use Foo::*;
| match *foo {
| A => println!("A"),
| B | C if 1 < 2 => println!("BC!"),
| _ => {},
}
}
} | fn main() {
for foo in &[A, B, C, D, E] { | random_line_split |
match-beginning-vert.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
enum | {
A,
B,
C,
D,
E,
}
use Foo::*;
fn main() {
for foo in &[A, B, C, D, E] {
match *foo {
| A => println!("A"),
| B | C if 1 < 2 => println!("BC!"),
| _ => {},
}
}
}
| Foo | identifier_name |
feature_collection.rs | // Copyright 2015 The GeoRust 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.
use std::collections::BTreeMap;
use rustc_serialize::json::{self, Json, ToJson};
use ::{Bbox, Crs, Error, Feature, FromObject, util};
/// Feature Collection Objects
///
/// [GeoJSON Format Specification § 2.3]
/// (http://geojson.org/geojson-spec.html#feature-collection-objects) | pub struct FeatureCollection {
pub bbox: Option<Bbox>,
pub crs: Option<Crs>,
pub features: Vec<Feature>,
}
impl<'a> From<&'a FeatureCollection> for json::Object {
fn from(fc: &'a FeatureCollection) -> json::Object {
let mut map = BTreeMap::new();
map.insert(String::from("type"), "FeatureCollection".to_json());
map.insert(String::from("features"), fc.features.to_json());
if let Some(ref crs) = fc.crs {
map.insert(String::from("crs"), crs.to_json());
}
if let Some(ref bbox) = fc.bbox {
map.insert(String::from("bbox"), bbox.to_json());
}
return map;
}
}
impl FromObject for FeatureCollection {
fn from_object(object: &json::Object) -> Result<Self, Error> {
return Ok(FeatureCollection{
bbox: try!(util::get_bbox(object)),
features: try!(util::get_features(object)),
crs: try!(util::get_crs(object)),
});
}
}
impl ToJson for FeatureCollection {
fn to_json(&self) -> json::Json {
return json::Json::Object(self.into());
}
} | #[derive(Clone, Debug, PartialEq)] | random_line_split |
feature_collection.rs | // Copyright 2015 The GeoRust 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.
use std::collections::BTreeMap;
use rustc_serialize::json::{self, Json, ToJson};
use ::{Bbox, Crs, Error, Feature, FromObject, util};
/// Feature Collection Objects
///
/// [GeoJSON Format Specification § 2.3]
/// (http://geojson.org/geojson-spec.html#feature-collection-objects)
#[derive(Clone, Debug, PartialEq)]
pub struct FeatureCollection {
pub bbox: Option<Bbox>,
pub crs: Option<Crs>,
pub features: Vec<Feature>,
}
impl<'a> From<&'a FeatureCollection> for json::Object {
fn from(fc: &'a FeatureCollection) -> json::Object {
let mut map = BTreeMap::new();
map.insert(String::from("type"), "FeatureCollection".to_json());
map.insert(String::from("features"), fc.features.to_json());
if let Some(ref crs) = fc.crs {
map.insert(String::from("crs"), crs.to_json());
}
if let Some(ref bbox) = fc.bbox {
map.insert(String::from("bbox"), bbox.to_json());
}
return map;
}
}
impl FromObject for FeatureCollection {
fn from_object(object: &json::Object) -> Result<Self, Error> {
return Ok(FeatureCollection{
bbox: try!(util::get_bbox(object)),
features: try!(util::get_features(object)),
crs: try!(util::get_crs(object)),
});
}
}
impl ToJson for FeatureCollection {
fn t | &self) -> json::Json {
return json::Json::Object(self.into());
}
}
| o_json( | identifier_name |
feature_collection.rs | // Copyright 2015 The GeoRust 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.
use std::collections::BTreeMap;
use rustc_serialize::json::{self, Json, ToJson};
use ::{Bbox, Crs, Error, Feature, FromObject, util};
/// Feature Collection Objects
///
/// [GeoJSON Format Specification § 2.3]
/// (http://geojson.org/geojson-spec.html#feature-collection-objects)
#[derive(Clone, Debug, PartialEq)]
pub struct FeatureCollection {
pub bbox: Option<Bbox>,
pub crs: Option<Crs>,
pub features: Vec<Feature>,
}
impl<'a> From<&'a FeatureCollection> for json::Object {
fn from(fc: &'a FeatureCollection) -> json::Object {
let mut map = BTreeMap::new();
map.insert(String::from("type"), "FeatureCollection".to_json());
map.insert(String::from("features"), fc.features.to_json());
if let Some(ref crs) = fc.crs { |
if let Some(ref bbox) = fc.bbox {
map.insert(String::from("bbox"), bbox.to_json());
}
return map;
}
}
impl FromObject for FeatureCollection {
fn from_object(object: &json::Object) -> Result<Self, Error> {
return Ok(FeatureCollection{
bbox: try!(util::get_bbox(object)),
features: try!(util::get_features(object)),
crs: try!(util::get_crs(object)),
});
}
}
impl ToJson for FeatureCollection {
fn to_json(&self) -> json::Json {
return json::Json::Object(self.into());
}
}
|
map.insert(String::from("crs"), crs.to_json());
}
| conditional_block |
color.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 azure::AzFloat;
use azure::azure::AzColor;
#[inline]
pub fn new(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor |
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn black() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }
}
#[inline]
pub fn transparent() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }
}
#[inline]
pub fn white() -> AzColor {
AzColor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
}
| {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
} | identifier_body |
color.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 azure::AzFloat;
use azure::azure::AzColor;
#[inline]
pub fn new(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
}
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor { | pub fn black() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }
}
#[inline]
pub fn transparent() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }
}
#[inline]
pub fn white() -> AzColor {
AzColor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
} | AzColor { r: r, g: g, b: b, a: a }
}
#[inline] | random_line_split |
color.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 azure::AzFloat;
use azure::azure::AzColor;
#[inline]
pub fn | (r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
}
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn black() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }
}
#[inline]
pub fn transparent() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }
}
#[inline]
pub fn white() -> AzColor {
AzColor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
}
| new | identifier_name |
city.rs | use iron::prelude::*;
use hyper::status::StatusCode;
use super::request_body;
use ::proto::response::*;
use ::proto::schema::NewCity;
use ::db::schema::*;
use ::db::*;
pub fn | (_: &mut Request) -> IronResult<Response> {
let query = City::select_builder().build();
let conn = get_db_connection();
info!("request GET /city");
let rows = conn.query(&query, &[]).unwrap();
let cities = rows.into_iter()
.map(City::from)
.collect::<Vec<City>>();
Ok(cities.as_response())
}
pub fn put_city(req: &mut Request) -> IronResult<Response> {
let new_city: NewCity = request_body(req)?;
info!("request PUT /city {{ {:?} }}", new_city);
let conn = get_db_connection();
let query = City::insert_query();
conn.execute(&query, &[&new_city.Name]).unwrap();
Ok(Response::with(StatusCode::Ok))
} | get_cities | identifier_name |
city.rs | use iron::prelude::*;
use hyper::status::StatusCode;
use super::request_body;
use ::proto::response::*;
use ::proto::schema::NewCity;
use ::db::schema::*;
use ::db::*;
pub fn get_cities(_: &mut Request) -> IronResult<Response> {
let query = City::select_builder().build();
let conn = get_db_connection();
info!("request GET /city"); |
Ok(cities.as_response())
}
pub fn put_city(req: &mut Request) -> IronResult<Response> {
let new_city: NewCity = request_body(req)?;
info!("request PUT /city {{ {:?} }}", new_city);
let conn = get_db_connection();
let query = City::insert_query();
conn.execute(&query, &[&new_city.Name]).unwrap();
Ok(Response::with(StatusCode::Ok))
} |
let rows = conn.query(&query, &[]).unwrap();
let cities = rows.into_iter()
.map(City::from)
.collect::<Vec<City>>(); | random_line_split |
city.rs | use iron::prelude::*;
use hyper::status::StatusCode;
use super::request_body;
use ::proto::response::*;
use ::proto::schema::NewCity;
use ::db::schema::*;
use ::db::*;
pub fn get_cities(_: &mut Request) -> IronResult<Response> |
pub fn put_city(req: &mut Request) -> IronResult<Response> {
let new_city: NewCity = request_body(req)?;
info!("request PUT /city {{ {:?} }}", new_city);
let conn = get_db_connection();
let query = City::insert_query();
conn.execute(&query, &[&new_city.Name]).unwrap();
Ok(Response::with(StatusCode::Ok))
} | {
let query = City::select_builder().build();
let conn = get_db_connection();
info!("request GET /city");
let rows = conn.query(&query, &[]).unwrap();
let cities = rows.into_iter()
.map(City::from)
.collect::<Vec<City>>();
Ok(cities.as_response())
} | identifier_body |
mouse.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use imp::ffi;
use imp::window::WindowImpl;
pub fn | (window: &WindowImpl) -> (i32, i32) {
let point = ffi::ve_mouse_get_location(window.window_handler);
(point.x as i32, point.y as i32)
}
pub fn screen_location() -> (i32, i32) {
let point = ffi::ve_mouse_get_global_location();
(point.x as i32, point.y as i32)
} | location | identifier_name |
mouse.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use imp::ffi;
use imp::window::WindowImpl;
pub fn location(window: &WindowImpl) -> (i32, i32) {
let point = ffi::ve_mouse_get_location(window.window_handler);
(point.x as i32, point.y as i32)
}
pub fn screen_location() -> (i32, i32) | {
let point = ffi::ve_mouse_get_global_location();
(point.x as i32, point.y as i32)
} | identifier_body |
|
mouse.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use imp::ffi;
use imp::window::WindowImpl;
pub fn location(window: &WindowImpl) -> (i32, i32) {
let point = ffi::ve_mouse_get_location(window.window_handler);
(point.x as i32, point.y as i32)
}
pub fn screen_location() -> (i32, i32) {
let point = ffi::ve_mouse_get_global_location(); | (point.x as i32, point.y as i32)
} | random_line_split |
|
extshadertexturelod.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::webglrenderingcontext::WebGLRenderingContext;
use canvas_traits::webgl::WebGLVersion;
use dom_struct::dom_struct;
#[dom_struct]
pub struct EXTShaderTextureLod {
reflector_: Reflector,
}
impl EXTShaderTextureLod {
fn new_inherited() -> Self {
Self {
reflector_: Reflector::new(),
}
}
}
impl WebGLExtension for EXTShaderTextureLod {
type Extension = Self;
fn new(ctx: &WebGLRenderingContext) -> DomRoot<Self> {
reflect_dom_object(Box::new(Self::new_inherited()), &*ctx.global())
}
fn spec() -> WebGLExtensionSpec {
WebGLExtensionSpec::Specific(WebGLVersion::WebGL1)
}
fn is_supported(ext: &WebGLExtensions) -> bool {
// This extension is always available on desktop GL. |
fn enable(_ext: &WebGLExtensions) {}
fn name() -> &'static str {
"EXT_shader_texture_lod"
}
} | !ext.is_gles() || ext.supports_gl_extension("GL_EXT_shader_texture_lod")
} | random_line_split |
extshadertexturelod.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::webglrenderingcontext::WebGLRenderingContext;
use canvas_traits::webgl::WebGLVersion;
use dom_struct::dom_struct;
#[dom_struct]
pub struct EXTShaderTextureLod {
reflector_: Reflector,
}
impl EXTShaderTextureLod {
fn new_inherited() -> Self {
Self {
reflector_: Reflector::new(),
}
}
}
impl WebGLExtension for EXTShaderTextureLod {
type Extension = Self;
fn new(ctx: &WebGLRenderingContext) -> DomRoot<Self> {
reflect_dom_object(Box::new(Self::new_inherited()), &*ctx.global())
}
fn spec() -> WebGLExtensionSpec {
WebGLExtensionSpec::Specific(WebGLVersion::WebGL1)
}
fn is_supported(ext: &WebGLExtensions) -> bool {
// This extension is always available on desktop GL.
!ext.is_gles() || ext.supports_gl_extension("GL_EXT_shader_texture_lod")
}
fn enable(_ext: &WebGLExtensions) {}
fn name() -> &'static str |
}
| {
"EXT_shader_texture_lod"
} | identifier_body |
extshadertexturelod.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::webglrenderingcontext::WebGLRenderingContext;
use canvas_traits::webgl::WebGLVersion;
use dom_struct::dom_struct;
#[dom_struct]
pub struct EXTShaderTextureLod {
reflector_: Reflector,
}
impl EXTShaderTextureLod {
fn new_inherited() -> Self {
Self {
reflector_: Reflector::new(),
}
}
}
impl WebGLExtension for EXTShaderTextureLod {
type Extension = Self;
fn new(ctx: &WebGLRenderingContext) -> DomRoot<Self> {
reflect_dom_object(Box::new(Self::new_inherited()), &*ctx.global())
}
fn spec() -> WebGLExtensionSpec {
WebGLExtensionSpec::Specific(WebGLVersion::WebGL1)
}
fn | (ext: &WebGLExtensions) -> bool {
// This extension is always available on desktop GL.
!ext.is_gles() || ext.supports_gl_extension("GL_EXT_shader_texture_lod")
}
fn enable(_ext: &WebGLExtensions) {}
fn name() -> &'static str {
"EXT_shader_texture_lod"
}
}
| is_supported | identifier_name |
structured-compare.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.
#[deriving(Show)]
enum foo { large, small, }
impl Copy for foo {}
impl PartialEq for foo {
fn eq(&self, other: &foo) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &foo) -> bool |
}
pub fn main() {
let a = (1i, 2i, 3i);
let b = (1i, 2i, 3i);
assert_eq!(a, b);
assert!((a!= (1, 2, 4)));
assert!((a < (1, 2, 4)));
assert!((a <= (1, 2, 4)));
assert!(((1i, 2i, 4i) > a));
assert!(((1i, 2i, 4i) >= a));
let x = foo::large;
let y = foo::small;
assert!((x!= y));
assert_eq!(x, foo::large);
assert!((x!= foo::small));
}
| { !(*self).eq(other) } | identifier_body |
structured-compare.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.
#[deriving(Show)]
enum foo { large, small, }
impl Copy for foo {}
impl PartialEq for foo {
fn eq(&self, other: &foo) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &foo) -> bool {!(*self).eq(other) }
}
pub fn | () {
let a = (1i, 2i, 3i);
let b = (1i, 2i, 3i);
assert_eq!(a, b);
assert!((a!= (1, 2, 4)));
assert!((a < (1, 2, 4)));
assert!((a <= (1, 2, 4)));
assert!(((1i, 2i, 4i) > a));
assert!(((1i, 2i, 4i) >= a));
let x = foo::large;
let y = foo::small;
assert!((x!= y));
assert_eq!(x, foo::large);
assert!((x!= foo::small));
}
| main | identifier_name |
structured-compare.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.
#[deriving(Show)]
enum foo { large, small, }
impl Copy for foo {}
impl PartialEq for foo {
fn eq(&self, other: &foo) -> bool {
((*self) as uint) == ((*other) as uint) | pub fn main() {
let a = (1i, 2i, 3i);
let b = (1i, 2i, 3i);
assert_eq!(a, b);
assert!((a!= (1, 2, 4)));
assert!((a < (1, 2, 4)));
assert!((a <= (1, 2, 4)));
assert!(((1i, 2i, 4i) > a));
assert!(((1i, 2i, 4i) >= a));
let x = foo::large;
let y = foo::small;
assert!((x!= y));
assert_eq!(x, foo::large);
assert!((x!= foo::small));
} | }
fn ne(&self, other: &foo) -> bool { !(*self).eq(other) }
}
| random_line_split |
symbol_analysis.rs | use tokens::*;
use symbols::*;
use support::*;
use plp::PLPWriter;
use symbols::commons::*;
use symbols::symbol_table::*;
pub fn get_accessor_namespace(symbol: &Symbol, symbol_table: &StaticSymbolTable) -> Option<String>
{
match symbol.symbol_class
{
SymbolClass::Variable(ref variable_type) => {
let potential_matches = symbol_table.lookup_by_name(&*variable_type);
if potential_matches.is_empty() { return None; }
let type_symbol = potential_matches[0];
let namespace = concatenate_namespace(&*type_symbol.namespace, &*type_symbol.name);
return Some(namespace);
},
SymbolClass::Structure(_, _) => {
panic!("get_accessor_namespace: Structure access not currently supported");
},
SymbolClass::Function(_, _, _, _) => { panic!("Expected Variable or Structure, found Function"); },
};
}
/// @return: (static_memory_label, static_init_label, local_init_label)
pub fn get_class_labels(class_symbol: &Symbol) -> (String, String, String)
{
let mut namespace_label = class_symbol.namespace.clone();
if!namespace_label.is_empty() { namespace_label.push_str("_"); }
namespace_label.push_str(&*class_symbol.name.clone());
let mut static_memory_label = namespace_label.clone();
static_memory_label.push_str("_static");
let mut static_init_label = static_memory_label.to_string();
static_init_label.push_str("_init");
let mut local_init_label = namespace_label.clone();
local_init_label.push_str("_local_init");
(static_memory_label, static_init_label, local_init_label)
}
/// @return: (method_label, return_label)
pub fn get_method_labels(method_symbol: &Symbol) -> (String, String)
{
let method_label = match method_symbol.location {
SymbolLocation::Memory(ref address) => address.label_name.clone(),
_ => { panic!("compile_method_body: Expected Memory address for method"); },
};
let mut return_label = method_label.clone();
return_label.push_str("_return");
(method_label, return_label)
}
/// @return (memory_label, memory_size)
pub fn get_static_allocation(method_symbol: &Symbol) -> (String, u16)
{
match method_symbol.symbol_class {
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(_, _, ref label_name, var_count) => (label_name.clone(), var_count as u16),
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
}
}
/// @return (memory_label, memory_size)
pub fn get_return_type_of(method_symbol: &Symbol) -> String
{
match method_symbol.symbol_class
{
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(ref return_type, _, _, _) => return_type.clone(),
SymbolClass::Structure(ref subtype, _) => |
}
}
/// @return ([arg1] [, arg2] {, arg3..})
pub fn get_arg_signature_of(method_symbol: &Symbol) -> String
{
let types: &Vec<String> = match method_symbol.symbol_class
{
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(_, ref arg_types, _, _) => arg_types,
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
};
let mut arg_signature = "(".to_string();
// Handle first arg type
if types.len() > 0
{
arg_signature.push_str(&*types[0]);
for ref arg_type in types[1..].iter()
{
arg_signature.push_str(",");
arg_signature.push_str(&*arg_type);
}
}
arg_signature.push_str(")");
arg_signature
}
| {
panic!("Expected Function found {}", subtype);
} | conditional_block |
symbol_analysis.rs | use tokens::*;
use symbols::*;
use support::*;
use plp::PLPWriter;
use symbols::commons::*;
use symbols::symbol_table::*;
pub fn get_accessor_namespace(symbol: &Symbol, symbol_table: &StaticSymbolTable) -> Option<String>
{
match symbol.symbol_class
{
SymbolClass::Variable(ref variable_type) => {
let potential_matches = symbol_table.lookup_by_name(&*variable_type); | let namespace = concatenate_namespace(&*type_symbol.namespace, &*type_symbol.name);
return Some(namespace);
},
SymbolClass::Structure(_, _) => {
panic!("get_accessor_namespace: Structure access not currently supported");
},
SymbolClass::Function(_, _, _, _) => { panic!("Expected Variable or Structure, found Function"); },
};
}
/// @return: (static_memory_label, static_init_label, local_init_label)
pub fn get_class_labels(class_symbol: &Symbol) -> (String, String, String)
{
let mut namespace_label = class_symbol.namespace.clone();
if!namespace_label.is_empty() { namespace_label.push_str("_"); }
namespace_label.push_str(&*class_symbol.name.clone());
let mut static_memory_label = namespace_label.clone();
static_memory_label.push_str("_static");
let mut static_init_label = static_memory_label.to_string();
static_init_label.push_str("_init");
let mut local_init_label = namespace_label.clone();
local_init_label.push_str("_local_init");
(static_memory_label, static_init_label, local_init_label)
}
/// @return: (method_label, return_label)
pub fn get_method_labels(method_symbol: &Symbol) -> (String, String)
{
let method_label = match method_symbol.location {
SymbolLocation::Memory(ref address) => address.label_name.clone(),
_ => { panic!("compile_method_body: Expected Memory address for method"); },
};
let mut return_label = method_label.clone();
return_label.push_str("_return");
(method_label, return_label)
}
/// @return (memory_label, memory_size)
pub fn get_static_allocation(method_symbol: &Symbol) -> (String, u16)
{
match method_symbol.symbol_class {
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(_, _, ref label_name, var_count) => (label_name.clone(), var_count as u16),
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
}
}
/// @return (memory_label, memory_size)
pub fn get_return_type_of(method_symbol: &Symbol) -> String
{
match method_symbol.symbol_class
{
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(ref return_type, _, _, _) => return_type.clone(),
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
}
}
/// @return ([arg1] [, arg2] {, arg3..})
pub fn get_arg_signature_of(method_symbol: &Symbol) -> String
{
let types: &Vec<String> = match method_symbol.symbol_class
{
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(_, ref arg_types, _, _) => arg_types,
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
};
let mut arg_signature = "(".to_string();
// Handle first arg type
if types.len() > 0
{
arg_signature.push_str(&*types[0]);
for ref arg_type in types[1..].iter()
{
arg_signature.push_str(",");
arg_signature.push_str(&*arg_type);
}
}
arg_signature.push_str(")");
arg_signature
} | if potential_matches.is_empty() { return None; }
let type_symbol = potential_matches[0];
| random_line_split |
symbol_analysis.rs | use tokens::*;
use symbols::*;
use support::*;
use plp::PLPWriter;
use symbols::commons::*;
use symbols::symbol_table::*;
pub fn get_accessor_namespace(symbol: &Symbol, symbol_table: &StaticSymbolTable) -> Option<String>
{
match symbol.symbol_class
{
SymbolClass::Variable(ref variable_type) => {
let potential_matches = symbol_table.lookup_by_name(&*variable_type);
if potential_matches.is_empty() { return None; }
let type_symbol = potential_matches[0];
let namespace = concatenate_namespace(&*type_symbol.namespace, &*type_symbol.name);
return Some(namespace);
},
SymbolClass::Structure(_, _) => {
panic!("get_accessor_namespace: Structure access not currently supported");
},
SymbolClass::Function(_, _, _, _) => { panic!("Expected Variable or Structure, found Function"); },
};
}
/// @return: (static_memory_label, static_init_label, local_init_label)
pub fn get_class_labels(class_symbol: &Symbol) -> (String, String, String)
{
let mut namespace_label = class_symbol.namespace.clone();
if!namespace_label.is_empty() { namespace_label.push_str("_"); }
namespace_label.push_str(&*class_symbol.name.clone());
let mut static_memory_label = namespace_label.clone();
static_memory_label.push_str("_static");
let mut static_init_label = static_memory_label.to_string();
static_init_label.push_str("_init");
let mut local_init_label = namespace_label.clone();
local_init_label.push_str("_local_init");
(static_memory_label, static_init_label, local_init_label)
}
/// @return: (method_label, return_label)
pub fn get_method_labels(method_symbol: &Symbol) -> (String, String)
{
let method_label = match method_symbol.location {
SymbolLocation::Memory(ref address) => address.label_name.clone(),
_ => { panic!("compile_method_body: Expected Memory address for method"); },
};
let mut return_label = method_label.clone();
return_label.push_str("_return");
(method_label, return_label)
}
/// @return (memory_label, memory_size)
pub fn | (method_symbol: &Symbol) -> (String, u16)
{
match method_symbol.symbol_class {
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(_, _, ref label_name, var_count) => (label_name.clone(), var_count as u16),
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
}
}
/// @return (memory_label, memory_size)
pub fn get_return_type_of(method_symbol: &Symbol) -> String
{
match method_symbol.symbol_class
{
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(ref return_type, _, _, _) => return_type.clone(),
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
}
}
/// @return ([arg1] [, arg2] {, arg3..})
pub fn get_arg_signature_of(method_symbol: &Symbol) -> String
{
let types: &Vec<String> = match method_symbol.symbol_class
{
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(_, ref arg_types, _, _) => arg_types,
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
};
let mut arg_signature = "(".to_string();
// Handle first arg type
if types.len() > 0
{
arg_signature.push_str(&*types[0]);
for ref arg_type in types[1..].iter()
{
arg_signature.push_str(",");
arg_signature.push_str(&*arg_type);
}
}
arg_signature.push_str(")");
arg_signature
}
| get_static_allocation | identifier_name |
symbol_analysis.rs | use tokens::*;
use symbols::*;
use support::*;
use plp::PLPWriter;
use symbols::commons::*;
use symbols::symbol_table::*;
pub fn get_accessor_namespace(symbol: &Symbol, symbol_table: &StaticSymbolTable) -> Option<String>
{
match symbol.symbol_class
{
SymbolClass::Variable(ref variable_type) => {
let potential_matches = symbol_table.lookup_by_name(&*variable_type);
if potential_matches.is_empty() { return None; }
let type_symbol = potential_matches[0];
let namespace = concatenate_namespace(&*type_symbol.namespace, &*type_symbol.name);
return Some(namespace);
},
SymbolClass::Structure(_, _) => {
panic!("get_accessor_namespace: Structure access not currently supported");
},
SymbolClass::Function(_, _, _, _) => { panic!("Expected Variable or Structure, found Function"); },
};
}
/// @return: (static_memory_label, static_init_label, local_init_label)
pub fn get_class_labels(class_symbol: &Symbol) -> (String, String, String)
{
let mut namespace_label = class_symbol.namespace.clone();
if!namespace_label.is_empty() { namespace_label.push_str("_"); }
namespace_label.push_str(&*class_symbol.name.clone());
let mut static_memory_label = namespace_label.clone();
static_memory_label.push_str("_static");
let mut static_init_label = static_memory_label.to_string();
static_init_label.push_str("_init");
let mut local_init_label = namespace_label.clone();
local_init_label.push_str("_local_init");
(static_memory_label, static_init_label, local_init_label)
}
/// @return: (method_label, return_label)
pub fn get_method_labels(method_symbol: &Symbol) -> (String, String)
{
let method_label = match method_symbol.location {
SymbolLocation::Memory(ref address) => address.label_name.clone(),
_ => { panic!("compile_method_body: Expected Memory address for method"); },
};
let mut return_label = method_label.clone();
return_label.push_str("_return");
(method_label, return_label)
}
/// @return (memory_label, memory_size)
pub fn get_static_allocation(method_symbol: &Symbol) -> (String, u16)
{
match method_symbol.symbol_class {
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(_, _, ref label_name, var_count) => (label_name.clone(), var_count as u16),
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
}
}
/// @return (memory_label, memory_size)
pub fn get_return_type_of(method_symbol: &Symbol) -> String
|
/// @return ([arg1] [, arg2] {, arg3..})
pub fn get_arg_signature_of(method_symbol: &Symbol) -> String
{
let types: &Vec<String> = match method_symbol.symbol_class
{
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(_, ref arg_types, _, _) => arg_types,
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
};
let mut arg_signature = "(".to_string();
// Handle first arg type
if types.len() > 0
{
arg_signature.push_str(&*types[0]);
for ref arg_type in types[1..].iter()
{
arg_signature.push_str(",");
arg_signature.push_str(&*arg_type);
}
}
arg_signature.push_str(")");
arg_signature
}
| {
match method_symbol.symbol_class
{
SymbolClass::Variable(_) => {
panic!("Expected Function found Variable");
},
SymbolClass::Function(ref return_type, _, _, _) => return_type.clone(),
SymbolClass::Structure(ref subtype, _) => {
panic!("Expected Function found {}", subtype);
}
}
} | identifier_body |
config.rs | //! The configuration format for the program container
use typedef::*;
pub const DEFAULT_SCALE: f64 = 4.0;
pub const DEFAULT_SCREEN_WIDTH: usize = 160;
pub const DEFAULT_SCREEN_HEIGHT: usize = 100;
pub const DEFAULT_WINDOW_TITLE: &str = "bakerVM";
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DisplayConfig {
#[serde(default)]
pub resolution: DisplayResolution,
pub default_scale: Float,
#[serde(default)]
pub hide_cursor: bool,
}
impl Default for DisplayConfig {
fn default() -> Self {
DisplayConfig {
resolution: Default::default(),
default_scale: DEFAULT_SCALE,
hide_cursor: true,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DisplayResolution {
pub width: usize,
pub height: usize,
}
impl Default for DisplayResolution {
fn default() -> Self {
DisplayResolution {
width: DEFAULT_SCREEN_WIDTH,
height: DEFAULT_SCREEN_HEIGHT,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
#[serde(default)]
pub title: String,
#[serde(default)]
pub display: DisplayConfig,
#[serde(default)]
pub input_enabled: bool,
}
impl Default for Config {
fn default() -> Self |
}
| {
Config {
title: DEFAULT_WINDOW_TITLE.into(),
display: Default::default(),
input_enabled: true,
}
} | identifier_body |
config.rs | //! The configuration format for the program container
use typedef::*;
pub const DEFAULT_SCALE: f64 = 4.0;
pub const DEFAULT_SCREEN_WIDTH: usize = 160;
pub const DEFAULT_SCREEN_HEIGHT: usize = 100;
pub const DEFAULT_WINDOW_TITLE: &str = "bakerVM";
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DisplayConfig {
#[serde(default)]
pub resolution: DisplayResolution,
pub default_scale: Float,
#[serde(default)]
pub hide_cursor: bool,
}
impl Default for DisplayConfig {
fn | () -> Self {
DisplayConfig {
resolution: Default::default(),
default_scale: DEFAULT_SCALE,
hide_cursor: true,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DisplayResolution {
pub width: usize,
pub height: usize,
}
impl Default for DisplayResolution {
fn default() -> Self {
DisplayResolution {
width: DEFAULT_SCREEN_WIDTH,
height: DEFAULT_SCREEN_HEIGHT,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
#[serde(default)]
pub title: String,
#[serde(default)]
pub display: DisplayConfig,
#[serde(default)]
pub input_enabled: bool,
}
impl Default for Config {
fn default() -> Self {
Config {
title: DEFAULT_WINDOW_TITLE.into(),
display: Default::default(),
input_enabled: true,
}
}
}
| default | identifier_name |
config.rs | //! The configuration format for the program container
use typedef::*; | pub const DEFAULT_SCREEN_HEIGHT: usize = 100;
pub const DEFAULT_WINDOW_TITLE: &str = "bakerVM";
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DisplayConfig {
#[serde(default)]
pub resolution: DisplayResolution,
pub default_scale: Float,
#[serde(default)]
pub hide_cursor: bool,
}
impl Default for DisplayConfig {
fn default() -> Self {
DisplayConfig {
resolution: Default::default(),
default_scale: DEFAULT_SCALE,
hide_cursor: true,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DisplayResolution {
pub width: usize,
pub height: usize,
}
impl Default for DisplayResolution {
fn default() -> Self {
DisplayResolution {
width: DEFAULT_SCREEN_WIDTH,
height: DEFAULT_SCREEN_HEIGHT,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
#[serde(default)]
pub title: String,
#[serde(default)]
pub display: DisplayConfig,
#[serde(default)]
pub input_enabled: bool,
}
impl Default for Config {
fn default() -> Self {
Config {
title: DEFAULT_WINDOW_TITLE.into(),
display: Default::default(),
input_enabled: true,
}
}
} |
pub const DEFAULT_SCALE: f64 = 4.0;
pub const DEFAULT_SCREEN_WIDTH: usize = 160; | random_line_split |
svg.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/. */
//! Generic types for CSS values in SVG
use cssparser::Parser;
use parser::{Parse, ParserContext};
use style_traits::{ParseError, StyleParseErrorKind};
use values::{Either, None_};
use values::computed::NumberOrPercentage;
use values::computed::length::LengthOrPercentage;
use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// An SVG paint value
///
/// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint>
#[animation(no_bound(UrlPaintServer))]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue,
ToComputedValue, ToCss)]
pub struct SVGPaint<ColorType, UrlPaintServer> { | /// The paint source
pub kind: SVGPaintKind<ColorType, UrlPaintServer>,
/// The fallback color. It would be empty, the `none` keyword or <color>.
pub fallback: Option<Either<ColorType, None_>>,
}
/// An SVG paint value without the fallback
///
/// Whereas the spec only allows PaintServer
/// to have a fallback, Gecko lets the context
/// properties have a fallback as well.
#[animation(no_bound(UrlPaintServer))]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue,
ToAnimatedZero, ToComputedValue, ToCss)]
pub enum SVGPaintKind<ColorType, UrlPaintServer> {
/// `none`
#[animation(error)]
None,
/// `<color>`
Color(ColorType),
/// `url(...)`
#[animation(error)]
PaintServer(UrlPaintServer),
/// `context-fill`
ContextFill,
/// `context-stroke`
ContextStroke,
}
impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> {
/// Parse a keyword value only
fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
try_match_ident_ignore_ascii_case! { input,
"none" => Ok(SVGPaintKind::None),
"context-fill" => Ok(SVGPaintKind::ContextFill),
"context-stroke" => Ok(SVGPaintKind::ContextStroke),
}
}
}
/// Parse SVGPaint's fallback.
/// fallback is keyword(none), Color or empty.
/// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint>
fn parse_fallback<'i, 't, ColorType: Parse>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Option<Either<ColorType, None_>> {
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
Some(Either::Second(None_))
} else {
if let Ok(color) = input.try(|i| ColorType::parse(context, i)) {
Some(Either::First(color))
} else {
None
}
}
}
impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) {
Ok(SVGPaint {
kind: SVGPaintKind::PaintServer(url),
fallback: parse_fallback(context, input),
})
} else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) {
if let SVGPaintKind::None = kind {
Ok(SVGPaint {
kind: kind,
fallback: None,
})
} else {
Ok(SVGPaint {
kind: kind,
fallback: parse_fallback(context, input),
})
}
} else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) {
Ok(SVGPaint {
kind: SVGPaintKind::Color(color),
fallback: None,
})
} else {
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
}
/// A value of <length> | <percentage> | <number> for svg which allow unitless length.
/// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero,
ToComputedValue, ToCss)]
pub enum SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> {
/// <length> | <percentage>
LengthOrPercentage(LengthOrPercentage),
/// <number>
Number(Number),
}
impl<L, N> ComputeSquaredDistance for SvgLengthOrPercentageOrNumber<L, N>
where
L: ComputeSquaredDistance + Copy + Into<NumberOrPercentage>,
N: ComputeSquaredDistance + Copy + Into<NumberOrPercentage>,
{
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
match (self, other) {
(
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref from),
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref to),
) => from.compute_squared_distance(to),
(
&SvgLengthOrPercentageOrNumber::Number(ref from),
&SvgLengthOrPercentageOrNumber::Number(ref to),
) => from.compute_squared_distance(to),
(
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(from),
&SvgLengthOrPercentageOrNumber::Number(to),
) => from.into().compute_squared_distance(&to.into()),
(
&SvgLengthOrPercentageOrNumber::Number(from),
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(to),
) => from.into().compute_squared_distance(&to.into()),
}
}
}
impl<LengthOrPercentageType, NumberType>
SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType>
where
LengthOrPercentage: From<LengthOrPercentageType>,
LengthOrPercentageType: Copy,
{
/// return true if this struct has calc value.
pub fn has_calc(&self) -> bool {
match self {
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => {
match LengthOrPercentage::from(lop) {
LengthOrPercentage::Calc(_) => true,
_ => false,
}
},
_ => false,
}
}
}
/// Parsing the SvgLengthOrPercentageOrNumber. At first, we need to parse number
/// since prevent converting to the length.
impl<LengthOrPercentageType: Parse, NumberType: Parse> Parse
for SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType>
{
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if let Ok(num) = input.try(|i| NumberType::parse(context, i)) {
return Ok(SvgLengthOrPercentageOrNumber::Number(num));
}
if let Ok(lop) = input.try(|i| LengthOrPercentageType::parse(context, i)) {
return Ok(SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop));
}
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
/// An SVG length value supports `context-value` in addition to length.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue,
ToAnimatedZero, ToComputedValue, ToCss)]
pub enum SVGLength<LengthType> {
/// `<length> | <percentage> | <number>`
Length(LengthType),
/// `context-value`
ContextValue,
}
/// Generic value for stroke-dasharray.
#[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue,
ToComputedValue, ToCss)]
pub enum SVGStrokeDashArray<LengthType> {
/// `[ <length> | <percentage> | <number> ]#`
#[css(comma)]
Values(
#[css(if_empty = "none", iterable)]
#[distance(field_bound)]
Vec<LengthType>,
),
/// `context-value`
ContextValue,
}
/// An SVG opacity value accepts `context-{fill,stroke}-opacity` in
/// addition to opacity value.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedZero,
ToComputedValue, ToCss)]
pub enum SVGOpacity<OpacityType> {
/// `<opacity-value>`
Opacity(OpacityType),
/// `context-fill-opacity`
ContextFillOpacity,
/// `context-stroke-opacity`
ContextStrokeOpacity,
} | random_line_split |
|
svg.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/. */
//! Generic types for CSS values in SVG
use cssparser::Parser;
use parser::{Parse, ParserContext};
use style_traits::{ParseError, StyleParseErrorKind};
use values::{Either, None_};
use values::computed::NumberOrPercentage;
use values::computed::length::LengthOrPercentage;
use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// An SVG paint value
///
/// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint>
#[animation(no_bound(UrlPaintServer))]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue,
ToComputedValue, ToCss)]
pub struct SVGPaint<ColorType, UrlPaintServer> {
/// The paint source
pub kind: SVGPaintKind<ColorType, UrlPaintServer>,
/// The fallback color. It would be empty, the `none` keyword or <color>.
pub fallback: Option<Either<ColorType, None_>>,
}
/// An SVG paint value without the fallback
///
/// Whereas the spec only allows PaintServer
/// to have a fallback, Gecko lets the context
/// properties have a fallback as well.
#[animation(no_bound(UrlPaintServer))]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue,
ToAnimatedZero, ToComputedValue, ToCss)]
pub enum SVGPaintKind<ColorType, UrlPaintServer> {
/// `none`
#[animation(error)]
None,
/// `<color>`
Color(ColorType),
/// `url(...)`
#[animation(error)]
PaintServer(UrlPaintServer),
/// `context-fill`
ContextFill,
/// `context-stroke`
ContextStroke,
}
impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> {
/// Parse a keyword value only
fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
try_match_ident_ignore_ascii_case! { input,
"none" => Ok(SVGPaintKind::None),
"context-fill" => Ok(SVGPaintKind::ContextFill),
"context-stroke" => Ok(SVGPaintKind::ContextStroke),
}
}
}
/// Parse SVGPaint's fallback.
/// fallback is keyword(none), Color or empty.
/// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint>
fn parse_fallback<'i, 't, ColorType: Parse>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Option<Either<ColorType, None_>> {
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
Some(Either::Second(None_))
} else {
if let Ok(color) = input.try(|i| ColorType::parse(context, i)) {
Some(Either::First(color))
} else {
None
}
}
}
impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) {
Ok(SVGPaint {
kind: SVGPaintKind::PaintServer(url),
fallback: parse_fallback(context, input),
})
} else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) {
if let SVGPaintKind::None = kind {
Ok(SVGPaint {
kind: kind,
fallback: None,
})
} else {
Ok(SVGPaint {
kind: kind,
fallback: parse_fallback(context, input),
})
}
} else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) {
Ok(SVGPaint {
kind: SVGPaintKind::Color(color),
fallback: None,
})
} else {
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
}
/// A value of <length> | <percentage> | <number> for svg which allow unitless length.
/// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero,
ToComputedValue, ToCss)]
pub enum SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> {
/// <length> | <percentage>
LengthOrPercentage(LengthOrPercentage),
/// <number>
Number(Number),
}
impl<L, N> ComputeSquaredDistance for SvgLengthOrPercentageOrNumber<L, N>
where
L: ComputeSquaredDistance + Copy + Into<NumberOrPercentage>,
N: ComputeSquaredDistance + Copy + Into<NumberOrPercentage>,
{
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
match (self, other) {
(
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref from),
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref to),
) => from.compute_squared_distance(to),
(
&SvgLengthOrPercentageOrNumber::Number(ref from),
&SvgLengthOrPercentageOrNumber::Number(ref to),
) => from.compute_squared_distance(to),
(
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(from),
&SvgLengthOrPercentageOrNumber::Number(to),
) => from.into().compute_squared_distance(&to.into()),
(
&SvgLengthOrPercentageOrNumber::Number(from),
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(to),
) => from.into().compute_squared_distance(&to.into()),
}
}
}
impl<LengthOrPercentageType, NumberType>
SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType>
where
LengthOrPercentage: From<LengthOrPercentageType>,
LengthOrPercentageType: Copy,
{
/// return true if this struct has calc value.
pub fn has_calc(&self) -> bool {
match self {
&SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => {
match LengthOrPercentage::from(lop) {
LengthOrPercentage::Calc(_) => true,
_ => false,
}
},
_ => false,
}
}
}
/// Parsing the SvgLengthOrPercentageOrNumber. At first, we need to parse number
/// since prevent converting to the length.
impl<LengthOrPercentageType: Parse, NumberType: Parse> Parse
for SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType>
{
fn | <'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if let Ok(num) = input.try(|i| NumberType::parse(context, i)) {
return Ok(SvgLengthOrPercentageOrNumber::Number(num));
}
if let Ok(lop) = input.try(|i| LengthOrPercentageType::parse(context, i)) {
return Ok(SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop));
}
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
/// An SVG length value supports `context-value` in addition to length.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue,
ToAnimatedZero, ToComputedValue, ToCss)]
pub enum SVGLength<LengthType> {
/// `<length> | <percentage> | <number>`
Length(LengthType),
/// `context-value`
ContextValue,
}
/// Generic value for stroke-dasharray.
#[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue,
ToComputedValue, ToCss)]
pub enum SVGStrokeDashArray<LengthType> {
/// `[ <length> | <percentage> | <number> ]#`
#[css(comma)]
Values(
#[css(if_empty = "none", iterable)]
#[distance(field_bound)]
Vec<LengthType>,
),
/// `context-value`
ContextValue,
}
/// An SVG opacity value accepts `context-{fill,stroke}-opacity` in
/// addition to opacity value.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedZero,
ToComputedValue, ToCss)]
pub enum SVGOpacity<OpacityType> {
/// `<opacity-value>`
Opacity(OpacityType),
/// `context-fill-opacity`
ContextFillOpacity,
/// `context-stroke-opacity`
ContextStrokeOpacity,
}
| parse | identifier_name |
issue-14182.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | // ignore-test FIXME(japari) remove test
struct Foo {
f: for <'b> |&'b isize|:
'b -> &'b isize //~ ERROR use of undeclared lifetime name `'b`
}
fn main() {
let mut x: Vec< for <'a> ||
:'a //~ ERROR use of undeclared lifetime name `'a`
> = Vec::new();
x.push(|| {});
let foo = Foo {
f: |x| x
};
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z parse-only
| random_line_split |
issue-14182.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z parse-only
// ignore-test FIXME(japari) remove test
struct Foo {
f: for <'b> |&'b isize|:
'b -> &'b isize //~ ERROR use of undeclared lifetime name `'b`
}
fn | () {
let mut x: Vec< for <'a> ||
:'a //~ ERROR use of undeclared lifetime name `'a`
> = Vec::new();
x.push(|| {});
let foo = Foo {
f: |x| x
};
}
| main | identifier_name |
issue-14182.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z parse-only
// ignore-test FIXME(japari) remove test
struct Foo {
f: for <'b> |&'b isize|:
'b -> &'b isize //~ ERROR use of undeclared lifetime name `'b`
}
fn main() | {
let mut x: Vec< for <'a> ||
:'a //~ ERROR use of undeclared lifetime name `'a`
> = Vec::new();
x.push(|| {});
let foo = Foo {
f: |x| x
};
} | identifier_body |
|
gash.rs | //
// gash.rs
//
// Reference solution for PS2
// Running on Rust 0.8
//
// Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8.
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu, Purnam Jantrania, David Evans
// Version 0.2
//
// Modified
use std::{run, os, libc};
use std::task;
fn get_fd(fpath: &str, mode: &str) -> libc::c_int {
#[fixed_stack_segment]; #[inline(never)];
unsafe {
let fpathbuf = fpath.to_c_str().unwrap();
let modebuf = mode.to_c_str().unwrap();
return libc::fileno(libc::fopen(fpathbuf, modebuf));
}
}
fn exit(status: libc::c_int) {
#[fixed_stack_segment]; #[inline(never)];
unsafe { libc::exit(status); }
}
fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int,
pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> {
let out_fd = pipe_out;
let in_fd = pipe_in;
let err_fd = pipe_err;
let mut argv: ~[~str] =
cmd_line.split_iter(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
let program = argv.remove(0);
let (out_opt, err_opt) = if output { (None, None) } else { (Some(out_fd), Some(err_fd))};
let mut prog = run::Process::new(program, argv, run::ProcessOptions {
env: None,
dir: None,
in_fd: Some(in_fd),
out_fd: out_opt,
err_fd: err_opt
});
let output_opt = if output { Some(prog.finish_with_output()) }
else { prog.finish(); None };
// close the pipes after process terminates.
if in_fd!= 0 {os::close(in_fd);}
if out_fd!= 1 {os::close(out_fd);}
if err_fd!= 2 {os::close(err_fd);}
return output_opt;
}
return None;
}
fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) {
_handle_cmd(cmd_line, pipe_in, pipe_out, pipe_err, false);
}
fn handle_cmd_with_output(cmd_line: &str, pipe_in: libc::c_int) -> Option<run::ProcessOutput> {
return _handle_cmd(cmd_line, pipe_in, -1, -1, true);
}
pub fn handle_cmdline(cmd_line: &str) -> Option<run::ProcessOutput> {
// handle pipes
let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect();
let mut pipes = ~[];
for _ in range(0, progs.len()-1) {
pipes.push(os::pipe());
}
if progs.len() == 1 {
return handle_cmd_with_output(progs[0], 0);
} else |
} | {
let mut output_opt = None;
for i in range(0, progs.len()) {
let prog = progs[i].to_owned();
if i == 0 {
let pipe_i = pipes[i];
task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)});
} else if i == progs.len() - 1 {
let pipe_i_1 = pipes[i-1];
output_opt = handle_cmd_with_output(prog, pipe_i_1.input);
} else {
let pipe_i = pipes[i];
let pipe_i_1 = pipes[i-1];
task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)});
}
}
return output_opt;
} | conditional_block |
gash.rs | //
// gash.rs
//
// Reference solution for PS2
// Running on Rust 0.8
//
// Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8.
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu, Purnam Jantrania, David Evans
// Version 0.2
//
// Modified
use std::{run, os, libc};
use std::task;
fn get_fd(fpath: &str, mode: &str) -> libc::c_int {
#[fixed_stack_segment]; #[inline(never)];
unsafe {
let fpathbuf = fpath.to_c_str().unwrap();
let modebuf = mode.to_c_str().unwrap();
return libc::fileno(libc::fopen(fpathbuf, modebuf));
}
}
fn exit(status: libc::c_int) |
fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int,
pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> {
let out_fd = pipe_out;
let in_fd = pipe_in;
let err_fd = pipe_err;
let mut argv: ~[~str] =
cmd_line.split_iter(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
let program = argv.remove(0);
let (out_opt, err_opt) = if output { (None, None) } else { (Some(out_fd), Some(err_fd))};
let mut prog = run::Process::new(program, argv, run::ProcessOptions {
env: None,
dir: None,
in_fd: Some(in_fd),
out_fd: out_opt,
err_fd: err_opt
});
let output_opt = if output { Some(prog.finish_with_output()) }
else { prog.finish(); None };
// close the pipes after process terminates.
if in_fd!= 0 {os::close(in_fd);}
if out_fd!= 1 {os::close(out_fd);}
if err_fd!= 2 {os::close(err_fd);}
return output_opt;
}
return None;
}
fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) {
_handle_cmd(cmd_line, pipe_in, pipe_out, pipe_err, false);
}
fn handle_cmd_with_output(cmd_line: &str, pipe_in: libc::c_int) -> Option<run::ProcessOutput> {
return _handle_cmd(cmd_line, pipe_in, -1, -1, true);
}
pub fn handle_cmdline(cmd_line: &str) -> Option<run::ProcessOutput> {
// handle pipes
let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect();
let mut pipes = ~[];
for _ in range(0, progs.len()-1) {
pipes.push(os::pipe());
}
if progs.len() == 1 {
return handle_cmd_with_output(progs[0], 0);
} else {
let mut output_opt = None;
for i in range(0, progs.len()) {
let prog = progs[i].to_owned();
if i == 0 {
let pipe_i = pipes[i];
task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)});
} else if i == progs.len() - 1 {
let pipe_i_1 = pipes[i-1];
output_opt = handle_cmd_with_output(prog, pipe_i_1.input);
} else {
let pipe_i = pipes[i];
let pipe_i_1 = pipes[i-1];
task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)});
}
}
return output_opt;
}
} | {
#[fixed_stack_segment]; #[inline(never)];
unsafe { libc::exit(status); }
} | identifier_body |
gash.rs | //
// gash.rs
//
// Reference solution for PS2
// Running on Rust 0.8
//
// Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8.
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu, Purnam Jantrania, David Evans
// Version 0.2
//
// Modified
use std::{run, os, libc};
use std::task;
fn get_fd(fpath: &str, mode: &str) -> libc::c_int {
#[fixed_stack_segment]; #[inline(never)];
unsafe {
let fpathbuf = fpath.to_c_str().unwrap();
let modebuf = mode.to_c_str().unwrap();
return libc::fileno(libc::fopen(fpathbuf, modebuf));
}
}
fn exit(status: libc::c_int) {
#[fixed_stack_segment]; #[inline(never)];
unsafe { libc::exit(status); }
}
fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int,
pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> {
let out_fd = pipe_out;
let in_fd = pipe_in;
let err_fd = pipe_err;
let mut argv: ~[~str] =
cmd_line.split_iter(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
let program = argv.remove(0);
let (out_opt, err_opt) = if output { (None, None) } else { (Some(out_fd), Some(err_fd))};
let mut prog = run::Process::new(program, argv, run::ProcessOptions {
env: None,
dir: None,
in_fd: Some(in_fd),
out_fd: out_opt,
err_fd: err_opt
});
let output_opt = if output { Some(prog.finish_with_output()) }
else { prog.finish(); None };
// close the pipes after process terminates.
if in_fd!= 0 {os::close(in_fd);}
if out_fd!= 1 {os::close(out_fd);}
if err_fd!= 2 {os::close(err_fd);}
return output_opt;
}
return None;
}
fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) {
_handle_cmd(cmd_line, pipe_in, pipe_out, pipe_err, false);
}
fn handle_cmd_with_output(cmd_line: &str, pipe_in: libc::c_int) -> Option<run::ProcessOutput> {
return _handle_cmd(cmd_line, pipe_in, -1, -1, true);
}
pub fn | (cmd_line: &str) -> Option<run::ProcessOutput> {
// handle pipes
let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect();
let mut pipes = ~[];
for _ in range(0, progs.len()-1) {
pipes.push(os::pipe());
}
if progs.len() == 1 {
return handle_cmd_with_output(progs[0], 0);
} else {
let mut output_opt = None;
for i in range(0, progs.len()) {
let prog = progs[i].to_owned();
if i == 0 {
let pipe_i = pipes[i];
task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)});
} else if i == progs.len() - 1 {
let pipe_i_1 = pipes[i-1];
output_opt = handle_cmd_with_output(prog, pipe_i_1.input);
} else {
let pipe_i = pipes[i];
let pipe_i_1 = pipes[i-1];
task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)});
}
}
return output_opt;
}
} | handle_cmdline | identifier_name |
gash.rs | //
// gash.rs
//
// Reference solution for PS2
// Running on Rust 0.8
//
// Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8.
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu, Purnam Jantrania, David Evans
// Version 0.2
//
// Modified
use std::{run, os, libc};
use std::task;
fn get_fd(fpath: &str, mode: &str) -> libc::c_int {
#[fixed_stack_segment]; #[inline(never)];
unsafe {
let fpathbuf = fpath.to_c_str().unwrap(); | }
fn exit(status: libc::c_int) {
#[fixed_stack_segment]; #[inline(never)];
unsafe { libc::exit(status); }
}
fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int,
pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> {
let out_fd = pipe_out;
let in_fd = pipe_in;
let err_fd = pipe_err;
let mut argv: ~[~str] =
cmd_line.split_iter(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
let program = argv.remove(0);
let (out_opt, err_opt) = if output { (None, None) } else { (Some(out_fd), Some(err_fd))};
let mut prog = run::Process::new(program, argv, run::ProcessOptions {
env: None,
dir: None,
in_fd: Some(in_fd),
out_fd: out_opt,
err_fd: err_opt
});
let output_opt = if output { Some(prog.finish_with_output()) }
else { prog.finish(); None };
// close the pipes after process terminates.
if in_fd!= 0 {os::close(in_fd);}
if out_fd!= 1 {os::close(out_fd);}
if err_fd!= 2 {os::close(err_fd);}
return output_opt;
}
return None;
}
fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) {
_handle_cmd(cmd_line, pipe_in, pipe_out, pipe_err, false);
}
fn handle_cmd_with_output(cmd_line: &str, pipe_in: libc::c_int) -> Option<run::ProcessOutput> {
return _handle_cmd(cmd_line, pipe_in, -1, -1, true);
}
pub fn handle_cmdline(cmd_line: &str) -> Option<run::ProcessOutput> {
// handle pipes
let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect();
let mut pipes = ~[];
for _ in range(0, progs.len()-1) {
pipes.push(os::pipe());
}
if progs.len() == 1 {
return handle_cmd_with_output(progs[0], 0);
} else {
let mut output_opt = None;
for i in range(0, progs.len()) {
let prog = progs[i].to_owned();
if i == 0 {
let pipe_i = pipes[i];
task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)});
} else if i == progs.len() - 1 {
let pipe_i_1 = pipes[i-1];
output_opt = handle_cmd_with_output(prog, pipe_i_1.input);
} else {
let pipe_i = pipes[i];
let pipe_i_1 = pipes[i-1];
task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)});
}
}
return output_opt;
}
} | let modebuf = mode.to_c_str().unwrap();
return libc::fileno(libc::fopen(fpathbuf, modebuf));
} | random_line_split |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// ignore-lexer-test FIXME #15679
//! This crate provides a native implementation of regular expressions that is
//! heavily based on RE2 both in syntax and in implementation. Notably,
//! backreferences and arbitrary lookahead/lookbehind assertions are not
//! provided. In return, regular expression searching provided by this package
//! has excellent worst case performance. The specific syntax supported is
//! documented further down.
//!
//! This crate's documentation provides some simple examples, describes Unicode
//! support and exhaustively lists the supported syntax. For more specific
//! details on the API, please see the documentation for the `Regex` type.
//!
//! # First example: find a date
//!
//! General use of regular expressions in this package involves compiling an
//! expression and then using it to search, split or replace text. For example,
//! to confirm that some text resembles a date:
//!
//! ```rust
//! use regex::Regex;
//! let re = match Regex::new(r"^\d{4}-\d{2}-\d{2}$") {
//! Ok(re) => re,
//! Err(err) => fail!("{}", err),
//! };
//! assert_eq!(re.is_match("2014-01-01"), true);
//! ```
//!
//! Notice the use of the `^` and `$` anchors. In this crate, every expression
//! is executed with an implicit `.*?` at the beginning and end, which allows
//! it to match anywhere in the text. Anchors can be used to ensure that the
//! full text matches an expression.
//!
//! This example also demonstrates the utility of raw strings in Rust, which
//! are just like regular strings except they are prefixed with an `r` and do
//! not process any escape sequences. For example, `"\\d"` is the same
//! expression as `r"\d"`.
//!
//! # The `regex!` macro
//!
//! Rust's compile time meta-programming facilities provide a way to write a
//! `regex!` macro which compiles regular expressions *when your program
//! compiles*. Said differently, if you only use `regex!` to build regular
//! expressions in your program, then your program cannot compile with an
//! invalid regular expression. Moreover, the `regex!` macro compiles the
//! given expression to native Rust code, which makes it much faster for
//! searching text.
//!
//! Since `regex!` provides compiled regular expressions that are both safer
//! and faster to use, you should use them whenever possible. The only
//! requirement for using them is that you have a string literal corresponding
//! to your expression. Otherwise, it is indistinguishable from an expression
//! compiled at runtime with `Regex::new`.
//!
//! To use the `regex!` macro, you must enable the `phase` feature and import
//! the `regex_macros` crate as a syntax extension:
//!
//! ```rust
//! #![feature(phase)]
//! #[phase(plugin)]
//! extern crate regex_macros;
//! extern crate regex;
//!
//! fn main() {
//! let re = regex!(r"^\d{4}-\d{2}-\d{2}$");
//! assert_eq!(re.is_match("2014-01-01"), true);
//! }
//! ```
//!
//! There are a few things worth mentioning about using the `regex!` macro.
//! Firstly, the `regex!` macro *only* accepts string *literals*.
//! Secondly, the `regex` crate *must* be linked with the name `regex` since
//! the generated code depends on finding symbols in the `regex` crate.
//!
//! The only downside of using the `regex!` macro is that it can increase the
//! size of your program's binary since it generates specialized Rust code.
//! The extra size probably won't be significant for a small number of
//! expressions, but 100+ calls to `regex!` will probably result in a
//! noticeably bigger binary.
//!
//! # Example: iterating over capture groups
//!
//! This crate provides convenient iterators for matching an expression
//! repeatedly against a search string to find successive non-overlapping
//! matches. For example, to find all dates in a string and be able to access
//! them by their component pieces:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"(\d{4})-(\d{2})-(\d{2})");
//! let text = "2012-03-14, 2013-01-01 and 2014-07-05";
//! for cap in re.captures_iter(text) {
//! println!("Month: {} Day: {} Year: {}", cap.at(2), cap.at(3), cap.at(1));
//! }
//! // Output:
//! // Month: 03 Day: 14 Year: 2012
//! // Month: 01 Day: 01 Year: 2013
//! // Month: 07 Day: 05 Year: 2014
//! # }
//! ```
//!
//! Notice that the year is in the capture group indexed at `1`. This is
//! because the *entire match* is stored in the capture group at index `0`.
//!
//! # Example: replacement with named capture groups
//!
//! Building on the previous example, perhaps we'd like to rearrange the date
//! formats. This can be done with text replacement. But to make the code
//! clearer, we can *name* our capture groups and use those names as variables
//! in our replacement text:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})");
//! let before = "2012-03-14, 2013-01-01 and 2014-07-05";
//! let after = re.replace_all(before, "$m/$d/$y");
//! assert_eq!(after.as_slice(), "03/14/2012, 01/01/2013 and 07/05/2014");
//! # }
//! ```
//!
//! The `replace` methods are actually polymorphic in the replacement, which
//! provides more flexibility than is seen here. (See the documentation for
//! `Regex::replace` for more details.)
//!
//! # Pay for what you use
//!
//! With respect to searching text with a regular expression, there are three
//! questions that can be asked:
//!
//! 1. Does the text match this expression?
//! 2. If so, where does it match?
//! 3. Where are the submatches?
//!
//! Generally speaking, this crate could provide a function to answer only #3,
//! which would subsume #1 and #2 automatically. However, it can be
//! significantly more expensive to compute the location of submatches, so it's
//! best not to do it if you don't need to.
//!
//! Therefore, only use what you need. For example, don't use `find` if you
//! only need to test if an expression matches a string. (Use `is_match`
//! instead.)
//!
//! # Unicode | //! This implementation executes regular expressions **only** on sequences of
//! Unicode code points while exposing match locations as byte indices into the
//! search string.
//!
//! Currently, only naive case folding is supported. Namely, when matching
//! case insensitively, the characters are first converted to their uppercase
//! forms and then compared.
//!
//! Regular expressions themselves are also **only** interpreted as a sequence
//! of Unicode code points. This means you can use Unicode characters
//! directly in your expression:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"(?i)Δ+");
//! assert_eq!(re.find("ΔδΔ"), Some((0, 6)));
//! # }
//! ```
//!
//! Finally, Unicode general categories and scripts are available as character
//! classes. For example, you can match a sequence of numerals, Greek or
//! Cherokee letters:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"[\pN\p{Greek}\p{Cherokee}]+");
//! assert_eq!(re.find("abcΔᎠβⅠᏴγδⅡxyz"), Some((3, 23)));
//! # }
//! ```
//!
//! # Syntax
//!
//! The syntax supported in this crate is almost in an exact correspondence
//! with the syntax supported by RE2.
//!
//! ## Matching one character
//!
//! <pre class="rust">
//!. any character except new line (includes new line with s flag)
//! [xyz] A character class matching either x, y or z.
//! [^xyz] A character class matching any character except x, y and z.
//! [a-z] A character class matching any character in range a-z.
//! \d Perl character class ([0-9])
//! \D Negated Perl character class ([^0-9])
//! [:alpha:] ASCII character class ([A-Za-z])
//! [:^alpha:] Negated ASCII character class ([^A-Za-z])
//! \pN One letter name Unicode character class
//! \p{Greek} Unicode character class (general category or script)
//! \PN Negated one letter name Unicode character class
//! \P{Greek} negated Unicode character class (general category or script)
//! </pre>
//!
//! Any named character class may appear inside a bracketed `[...]` character
//! class. For example, `[\p{Greek}\pN]` matches any Greek or numeral
//! character.
//!
//! ## Composites
//!
//! <pre class="rust">
//! xy concatenation (x followed by y)
//! x|y alternation (x or y, prefer x)
//! </pre>
//!
//! ## Repetitions
//!
//! <pre class="rust">
//! x* zero or more of x (greedy)
//! x+ one or more of x (greedy)
//! x? zero or one of x (greedy)
//! x*? zero or more of x (ungreedy)
//! x+? one or more of x (ungreedy)
//! x?? zero or one of x (ungreedy)
//! x{n,m} at least n x and at most m x (greedy)
//! x{n,} at least n x (greedy)
//! x{n} exactly n x
//! x{n,m}? at least n x and at most m x (ungreedy)
//! x{n,}? at least n x (ungreedy)
//! x{n}? exactly n x
//! </pre>
//!
//! ## Empty matches
//!
//! <pre class="rust">
//! ^ the beginning of text (or start-of-line with multi-line mode)
//! $ the end of text (or end-of-line with multi-line mode)
//! \A only the beginning of text (even with multi-line mode enabled)
//! \z only the end of text (even with multi-line mode enabled)
//! \b a Unicode word boundary (\w on one side and \W, \A, or \z on other)
//! \B not a Unicode word boundary
//! </pre>
//!
//! ## Grouping and flags
//!
//! <pre class="rust">
//! (exp) numbered capture group (indexed by opening parenthesis)
//! (?P<name>exp) named (also numbered) capture group (allowed chars: [_0-9a-zA-Z])
//! (?:exp) non-capturing group
//! (?flags) set flags within current group
//! (?flags:exp) set flags for exp (non-capturing)
//! </pre>
//!
//! Flags are each a single character. For example, `(?x)` sets the flag `x`
//! and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at
//! the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets
//! the `x` flag and clears the `y` flag.
//!
//! All flags are by default disabled. They are:
//!
//! <pre class="rust">
//! i case insensitive
//! m multi-line mode: ^ and $ match begin/end of line
//! s allow. to match \n
//! U swap the meaning of x* and x*?
//! </pre>
//!
//! Here's an example that matches case insensitively for only part of the
//! expression:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"(?i)a+(?-i)b+");
//! let cap = re.captures("AaAaAbbBBBb").unwrap();
//! assert_eq!(cap.at(0), "AaAaAbb");
//! # }
//! ```
//!
//! Notice that the `a+` matches either `a` or `A`, but the `b+` only matches
//! `b`.
//!
//! ## Escape sequences
//!
//! <pre class="rust">
//! \* literal *, works for any punctuation character: \.+*?()|[]{}^$
//! \a bell (\x07)
//! \f form feed (\x0C)
//! \t horizontal tab
//! \n new line
//! \r carriage return
//! \v vertical tab (\x0B)
//! \123 octal character code (up to three digits)
//! \x7F hex character code (exactly two digits)
//! \x{10FFFF} any hex character code corresponding to a Unicode code point
//! </pre>
//!
//! ## Perl character classes (Unicode friendly)
//!
//! These classes are based on the definitions provided in
//! [UTS#18](http://www.unicode.org/reports/tr18/#Compatibility_Properties):
//!
//! <pre class="rust">
//! \d digit (\p{Nd})
//! \D not digit
//! \s whitespace (\p{White_Space})
//! \S not whitespace
//! \w word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control})
//! \W not word character
//! </pre>
//!
//! ## ASCII character classes
//!
//! <pre class="rust">
//! [:alnum:] alphanumeric ([0-9A-Za-z])
//! [:alpha:] alphabetic ([A-Za-z])
//! [:ascii:] ASCII ([\x00-\x7F])
//! [:blank:] blank ([\t ])
//! [:cntrl:] control ([\x00-\x1F\x7F])
//! [:digit:] digits ([0-9])
//! [:graph:] graphical ([!-~])
//! [:lower:] lower case ([a-z])
//! [:print:] printable ([ -~])
//! [:punct:] punctuation ([!-/:-@[-`{-~])
//! [:space:] whitespace ([\t\n\v\f\r ])
//! [:upper:] upper case ([A-Z])
//! [:word:] word characters ([0-9A-Za-z_])
//! [:xdigit:] hex digit ([0-9A-Fa-f])
//! </pre>
//!
//! # Untrusted input
//!
//! There are two factors to consider here: untrusted regular expressions and
//! untrusted search text.
//!
//! Currently, there are no counter-measures in place to prevent a malicious
//! user from writing an expression that may use a lot of resources. One such
//! example is to repeat counted repetitions: `((a{100}){100}){100}` will try
//! to repeat the `a` instruction `100^3` times. Essentially, this means it's
//! very easy for an attacker to exhaust your system's memory if they are
//! allowed to execute arbitrary regular expressions. A possible solution to
//! this is to impose a hard limit on the size of a compiled expression, but it
//! does not yet exist.
//!
//! The story is a bit better with untrusted search text, since this crate's
//! implementation provides `O(nm)` search where `n` is the number of
//! characters in the search text and `m` is the number of instructions in a
//! compiled expression.
#![crate_name = "regex"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![experimental]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
#[cfg(test)]
extern crate stdtest = "test";
#[cfg(test)]
extern crate rand;
// During tests, this links with the `regex` crate so that the `regex!` macro
// can be tested.
#[cfg(test)]
extern crate regex;
// unicode tables for character classes are defined in libunicode
extern crate unicode;
pub use parse::Error;
pub use re::{Regex, Captures, SubCaptures, SubCapturesPos};
pub use re::{FindCaptures, FindMatches};
pub use re::{Replacer, NoExpand, RegexSplits, RegexSplitsN};
pub use re::{quote, is_match};
mod compile;
mod parse;
mod re;
mod vm;
#[cfg(test)]
mod test;
/// The `native` module exists to support the `regex!` macro. Do not use.
#[doc(hidden)]
pub mod native {
// Exporting this stuff is bad form, but it's necessary for two reasons.
// Firstly, the `regex!` syntax extension is in a different crate and
// requires access to the representation of a regex (particularly the
// instruction set) in order to compile to native Rust. This could be
// mitigated if `regex!` was defined in the same crate, but this has
// undesirable consequences (such as requiring a dependency on
// `libsyntax`).
//
// Secondly, the code generated by `regex!` must *also* be able
// to access various functions in this crate to reduce code duplication
// and to provide a value with precisely the same `Regex` type in this
// crate. This, AFAIK, is impossible to mitigate.
//
// On the bright side, `rustdoc` lets us hide this from the public API
// documentation.
pub use compile::{
Program,
OneChar, CharClass, Any, Save, Jump, Split,
Match, EmptyBegin, EmptyEnd, EmptyWordBoundary,
};
pub use parse::{
FLAG_EMPTY, FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL,
FLAG_SWAP_GREED, FLAG_NEGATED,
};
pub use re::{Dynamic, Native};
pub use vm::{
MatchKind, Exists, Location, Submatches,
StepState, StepMatchEarlyReturn, StepMatch, StepContinue,
CharReader, find_prefix,
};
} | //! | random_line_split |
gamepad.rs | //! Gamepad utility functions.
//!
//! This is going to be a bit of a work-in-progress as gamepad input
//! gets fleshed out. The `gilrs` crate needs help to add better
//! cross-platform support. Why not give it a hand?
use gilrs::ConnectedGamepadsIterator;
use std::fmt;
pub use gilrs::{self, Event, Gamepad, Gilrs};
/// A unique identifier for a particular GamePad
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct GamepadId(pub(crate) gilrs::GamepadId);
use crate::context::Context;
use crate::error::GameResult;
/// Trait object defining a gamepad/joystick context.
pub trait GamepadContext {
/// Returns a gamepad event.
fn next_event(&mut self) -> Option<Event>;
/// returns the `Gamepad` associated with an id.
fn gamepad(&self, id: GamepadId) -> Gamepad;
/// returns an iterator over the connected `Gamepad`s.
fn gamepads(&self) -> GamepadsIterator;
}
/// A structure that contains gamepad state using `gilrs`.
pub struct GilrsGamepadContext {
pub(crate) gilrs: Gilrs,
}
impl fmt::Debug for GilrsGamepadContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<GilrsGamepadContext: {:p}>", self)
}
}
impl GilrsGamepadContext {
pub(crate) fn new() -> GameResult<Self> {
let gilrs = Gilrs::new()?;
Ok(GilrsGamepadContext { gilrs })
}
}
impl From<Gilrs> for GilrsGamepadContext {
/// Converts from a `Gilrs` custom instance to a `GilrsGamepadContext`
fn from(gilrs: Gilrs) -> Self {
Self { gilrs }
}
}
impl GamepadContext for GilrsGamepadContext {
fn next_event(&mut self) -> Option<Event> {
self.gilrs.next_event()
}
fn gamepad(&self, id: GamepadId) -> Gamepad {
self.gilrs.gamepad(id.0)
}
fn gamepads(&self) -> GamepadsIterator {
GamepadsIterator {
wrapped: self.gilrs.gamepads(),
}
}
}
/// An iterator of the connected gamepads
pub struct GamepadsIterator<'a> {
wrapped: ConnectedGamepadsIterator<'a>,
}
impl<'a> fmt::Debug for GamepadsIterator<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<GamepadsIterator: {:p}>", self) | }
}
impl<'a> Iterator for GamepadsIterator<'a> {
type Item = (GamepadId, Gamepad<'a>);
fn next(&mut self) -> Option<(GamepadId, Gamepad<'a>)> {
self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp))
}
}
/// A structure that implements [`GamepadContext`](trait.GamepadContext.html)
/// but does nothing; a stub for when you don't need it or are
/// on a platform that `gilrs` doesn't support.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct NullGamepadContext {}
impl GamepadContext for NullGamepadContext {
fn next_event(&mut self) -> Option<Event> {
panic!("Gamepad module disabled")
}
fn gamepad(&self, _id: GamepadId) -> Gamepad {
panic!("Gamepad module disabled")
}
fn gamepads(&self) -> GamepadsIterator {
panic!("Gamepad module disabled")
}
}
/// Returns the `Gamepad` associated with an `id`.
pub fn gamepad(ctx: &Context, id: GamepadId) -> Gamepad {
ctx.gamepad_context.gamepad(id)
}
/// Return an iterator of all the `Gamepads` that are connected.
pub fn gamepads(ctx: &Context) -> GamepadsIterator {
ctx.gamepad_context.gamepads()
}
// Properties gamepads might want:
// Number of buttons
// Number of axes
// Name/ID
// Is it connected? (For consoles?)
// Whether or not they support vibration
/*
/// Lists all gamepads. With metainfo, maybe?
pub fn list_gamepads() {
unimplemented!()
}
/// Returns the state of the given axis on a gamepad.
pub fn axis() {
unimplemented!()
}
/// Returns the state of the given button on a gamepad.
pub fn button_pressed() {
unimplemented!()
}
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gilrs_init() {
assert!(GilrsGamepadContext::new().is_ok());
}
} | random_line_split |
|
gamepad.rs | //! Gamepad utility functions.
//!
//! This is going to be a bit of a work-in-progress as gamepad input
//! gets fleshed out. The `gilrs` crate needs help to add better
//! cross-platform support. Why not give it a hand?
use gilrs::ConnectedGamepadsIterator;
use std::fmt;
pub use gilrs::{self, Event, Gamepad, Gilrs};
/// A unique identifier for a particular GamePad
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct GamepadId(pub(crate) gilrs::GamepadId);
use crate::context::Context;
use crate::error::GameResult;
/// Trait object defining a gamepad/joystick context.
pub trait GamepadContext {
/// Returns a gamepad event.
fn next_event(&mut self) -> Option<Event>;
/// returns the `Gamepad` associated with an id.
fn gamepad(&self, id: GamepadId) -> Gamepad;
/// returns an iterator over the connected `Gamepad`s.
fn gamepads(&self) -> GamepadsIterator;
}
/// A structure that contains gamepad state using `gilrs`.
pub struct GilrsGamepadContext {
pub(crate) gilrs: Gilrs,
}
impl fmt::Debug for GilrsGamepadContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<GilrsGamepadContext: {:p}>", self)
}
}
impl GilrsGamepadContext {
pub(crate) fn new() -> GameResult<Self> {
let gilrs = Gilrs::new()?;
Ok(GilrsGamepadContext { gilrs })
}
}
impl From<Gilrs> for GilrsGamepadContext {
/// Converts from a `Gilrs` custom instance to a `GilrsGamepadContext`
fn from(gilrs: Gilrs) -> Self {
Self { gilrs }
}
}
impl GamepadContext for GilrsGamepadContext {
fn next_event(&mut self) -> Option<Event> {
self.gilrs.next_event()
}
fn gamepad(&self, id: GamepadId) -> Gamepad {
self.gilrs.gamepad(id.0)
}
fn gamepads(&self) -> GamepadsIterator {
GamepadsIterator {
wrapped: self.gilrs.gamepads(),
}
}
}
/// An iterator of the connected gamepads
pub struct GamepadsIterator<'a> {
wrapped: ConnectedGamepadsIterator<'a>,
}
impl<'a> fmt::Debug for GamepadsIterator<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<GamepadsIterator: {:p}>", self)
}
}
impl<'a> Iterator for GamepadsIterator<'a> {
type Item = (GamepadId, Gamepad<'a>);
fn | (&mut self) -> Option<(GamepadId, Gamepad<'a>)> {
self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp))
}
}
/// A structure that implements [`GamepadContext`](trait.GamepadContext.html)
/// but does nothing; a stub for when you don't need it or are
/// on a platform that `gilrs` doesn't support.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct NullGamepadContext {}
impl GamepadContext for NullGamepadContext {
fn next_event(&mut self) -> Option<Event> {
panic!("Gamepad module disabled")
}
fn gamepad(&self, _id: GamepadId) -> Gamepad {
panic!("Gamepad module disabled")
}
fn gamepads(&self) -> GamepadsIterator {
panic!("Gamepad module disabled")
}
}
/// Returns the `Gamepad` associated with an `id`.
pub fn gamepad(ctx: &Context, id: GamepadId) -> Gamepad {
ctx.gamepad_context.gamepad(id)
}
/// Return an iterator of all the `Gamepads` that are connected.
pub fn gamepads(ctx: &Context) -> GamepadsIterator {
ctx.gamepad_context.gamepads()
}
// Properties gamepads might want:
// Number of buttons
// Number of axes
// Name/ID
// Is it connected? (For consoles?)
// Whether or not they support vibration
/*
/// Lists all gamepads. With metainfo, maybe?
pub fn list_gamepads() {
unimplemented!()
}
/// Returns the state of the given axis on a gamepad.
pub fn axis() {
unimplemented!()
}
/// Returns the state of the given button on a gamepad.
pub fn button_pressed() {
unimplemented!()
}
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gilrs_init() {
assert!(GilrsGamepadContext::new().is_ok());
}
}
| next | identifier_name |
gamepad.rs | //! Gamepad utility functions.
//!
//! This is going to be a bit of a work-in-progress as gamepad input
//! gets fleshed out. The `gilrs` crate needs help to add better
//! cross-platform support. Why not give it a hand?
use gilrs::ConnectedGamepadsIterator;
use std::fmt;
pub use gilrs::{self, Event, Gamepad, Gilrs};
/// A unique identifier for a particular GamePad
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct GamepadId(pub(crate) gilrs::GamepadId);
use crate::context::Context;
use crate::error::GameResult;
/// Trait object defining a gamepad/joystick context.
pub trait GamepadContext {
/// Returns a gamepad event.
fn next_event(&mut self) -> Option<Event>;
/// returns the `Gamepad` associated with an id.
fn gamepad(&self, id: GamepadId) -> Gamepad;
/// returns an iterator over the connected `Gamepad`s.
fn gamepads(&self) -> GamepadsIterator;
}
/// A structure that contains gamepad state using `gilrs`.
pub struct GilrsGamepadContext {
pub(crate) gilrs: Gilrs,
}
impl fmt::Debug for GilrsGamepadContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<GilrsGamepadContext: {:p}>", self)
}
}
impl GilrsGamepadContext {
pub(crate) fn new() -> GameResult<Self> {
let gilrs = Gilrs::new()?;
Ok(GilrsGamepadContext { gilrs })
}
}
impl From<Gilrs> for GilrsGamepadContext {
/// Converts from a `Gilrs` custom instance to a `GilrsGamepadContext`
fn from(gilrs: Gilrs) -> Self {
Self { gilrs }
}
}
impl GamepadContext for GilrsGamepadContext {
fn next_event(&mut self) -> Option<Event> {
self.gilrs.next_event()
}
fn gamepad(&self, id: GamepadId) -> Gamepad {
self.gilrs.gamepad(id.0)
}
fn gamepads(&self) -> GamepadsIterator {
GamepadsIterator {
wrapped: self.gilrs.gamepads(),
}
}
}
/// An iterator of the connected gamepads
pub struct GamepadsIterator<'a> {
wrapped: ConnectedGamepadsIterator<'a>,
}
impl<'a> fmt::Debug for GamepadsIterator<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<GamepadsIterator: {:p}>", self)
}
}
impl<'a> Iterator for GamepadsIterator<'a> {
type Item = (GamepadId, Gamepad<'a>);
fn next(&mut self) -> Option<(GamepadId, Gamepad<'a>)> {
self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp))
}
}
/// A structure that implements [`GamepadContext`](trait.GamepadContext.html)
/// but does nothing; a stub for when you don't need it or are
/// on a platform that `gilrs` doesn't support.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct NullGamepadContext {}
impl GamepadContext for NullGamepadContext {
fn next_event(&mut self) -> Option<Event> |
fn gamepad(&self, _id: GamepadId) -> Gamepad {
panic!("Gamepad module disabled")
}
fn gamepads(&self) -> GamepadsIterator {
panic!("Gamepad module disabled")
}
}
/// Returns the `Gamepad` associated with an `id`.
pub fn gamepad(ctx: &Context, id: GamepadId) -> Gamepad {
ctx.gamepad_context.gamepad(id)
}
/// Return an iterator of all the `Gamepads` that are connected.
pub fn gamepads(ctx: &Context) -> GamepadsIterator {
ctx.gamepad_context.gamepads()
}
// Properties gamepads might want:
// Number of buttons
// Number of axes
// Name/ID
// Is it connected? (For consoles?)
// Whether or not they support vibration
/*
/// Lists all gamepads. With metainfo, maybe?
pub fn list_gamepads() {
unimplemented!()
}
/// Returns the state of the given axis on a gamepad.
pub fn axis() {
unimplemented!()
}
/// Returns the state of the given button on a gamepad.
pub fn button_pressed() {
unimplemented!()
}
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gilrs_init() {
assert!(GilrsGamepadContext::new().is_ok());
}
}
| {
panic!("Gamepad module disabled")
} | identifier_body |
mod.rs | #![cfg(target_os = "android")]
use crate::api::egl::{
Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType,
};
use crate::CreationError::{self, OsError};
use crate::{
Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect,
};
use crate::platform::android::EventLoopExtAndroid;
use glutin_egl_sys as ffi;
use parking_lot::Mutex;
use winit;
use winit::dpi;
use winit::event_loop::EventLoopWindowTarget;
use winit::window::WindowBuilder;
use std::sync::Arc;
#[derive(Debug)]
struct AndroidContext {
egl_context: EglContext,
stopped: Option<Mutex<bool>>,
}
#[derive(Debug)]
pub struct Context(Arc<AndroidContext>);
#[derive(Debug)]
struct AndroidSyncEventHandler(Arc<AndroidContext>);
impl android_glue::SyncEventHandler for AndroidSyncEventHandler {
fn handle(&mut self, event: &android_glue::Event) {
match *event {
// 'on_surface_destroyed' Android event can arrive with some delay
// because multithreading communication. Because of
// that, swap_buffers can be called before processing
// 'on_surface_destroyed' event, with the native window
// surface already destroyed. EGL generates a BAD_SURFACE error in
// this situation. Set stop to true to prevent
// swap_buffer call race conditions.
android_glue::Event::TermWindow => {
let mut stopped = self.0.stopped.as_ref().unwrap().lock();
*stopped = true;
}
_ => {
return;
}
};
}
}
impl Context {
#[inline]
pub fn new_windowed<T>(
wb: WindowBuilder,
el: &EventLoopWindowTarget<T>,
pf_reqs: &PixelFormatRequirements,
gl_attr: &GlAttributes<&Self>,
) -> Result<(winit::window::Window, Self), CreationError> {
let win = wb.build(el)?;
let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context);
let nwin = unsafe { android_glue::get_native_window() };
if nwin.is_null() {
return Err(OsError("Android's native window is null".to_string()));
}
let native_display = NativeDisplay::Android;
let egl_context = EglContext::new(
pf_reqs,
&gl_attr,
native_display,
EglSurfaceType::Window,
|c, _| Ok(c[0]),
)
.and_then(|p| p.finish(nwin as *const _))?;
let ctx = Arc::new(AndroidContext {
egl_context,
stopped: Some(Mutex::new(false)),
});
let handler = Box::new(AndroidSyncEventHandler(ctx.clone()));
android_glue::add_sync_event_handler(handler);
let context = Context(ctx.clone());
el.set_suspend_callback(Some(Box::new(move |suspended| {
let mut stopped = ctx.stopped.as_ref().unwrap().lock();
*stopped = suspended;
if suspended {
// Android has stopped the activity or sent it to background.
// Release the EGL surface and stop the animation loop.
unsafe {
ctx.egl_context.on_surface_destroyed();
}
} else {
// Android has started the activity or sent it to foreground.
// Restore the EGL surface and animation loop.
unsafe {
let nwin = android_glue::get_native_window();
ctx.egl_context.on_surface_created(nwin as *const _);
}
}
})));
Ok((win, context))
}
#[inline]
pub fn new_headless<T>(
_el: &EventLoopWindowTarget<T>,
pf_reqs: &PixelFormatRequirements,
gl_attr: &GlAttributes<&Context>,
size: dpi::PhysicalSize<u32>,
) -> Result<Self, CreationError> {
let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context);
let context = EglContext::new(
pf_reqs,
&gl_attr,
NativeDisplay::Android,
EglSurfaceType::PBuffer,
|c, _| Ok(c[0]),
)?;
let egl_context = context.finish_pbuffer(size)?;
let ctx = Arc::new(AndroidContext {
egl_context,
stopped: None,
});
Ok(Context(ctx))
}
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.make_current()
}
#[inline]
pub unsafe fn make_not_current(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.make_not_current()
}
#[inline]
pub fn resize(&self, _: u32, _: u32) {}
#[inline]
pub fn is_current(&self) -> bool {
self.0.egl_context.is_current()
}
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const core::ffi::c_void {
self.0.egl_context.get_proc_address(addr)
}
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.swap_buffers()
}
#[inline]
pub fn swap_buffers_with_damage(
&self,
rects: &[Rect],
) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.swap_buffers_with_damage(rects)
}
#[inline]
pub fn swap_buffers_with_damage_supported(&self) -> bool { |
#[inline]
pub fn get_api(&self) -> Api {
self.0.egl_context.get_api()
}
#[inline]
pub fn get_pixel_format(&self) -> PixelFormat {
self.0.egl_context.get_pixel_format()
}
#[inline]
pub unsafe fn raw_handle(&self) -> ffi::EGLContext {
self.0.egl_context.raw_handle()
}
#[inline]
pub unsafe fn get_egl_display(&self) -> ffi::EGLDisplay {
self.0.egl_context.get_egl_display()
}
} | self.0.egl_context.swap_buffers_with_damage_supported()
} | random_line_split |
mod.rs | #![cfg(target_os = "android")]
use crate::api::egl::{
Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType,
};
use crate::CreationError::{self, OsError};
use crate::{
Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect,
};
use crate::platform::android::EventLoopExtAndroid;
use glutin_egl_sys as ffi;
use parking_lot::Mutex;
use winit;
use winit::dpi;
use winit::event_loop::EventLoopWindowTarget;
use winit::window::WindowBuilder;
use std::sync::Arc;
#[derive(Debug)]
struct AndroidContext {
egl_context: EglContext,
stopped: Option<Mutex<bool>>,
}
#[derive(Debug)]
pub struct Context(Arc<AndroidContext>);
#[derive(Debug)]
struct AndroidSyncEventHandler(Arc<AndroidContext>);
impl android_glue::SyncEventHandler for AndroidSyncEventHandler {
fn handle(&mut self, event: &android_glue::Event) {
match *event {
// 'on_surface_destroyed' Android event can arrive with some delay
// because multithreading communication. Because of
// that, swap_buffers can be called before processing
// 'on_surface_destroyed' event, with the native window
// surface already destroyed. EGL generates a BAD_SURFACE error in
// this situation. Set stop to true to prevent
// swap_buffer call race conditions.
android_glue::Event::TermWindow => {
let mut stopped = self.0.stopped.as_ref().unwrap().lock();
*stopped = true;
}
_ => {
return;
}
};
}
}
impl Context {
#[inline]
pub fn new_windowed<T>(
wb: WindowBuilder,
el: &EventLoopWindowTarget<T>,
pf_reqs: &PixelFormatRequirements,
gl_attr: &GlAttributes<&Self>,
) -> Result<(winit::window::Window, Self), CreationError> {
let win = wb.build(el)?;
let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context);
let nwin = unsafe { android_glue::get_native_window() };
if nwin.is_null() {
return Err(OsError("Android's native window is null".to_string()));
}
let native_display = NativeDisplay::Android;
let egl_context = EglContext::new(
pf_reqs,
&gl_attr,
native_display,
EglSurfaceType::Window,
|c, _| Ok(c[0]),
)
.and_then(|p| p.finish(nwin as *const _))?;
let ctx = Arc::new(AndroidContext {
egl_context,
stopped: Some(Mutex::new(false)),
});
let handler = Box::new(AndroidSyncEventHandler(ctx.clone()));
android_glue::add_sync_event_handler(handler);
let context = Context(ctx.clone());
el.set_suspend_callback(Some(Box::new(move |suspended| {
let mut stopped = ctx.stopped.as_ref().unwrap().lock();
*stopped = suspended;
if suspended {
// Android has stopped the activity or sent it to background.
// Release the EGL surface and stop the animation loop.
unsafe {
ctx.egl_context.on_surface_destroyed();
}
} else {
// Android has started the activity or sent it to foreground.
// Restore the EGL surface and animation loop.
unsafe {
let nwin = android_glue::get_native_window();
ctx.egl_context.on_surface_created(nwin as *const _);
}
}
})));
Ok((win, context))
}
#[inline]
pub fn new_headless<T>(
_el: &EventLoopWindowTarget<T>,
pf_reqs: &PixelFormatRequirements,
gl_attr: &GlAttributes<&Context>,
size: dpi::PhysicalSize<u32>,
) -> Result<Self, CreationError> {
let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context);
let context = EglContext::new(
pf_reqs,
&gl_attr,
NativeDisplay::Android,
EglSurfaceType::PBuffer,
|c, _| Ok(c[0]),
)?;
let egl_context = context.finish_pbuffer(size)?;
let ctx = Arc::new(AndroidContext {
egl_context,
stopped: None,
});
Ok(Context(ctx))
}
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.make_current()
}
#[inline]
pub unsafe fn make_not_current(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.make_not_current()
}
#[inline]
pub fn resize(&self, _: u32, _: u32) {}
#[inline]
pub fn is_current(&self) -> bool {
self.0.egl_context.is_current()
}
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const core::ffi::c_void {
self.0.egl_context.get_proc_address(addr)
}
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.swap_buffers()
}
#[inline]
pub fn swap_buffers_with_damage(
&self,
rects: &[Rect],
) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.swap_buffers_with_damage(rects)
}
#[inline]
pub fn swap_buffers_with_damage_supported(&self) -> bool {
self.0.egl_context.swap_buffers_with_damage_supported()
}
#[inline]
pub fn get_api(&self) -> Api {
self.0.egl_context.get_api()
}
#[inline]
pub fn get_pixel_format(&self) -> PixelFormat {
self.0.egl_context.get_pixel_format()
}
#[inline]
pub unsafe fn raw_handle(&self) -> ffi::EGLContext {
self.0.egl_context.raw_handle()
}
#[inline]
pub unsafe fn | (&self) -> ffi::EGLDisplay {
self.0.egl_context.get_egl_display()
}
}
| get_egl_display | identifier_name |
mod.rs | #![cfg(target_os = "android")]
use crate::api::egl::{
Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType,
};
use crate::CreationError::{self, OsError};
use crate::{
Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect,
};
use crate::platform::android::EventLoopExtAndroid;
use glutin_egl_sys as ffi;
use parking_lot::Mutex;
use winit;
use winit::dpi;
use winit::event_loop::EventLoopWindowTarget;
use winit::window::WindowBuilder;
use std::sync::Arc;
#[derive(Debug)]
struct AndroidContext {
egl_context: EglContext,
stopped: Option<Mutex<bool>>,
}
#[derive(Debug)]
pub struct Context(Arc<AndroidContext>);
#[derive(Debug)]
struct AndroidSyncEventHandler(Arc<AndroidContext>);
impl android_glue::SyncEventHandler for AndroidSyncEventHandler {
fn handle(&mut self, event: &android_glue::Event) {
match *event {
// 'on_surface_destroyed' Android event can arrive with some delay
// because multithreading communication. Because of
// that, swap_buffers can be called before processing
// 'on_surface_destroyed' event, with the native window
// surface already destroyed. EGL generates a BAD_SURFACE error in
// this situation. Set stop to true to prevent
// swap_buffer call race conditions.
android_glue::Event::TermWindow => |
_ => {
return;
}
};
}
}
impl Context {
#[inline]
pub fn new_windowed<T>(
wb: WindowBuilder,
el: &EventLoopWindowTarget<T>,
pf_reqs: &PixelFormatRequirements,
gl_attr: &GlAttributes<&Self>,
) -> Result<(winit::window::Window, Self), CreationError> {
let win = wb.build(el)?;
let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context);
let nwin = unsafe { android_glue::get_native_window() };
if nwin.is_null() {
return Err(OsError("Android's native window is null".to_string()));
}
let native_display = NativeDisplay::Android;
let egl_context = EglContext::new(
pf_reqs,
&gl_attr,
native_display,
EglSurfaceType::Window,
|c, _| Ok(c[0]),
)
.and_then(|p| p.finish(nwin as *const _))?;
let ctx = Arc::new(AndroidContext {
egl_context,
stopped: Some(Mutex::new(false)),
});
let handler = Box::new(AndroidSyncEventHandler(ctx.clone()));
android_glue::add_sync_event_handler(handler);
let context = Context(ctx.clone());
el.set_suspend_callback(Some(Box::new(move |suspended| {
let mut stopped = ctx.stopped.as_ref().unwrap().lock();
*stopped = suspended;
if suspended {
// Android has stopped the activity or sent it to background.
// Release the EGL surface and stop the animation loop.
unsafe {
ctx.egl_context.on_surface_destroyed();
}
} else {
// Android has started the activity or sent it to foreground.
// Restore the EGL surface and animation loop.
unsafe {
let nwin = android_glue::get_native_window();
ctx.egl_context.on_surface_created(nwin as *const _);
}
}
})));
Ok((win, context))
}
#[inline]
pub fn new_headless<T>(
_el: &EventLoopWindowTarget<T>,
pf_reqs: &PixelFormatRequirements,
gl_attr: &GlAttributes<&Context>,
size: dpi::PhysicalSize<u32>,
) -> Result<Self, CreationError> {
let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context);
let context = EglContext::new(
pf_reqs,
&gl_attr,
NativeDisplay::Android,
EglSurfaceType::PBuffer,
|c, _| Ok(c[0]),
)?;
let egl_context = context.finish_pbuffer(size)?;
let ctx = Arc::new(AndroidContext {
egl_context,
stopped: None,
});
Ok(Context(ctx))
}
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.make_current()
}
#[inline]
pub unsafe fn make_not_current(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.make_not_current()
}
#[inline]
pub fn resize(&self, _: u32, _: u32) {}
#[inline]
pub fn is_current(&self) -> bool {
self.0.egl_context.is_current()
}
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const core::ffi::c_void {
self.0.egl_context.get_proc_address(addr)
}
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.swap_buffers()
}
#[inline]
pub fn swap_buffers_with_damage(
&self,
rects: &[Rect],
) -> Result<(), ContextError> {
if let Some(ref stopped) = self.0.stopped {
let stopped = stopped.lock();
if *stopped {
return Err(ContextError::ContextLost);
}
}
self.0.egl_context.swap_buffers_with_damage(rects)
}
#[inline]
pub fn swap_buffers_with_damage_supported(&self) -> bool {
self.0.egl_context.swap_buffers_with_damage_supported()
}
#[inline]
pub fn get_api(&self) -> Api {
self.0.egl_context.get_api()
}
#[inline]
pub fn get_pixel_format(&self) -> PixelFormat {
self.0.egl_context.get_pixel_format()
}
#[inline]
pub unsafe fn raw_handle(&self) -> ffi::EGLContext {
self.0.egl_context.raw_handle()
}
#[inline]
pub unsafe fn get_egl_display(&self) -> ffi::EGLDisplay {
self.0.egl_context.get_egl_display()
}
}
| {
let mut stopped = self.0.stopped.as_ref().unwrap().lock();
*stopped = true;
} | conditional_block |
book.rs | use super::Processor;
use crate::data::messages::{BookRecord, BookUpdate, RecordUpdate};
use crate::data::trade::TradeBook; |
#[derive(Clone)]
pub struct Accountant {
tb: Arc<Mutex<TradeBook>>,
}
impl Accountant {
pub fn new(tb: Arc<Mutex<TradeBook>>) -> Accountant {
Accountant { tb }
}
}
impl Processor for Accountant {
fn process_message(&mut self, msg: String) -> Result<(), PoloError> {
let err = |title| PoloError::wrong_data(format!("{} {:?}", title, msg));
let update = BookUpdate::from_str(&msg)?;
for rec in update.records {
let mut tb = self.tb.lock().unwrap();
match rec {
RecordUpdate::Initial(book) => {
tb.add_book(book, update.book_id);
}
RecordUpdate::SellTotal(BookRecord { rate, amount }) => {
let book = tb
.book_by_id(update.book_id)
.ok_or_else(|| err("book not initialized"))?;
book.update_sell_orders(rate, amount);
}
RecordUpdate::BuyTotal(BookRecord { rate, amount }) => {
let book = tb
.book_by_id(update.book_id)
.ok_or_else(|| err("book not initialized"))?;
book.update_buy_orders(rate, amount);
}
RecordUpdate::Sell(deal) => {
let book = tb
.book_by_id(update.book_id)
.ok_or_else(|| err("book not initialized"))?;
book.new_deal(deal.id, deal.rate, -deal.amount)?;
}
RecordUpdate::Buy(deal) => {
let book = tb
.book_by_id(update.book_id)
.ok_or_else(|| err("book not initialized"))?;
book.new_deal(deal.id, deal.rate, deal.amount)?;
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::Accountant;
use crate::actors::Processor;
use crate::data::messages::{BookUpdate, RecordUpdate};
use crate::data::trade::TradeBook;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
#[test]
fn initial_order() {
let tb = Arc::new(Mutex::new(TradeBook::new()));
let mut accountant = Accountant::new(tb.clone());
let order = String::from(r#"[189, 5130995, [["i", {"currencyPair": "BTC_BCH", "orderBook": [{"0.13161901": 0.23709568, "0.13164313": "0.17328089"}, {"0.13169621": 0.2331}]}]]]"#);
accountant.process_message(order.clone()).unwrap();
let mut tb_mut = tb.lock().unwrap();
let actor_book = tb_mut.book_by_id(189).unwrap().book_ref();
match BookUpdate::from_str(&order).unwrap().records[0] {
RecordUpdate::Initial(ref book) => assert_eq!((&book.sell, &book.buy), (&actor_book.sell, &actor_book.buy)),
_ => panic!("BookUpdate::from_str were not able to parse RecordUpdate::Initial"),
}
}
} | use crate::error::PoloError;
use std::str::FromStr;
use std::sync::{Arc, Mutex}; | random_line_split |
book.rs | use super::Processor;
use crate::data::messages::{BookRecord, BookUpdate, RecordUpdate};
use crate::data::trade::TradeBook;
use crate::error::PoloError;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct Accountant {
tb: Arc<Mutex<TradeBook>>,
}
impl Accountant {
pub fn new(tb: Arc<Mutex<TradeBook>>) -> Accountant {
Accountant { tb }
}
}
impl Processor for Accountant {
fn process_message(&mut self, msg: String) -> Result<(), PoloError> {
let err = |title| PoloError::wrong_data(format!("{} {:?}", title, msg));
let update = BookUpdate::from_str(&msg)?;
for rec in update.records {
let mut tb = self.tb.lock().unwrap();
match rec {
RecordUpdate::Initial(book) => {
tb.add_book(book, update.book_id);
}
RecordUpdate::SellTotal(BookRecord { rate, amount }) => {
let book = tb
.book_by_id(update.book_id)
.ok_or_else(|| err("book not initialized"))?;
book.update_sell_orders(rate, amount);
}
RecordUpdate::BuyTotal(BookRecord { rate, amount }) => {
let book = tb
.book_by_id(update.book_id)
.ok_or_else(|| err("book not initialized"))?;
book.update_buy_orders(rate, amount);
}
RecordUpdate::Sell(deal) => {
let book = tb
.book_by_id(update.book_id)
.ok_or_else(|| err("book not initialized"))?;
book.new_deal(deal.id, deal.rate, -deal.amount)?;
}
RecordUpdate::Buy(deal) => {
let book = tb
.book_by_id(update.book_id)
.ok_or_else(|| err("book not initialized"))?;
book.new_deal(deal.id, deal.rate, deal.amount)?;
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::Accountant;
use crate::actors::Processor;
use crate::data::messages::{BookUpdate, RecordUpdate};
use crate::data::trade::TradeBook;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
#[test]
fn | () {
let tb = Arc::new(Mutex::new(TradeBook::new()));
let mut accountant = Accountant::new(tb.clone());
let order = String::from(r#"[189, 5130995, [["i", {"currencyPair": "BTC_BCH", "orderBook": [{"0.13161901": 0.23709568, "0.13164313": "0.17328089"}, {"0.13169621": 0.2331}]}]]]"#);
accountant.process_message(order.clone()).unwrap();
let mut tb_mut = tb.lock().unwrap();
let actor_book = tb_mut.book_by_id(189).unwrap().book_ref();
match BookUpdate::from_str(&order).unwrap().records[0] {
RecordUpdate::Initial(ref book) => assert_eq!((&book.sell, &book.buy), (&actor_book.sell, &actor_book.buy)),
_ => panic!("BookUpdate::from_str were not able to parse RecordUpdate::Initial"),
}
}
}
| initial_order | identifier_name |
bad_transaction.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_universe::{AUTransactionGen, AccountUniverse},
common_transactions::{empty_txn, EMPTY_SCRIPT},
gas_costs,
};
use diem_crypto::{
ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey},
test_utils::KeyPair,
};
use diem_proptest_helpers::Index;
use diem_types::{
account_config::XUS_NAME,
transaction::{Script, SignedTransaction, TransactionStatus},
vm_status::StatusCode,
};
use move_core_types::gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier, GasConstants};
use move_vm_types::gas_schedule::calculate_intrinsic_gas;
use proptest::prelude::*;
use proptest_derive::Arbitrary;
use std::sync::Arc;
/// Represents a sequence number mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct SequenceNumberMismatchGen {
sender: Index,
#[proptest(strategy = "params.0..= params.1")]
seq: u64,
}
impl AUTransactionGen for SequenceNumberMismatchGen {
fn | (
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let seq = if sender.sequence_number == self.seq {
self.seq + 1
} else {
self.seq
};
let txn = empty_txn(
sender.account(),
seq,
gas_costs::TXN_RESERVED,
0,
XUS_NAME.to_string(),
);
(
txn,
(
if seq >= sender.sequence_number {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_NEW)
} else {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_OLD)
},
0,
),
)
}
}
/// Represents a insufficient balance transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct InsufficientBalanceGen {
sender: Index,
#[proptest(strategy = "params.0..= params.1")]
gas_unit_price: u64,
}
impl AUTransactionGen for InsufficientBalanceGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let max_gas_unit = (sender.balance / self.gas_unit_price) + 1;
let txn = empty_txn(
sender.account(),
sender.sequence_number,
max_gas_unit,
self.gas_unit_price,
XUS_NAME.to_string(),
);
// TODO: Move such config to AccountUniverse
let default_constants = GasConstants::default();
let raw_bytes_len = AbstractMemorySize::new(txn.raw_txn_bytes_len() as GasCarrier);
let min_cost = GasConstants::default()
.to_external_units(calculate_intrinsic_gas(
raw_bytes_len,
&GasConstants::default(),
))
.get();
(
txn,
(
if max_gas_unit > default_constants.maximum_number_of_gas_units.get() {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND,
)
} else if max_gas_unit < min_cost {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS,
)
} else if self.gas_unit_price > default_constants.max_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_ABOVE_MAX_BOUND)
} else if self.gas_unit_price < default_constants.min_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_BELOW_MIN_BOUND)
} else {
TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE)
},
0,
),
)
}
}
/// Represents a authkey mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(no_params)]
pub struct InvalidAuthkeyGen {
sender: Index,
#[proptest(strategy = "ed25519::keypair_strategy()")]
new_keypair: KeyPair<Ed25519PrivateKey, Ed25519PublicKey>,
}
impl AUTransactionGen for InvalidAuthkeyGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let txn = sender
.account()
.transaction()
.script(Script::new(EMPTY_SCRIPT.clone(), vec![], vec![]))
.sequence_number(sender.sequence_number)
.raw()
.sign(
&self.new_keypair.private_key,
self.new_keypair.public_key.clone(),
)
.unwrap()
.into_inner();
(
txn,
(TransactionStatus::Discard(StatusCode::INVALID_AUTH_KEY), 0),
)
}
}
pub fn bad_txn_strategy() -> impl Strategy<Value = Arc<dyn AUTransactionGen +'static>> {
prop_oneof![
1 => any_with::<SequenceNumberMismatchGen>((0, 10_000)).prop_map(SequenceNumberMismatchGen::arced),
1 => any_with::<InvalidAuthkeyGen>(()).prop_map(InvalidAuthkeyGen::arced),
1 => any_with::<InsufficientBalanceGen>((1, 20_000)).prop_map(InsufficientBalanceGen::arced),
]
}
| apply | identifier_name |
bad_transaction.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_universe::{AUTransactionGen, AccountUniverse},
common_transactions::{empty_txn, EMPTY_SCRIPT},
gas_costs,
};
use diem_crypto::{
ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey},
test_utils::KeyPair,
};
use diem_proptest_helpers::Index;
use diem_types::{
account_config::XUS_NAME,
transaction::{Script, SignedTransaction, TransactionStatus},
vm_status::StatusCode,
};
use move_core_types::gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier, GasConstants};
use move_vm_types::gas_schedule::calculate_intrinsic_gas;
use proptest::prelude::*;
use proptest_derive::Arbitrary;
use std::sync::Arc;
/// Represents a sequence number mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct SequenceNumberMismatchGen {
sender: Index,
#[proptest(strategy = "params.0..= params.1")]
seq: u64,
}
impl AUTransactionGen for SequenceNumberMismatchGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let seq = if sender.sequence_number == self.seq {
self.seq + 1
} else | ;
let txn = empty_txn(
sender.account(),
seq,
gas_costs::TXN_RESERVED,
0,
XUS_NAME.to_string(),
);
(
txn,
(
if seq >= sender.sequence_number {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_NEW)
} else {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_OLD)
},
0,
),
)
}
}
/// Represents a insufficient balance transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct InsufficientBalanceGen {
sender: Index,
#[proptest(strategy = "params.0..= params.1")]
gas_unit_price: u64,
}
impl AUTransactionGen for InsufficientBalanceGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let max_gas_unit = (sender.balance / self.gas_unit_price) + 1;
let txn = empty_txn(
sender.account(),
sender.sequence_number,
max_gas_unit,
self.gas_unit_price,
XUS_NAME.to_string(),
);
// TODO: Move such config to AccountUniverse
let default_constants = GasConstants::default();
let raw_bytes_len = AbstractMemorySize::new(txn.raw_txn_bytes_len() as GasCarrier);
let min_cost = GasConstants::default()
.to_external_units(calculate_intrinsic_gas(
raw_bytes_len,
&GasConstants::default(),
))
.get();
(
txn,
(
if max_gas_unit > default_constants.maximum_number_of_gas_units.get() {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND,
)
} else if max_gas_unit < min_cost {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS,
)
} else if self.gas_unit_price > default_constants.max_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_ABOVE_MAX_BOUND)
} else if self.gas_unit_price < default_constants.min_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_BELOW_MIN_BOUND)
} else {
TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE)
},
0,
),
)
}
}
/// Represents a authkey mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(no_params)]
pub struct InvalidAuthkeyGen {
sender: Index,
#[proptest(strategy = "ed25519::keypair_strategy()")]
new_keypair: KeyPair<Ed25519PrivateKey, Ed25519PublicKey>,
}
impl AUTransactionGen for InvalidAuthkeyGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let txn = sender
.account()
.transaction()
.script(Script::new(EMPTY_SCRIPT.clone(), vec![], vec![]))
.sequence_number(sender.sequence_number)
.raw()
.sign(
&self.new_keypair.private_key,
self.new_keypair.public_key.clone(),
)
.unwrap()
.into_inner();
(
txn,
(TransactionStatus::Discard(StatusCode::INVALID_AUTH_KEY), 0),
)
}
}
pub fn bad_txn_strategy() -> impl Strategy<Value = Arc<dyn AUTransactionGen +'static>> {
prop_oneof![
1 => any_with::<SequenceNumberMismatchGen>((0, 10_000)).prop_map(SequenceNumberMismatchGen::arced),
1 => any_with::<InvalidAuthkeyGen>(()).prop_map(InvalidAuthkeyGen::arced),
1 => any_with::<InsufficientBalanceGen>((1, 20_000)).prop_map(InsufficientBalanceGen::arced),
]
}
| {
self.seq
} | conditional_block |
bad_transaction.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_universe::{AUTransactionGen, AccountUniverse},
common_transactions::{empty_txn, EMPTY_SCRIPT},
gas_costs,
};
use diem_crypto::{
ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey},
test_utils::KeyPair,
};
use diem_proptest_helpers::Index;
use diem_types::{
account_config::XUS_NAME,
transaction::{Script, SignedTransaction, TransactionStatus},
vm_status::StatusCode,
};
use move_core_types::gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier, GasConstants};
use move_vm_types::gas_schedule::calculate_intrinsic_gas;
use proptest::prelude::*;
use proptest_derive::Arbitrary;
use std::sync::Arc;
/// Represents a sequence number mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct SequenceNumberMismatchGen {
sender: Index,
#[proptest(strategy = "params.0..= params.1")]
seq: u64,
}
impl AUTransactionGen for SequenceNumberMismatchGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let seq = if sender.sequence_number == self.seq {
self.seq + 1
} else {
self.seq
};
let txn = empty_txn(
sender.account(),
seq,
gas_costs::TXN_RESERVED,
0,
XUS_NAME.to_string(),
);
(
txn,
(
if seq >= sender.sequence_number {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_NEW)
} else {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_OLD)
},
0,
),
)
}
}
/// Represents a insufficient balance transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct InsufficientBalanceGen {
sender: Index,
#[proptest(strategy = "params.0..= params.1")]
gas_unit_price: u64,
}
impl AUTransactionGen for InsufficientBalanceGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let max_gas_unit = (sender.balance / self.gas_unit_price) + 1;
let txn = empty_txn(
sender.account(),
sender.sequence_number,
max_gas_unit,
self.gas_unit_price,
XUS_NAME.to_string(),
);
// TODO: Move such config to AccountUniverse
let default_constants = GasConstants::default();
let raw_bytes_len = AbstractMemorySize::new(txn.raw_txn_bytes_len() as GasCarrier);
let min_cost = GasConstants::default()
.to_external_units(calculate_intrinsic_gas(
raw_bytes_len,
&GasConstants::default(),
))
.get();
(
txn,
(
if max_gas_unit > default_constants.maximum_number_of_gas_units.get() {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND,
)
} else if max_gas_unit < min_cost {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS,
)
} else if self.gas_unit_price > default_constants.max_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_ABOVE_MAX_BOUND)
} else if self.gas_unit_price < default_constants.min_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_BELOW_MIN_BOUND)
} else {
TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE)
},
0,
),
)
}
}
/// Represents a authkey mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(no_params)]
pub struct InvalidAuthkeyGen {
sender: Index,
#[proptest(strategy = "ed25519::keypair_strategy()")]
new_keypair: KeyPair<Ed25519PrivateKey, Ed25519PublicKey>,
}
impl AUTransactionGen for InvalidAuthkeyGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let txn = sender
.account()
.transaction()
.script(Script::new(EMPTY_SCRIPT.clone(), vec![], vec![]))
.sequence_number(sender.sequence_number)
.raw()
.sign(
&self.new_keypair.private_key,
self.new_keypair.public_key.clone(),
)
.unwrap()
.into_inner();
(
txn,
(TransactionStatus::Discard(StatusCode::INVALID_AUTH_KEY), 0),
)
}
}
pub fn bad_txn_strategy() -> impl Strategy<Value = Arc<dyn AUTransactionGen +'static>> | {
prop_oneof![
1 => any_with::<SequenceNumberMismatchGen>((0, 10_000)).prop_map(SequenceNumberMismatchGen::arced),
1 => any_with::<InvalidAuthkeyGen>(()).prop_map(InvalidAuthkeyGen::arced),
1 => any_with::<InsufficientBalanceGen>((1, 20_000)).prop_map(InsufficientBalanceGen::arced),
]
} | identifier_body |
|
bad_transaction.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_universe::{AUTransactionGen, AccountUniverse},
common_transactions::{empty_txn, EMPTY_SCRIPT},
gas_costs,
};
use diem_crypto::{
ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey},
test_utils::KeyPair,
};
use diem_proptest_helpers::Index;
use diem_types::{
account_config::XUS_NAME,
transaction::{Script, SignedTransaction, TransactionStatus},
vm_status::StatusCode,
};
use move_core_types::gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier, GasConstants};
use move_vm_types::gas_schedule::calculate_intrinsic_gas;
use proptest::prelude::*;
use proptest_derive::Arbitrary;
use std::sync::Arc;
/// Represents a sequence number mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct SequenceNumberMismatchGen {
sender: Index,
#[proptest(strategy = "params.0..= params.1")]
seq: u64,
}
impl AUTransactionGen for SequenceNumberMismatchGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let seq = if sender.sequence_number == self.seq {
self.seq + 1
} else {
self.seq
};
let txn = empty_txn(
sender.account(),
seq,
gas_costs::TXN_RESERVED,
0, | XUS_NAME.to_string(),
);
(
txn,
(
if seq >= sender.sequence_number {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_NEW)
} else {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_OLD)
},
0,
),
)
}
}
/// Represents a insufficient balance transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct InsufficientBalanceGen {
sender: Index,
#[proptest(strategy = "params.0..= params.1")]
gas_unit_price: u64,
}
impl AUTransactionGen for InsufficientBalanceGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let max_gas_unit = (sender.balance / self.gas_unit_price) + 1;
let txn = empty_txn(
sender.account(),
sender.sequence_number,
max_gas_unit,
self.gas_unit_price,
XUS_NAME.to_string(),
);
// TODO: Move such config to AccountUniverse
let default_constants = GasConstants::default();
let raw_bytes_len = AbstractMemorySize::new(txn.raw_txn_bytes_len() as GasCarrier);
let min_cost = GasConstants::default()
.to_external_units(calculate_intrinsic_gas(
raw_bytes_len,
&GasConstants::default(),
))
.get();
(
txn,
(
if max_gas_unit > default_constants.maximum_number_of_gas_units.get() {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND,
)
} else if max_gas_unit < min_cost {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS,
)
} else if self.gas_unit_price > default_constants.max_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_ABOVE_MAX_BOUND)
} else if self.gas_unit_price < default_constants.min_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_BELOW_MIN_BOUND)
} else {
TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE)
},
0,
),
)
}
}
/// Represents a authkey mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(no_params)]
pub struct InvalidAuthkeyGen {
sender: Index,
#[proptest(strategy = "ed25519::keypair_strategy()")]
new_keypair: KeyPair<Ed25519PrivateKey, Ed25519PublicKey>,
}
impl AUTransactionGen for InvalidAuthkeyGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let txn = sender
.account()
.transaction()
.script(Script::new(EMPTY_SCRIPT.clone(), vec![], vec![]))
.sequence_number(sender.sequence_number)
.raw()
.sign(
&self.new_keypair.private_key,
self.new_keypair.public_key.clone(),
)
.unwrap()
.into_inner();
(
txn,
(TransactionStatus::Discard(StatusCode::INVALID_AUTH_KEY), 0),
)
}
}
pub fn bad_txn_strategy() -> impl Strategy<Value = Arc<dyn AUTransactionGen +'static>> {
prop_oneof![
1 => any_with::<SequenceNumberMismatchGen>((0, 10_000)).prop_map(SequenceNumberMismatchGen::arced),
1 => any_with::<InvalidAuthkeyGen>(()).prop_map(InvalidAuthkeyGen::arced),
1 => any_with::<InsufficientBalanceGen>((1, 20_000)).prop_map(InsufficientBalanceGen::arced),
]
} | random_line_split |
|
libc_heap.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The global (exchange) heap.
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, null_mut};
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
// `malloc(0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
if size == 0 {
null_mut()
} else {
let p = malloc(size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn | (ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
if size == 0 {
free(ptr as *mut c_void);
null_mut()
} else {
let p = realloc(ptr as *mut c_void, size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
| realloc_raw | identifier_name |
libc_heap.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The global (exchange) heap.
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, null_mut};
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 |
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn realloc_raw(ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
if size == 0 {
free(ptr as *mut c_void);
null_mut()
} else {
let p = realloc(ptr as *mut c_void, size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
| {
// `malloc(0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
if size == 0 {
null_mut()
} else {
let p = malloc(size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
} | identifier_body |
libc_heap.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The global (exchange) heap.
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, null_mut};
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
// `malloc(0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
if size == 0 {
null_mut()
} else {
let p = malloc(size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn realloc_raw(ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
if size == 0 {
free(ptr as *mut c_void);
null_mut()
} else {
let p = realloc(ptr as *mut c_void, size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8 | } | } | random_line_split |
libc_heap.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The global (exchange) heap.
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, null_mut};
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
// `malloc(0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
if size == 0 {
null_mut()
} else {
let p = malloc(size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn realloc_raw(ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
if size == 0 {
free(ptr as *mut c_void);
null_mut()
} else {
let p = realloc(ptr as *mut c_void, size as size_t);
if p.is_null() |
p as *mut u8
}
}
| {
::oom();
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(int_uint)]
extern crate devtools_traits;
extern crate geom;
extern crate libc;
extern crate msg;
extern crate net;
extern crate util;
extern crate url;
// This module contains traits in script used generically
// in the rest of Servo.
// The traits are here instead of in script so
// that these modules won't have to depend on script.
use devtools_traits::DevtoolsControlChan;
use libc::c_void;
use msg::constellation_msg::{ConstellationChan, PipelineId, Failure, WindowSizeData};
use msg::constellation_msg::{LoadData, SubpageId, Key, KeyState, KeyModifiers};
use msg::constellation_msg::PipelineExitType;
use msg::compositor_msg::ScriptListener;
use net::image_cache_task::ImageCacheTask;
use net::resource_task::ResourceTask;
use net::storage_task::StorageTask;
use util::smallvec::SmallVec1;
use std::any::Any;
use std::sync::mpsc::{Sender, Receiver};
use geom::point::Point2D;
use geom::rect::Rect;
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[allow(raw_pointer_derive)]
#[derive(Copy, Clone)]
pub struct UntrustedNodeAddress(pub *const c_void);
unsafe impl Send for UntrustedNodeAddress {}
pub struct | {
pub containing_pipeline_id: PipelineId,
pub new_pipeline_id: PipelineId,
pub subpage_id: SubpageId,
pub layout_chan: Box<Any+Send>, // opaque reference to a LayoutChannel
pub load_data: LoadData,
}
/// Messages sent from the constellation to the script task
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, PipelineExitType),
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script that reflow is finished.
ReflowComplete(PipelineId, uint),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Requests that the script task immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script task to suspend all its timers
Freeze(PipelineId),
/// Notifies script task to resume all its timers
Thaw(PipelineId),
/// Notifies script task that a url should be loaded in this iframe.
Navigate(PipelineId, SubpageId, LoadData),
/// Requests the script task forward a mozbrowser event to an iframe it owns
MozBrowserEvent(PipelineId, SubpageId, String, Option<String>),
}
unsafe impl Send for ConstellationControlMsg {
}
/// Events from the compositor that the script task needs to know about
pub enum CompositorEvent {
ResizeEvent(WindowSizeData),
ReflowEvent(SmallVec1<UntrustedNodeAddress>),
ClickEvent(uint, Point2D<f32>),
MouseDownEvent(uint, Point2D<f32>),
MouseUpEvent(uint, Point2D<f32>),
MouseMoveEvent(Point2D<f32>),
KeyEvent(Key, KeyState, KeyModifiers),
}
/// An opaque wrapper around script<->layout channels to avoid leaking message types into
/// crates that don't need to know about them.
pub struct OpaqueScriptLayoutChannel(pub (Box<Any+Send>, Box<Any+Send>));
/// Encapsulates external communication with the script task.
#[derive(Clone)]
pub struct ScriptControlChan(pub Sender<ConstellationControlMsg>);
pub trait ScriptTaskFactory {
fn create<C>(_phantom: Option<&mut Self>,
id: PipelineId,
parent_info: Option<(PipelineId, SubpageId)>,
compositor: C,
layout_chan: &OpaqueScriptLayoutChannel,
control_chan: ScriptControlChan,
control_port: Receiver<ConstellationControlMsg>,
constellation_msg: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
storage_task: StorageTask,
image_cache_task: ImageCacheTask,
devtools_chan: Option<DevtoolsControlChan>,
window_size: Option<WindowSizeData>,
load_data: LoadData)
where C: ScriptListener + Send;
fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel;
fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel)
-> Box<Any+Send>;
}
| NewLayoutInfo | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(int_uint)]
extern crate devtools_traits;
extern crate geom;
extern crate libc;
extern crate msg;
extern crate net;
extern crate util;
extern crate url;
// This module contains traits in script used generically
// in the rest of Servo.
// The traits are here instead of in script so
// that these modules won't have to depend on script.
use devtools_traits::DevtoolsControlChan;
use libc::c_void;
use msg::constellation_msg::{ConstellationChan, PipelineId, Failure, WindowSizeData};
use msg::constellation_msg::{LoadData, SubpageId, Key, KeyState, KeyModifiers};
use msg::constellation_msg::PipelineExitType;
use msg::compositor_msg::ScriptListener;
use net::image_cache_task::ImageCacheTask;
use net::resource_task::ResourceTask;
use net::storage_task::StorageTask;
use util::smallvec::SmallVec1; |
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[allow(raw_pointer_derive)]
#[derive(Copy, Clone)]
pub struct UntrustedNodeAddress(pub *const c_void);
unsafe impl Send for UntrustedNodeAddress {}
pub struct NewLayoutInfo {
pub containing_pipeline_id: PipelineId,
pub new_pipeline_id: PipelineId,
pub subpage_id: SubpageId,
pub layout_chan: Box<Any+Send>, // opaque reference to a LayoutChannel
pub load_data: LoadData,
}
/// Messages sent from the constellation to the script task
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, PipelineExitType),
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script that reflow is finished.
ReflowComplete(PipelineId, uint),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Requests that the script task immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script task to suspend all its timers
Freeze(PipelineId),
/// Notifies script task to resume all its timers
Thaw(PipelineId),
/// Notifies script task that a url should be loaded in this iframe.
Navigate(PipelineId, SubpageId, LoadData),
/// Requests the script task forward a mozbrowser event to an iframe it owns
MozBrowserEvent(PipelineId, SubpageId, String, Option<String>),
}
unsafe impl Send for ConstellationControlMsg {
}
/// Events from the compositor that the script task needs to know about
pub enum CompositorEvent {
ResizeEvent(WindowSizeData),
ReflowEvent(SmallVec1<UntrustedNodeAddress>),
ClickEvent(uint, Point2D<f32>),
MouseDownEvent(uint, Point2D<f32>),
MouseUpEvent(uint, Point2D<f32>),
MouseMoveEvent(Point2D<f32>),
KeyEvent(Key, KeyState, KeyModifiers),
}
/// An opaque wrapper around script<->layout channels to avoid leaking message types into
/// crates that don't need to know about them.
pub struct OpaqueScriptLayoutChannel(pub (Box<Any+Send>, Box<Any+Send>));
/// Encapsulates external communication with the script task.
#[derive(Clone)]
pub struct ScriptControlChan(pub Sender<ConstellationControlMsg>);
pub trait ScriptTaskFactory {
fn create<C>(_phantom: Option<&mut Self>,
id: PipelineId,
parent_info: Option<(PipelineId, SubpageId)>,
compositor: C,
layout_chan: &OpaqueScriptLayoutChannel,
control_chan: ScriptControlChan,
control_port: Receiver<ConstellationControlMsg>,
constellation_msg: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
storage_task: StorageTask,
image_cache_task: ImageCacheTask,
devtools_chan: Option<DevtoolsControlChan>,
window_size: Option<WindowSizeData>,
load_data: LoadData)
where C: ScriptListener + Send;
fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel;
fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel)
-> Box<Any+Send>;
} | use std::any::Any;
use std::sync::mpsc::{Sender, Receiver};
use geom::point::Point2D;
use geom::rect::Rect; | random_line_split |
std-sync-right-kind-impls.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(static_mutex, static_rwlock, static_condvar)]
#![feature(arc_weak, semaphore)]
use std::sync;
fn assert_both<T: Sync + Send>() {}
fn | () {
assert_both::<sync::StaticMutex>();
assert_both::<sync::StaticCondvar>();
assert_both::<sync::StaticRwLock>();
assert_both::<sync::Mutex<()>>();
assert_both::<sync::Condvar>();
assert_both::<sync::RwLock<()>>();
assert_both::<sync::Semaphore>();
assert_both::<sync::Barrier>();
assert_both::<sync::Arc<()>>();
assert_both::<sync::Weak<()>>();
assert_both::<sync::Once>();
}
| main | identifier_name |
std-sync-right-kind-impls.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(static_mutex, static_rwlock, static_condvar)]
#![feature(arc_weak, semaphore)]
use std::sync;
fn assert_both<T: Sync + Send>() {}
fn main() | {
assert_both::<sync::StaticMutex>();
assert_both::<sync::StaticCondvar>();
assert_both::<sync::StaticRwLock>();
assert_both::<sync::Mutex<()>>();
assert_both::<sync::Condvar>();
assert_both::<sync::RwLock<()>>();
assert_both::<sync::Semaphore>();
assert_both::<sync::Barrier>();
assert_both::<sync::Arc<()>>();
assert_both::<sync::Weak<()>>();
assert_both::<sync::Once>();
} | identifier_body |
|
std-sync-right-kind-impls.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(static_mutex, static_rwlock, static_condvar)]
#![feature(arc_weak, semaphore)]
|
fn assert_both<T: Sync + Send>() {}
fn main() {
assert_both::<sync::StaticMutex>();
assert_both::<sync::StaticCondvar>();
assert_both::<sync::StaticRwLock>();
assert_both::<sync::Mutex<()>>();
assert_both::<sync::Condvar>();
assert_both::<sync::RwLock<()>>();
assert_both::<sync::Semaphore>();
assert_both::<sync::Barrier>();
assert_both::<sync::Arc<()>>();
assert_both::<sync::Weak<()>>();
assert_both::<sync::Once>();
} | use std::sync; | random_line_split |
arena_storage_pool.rs | // Implements http://rosettacode.org/wiki/Arena_storage_pool
#![feature(rustc_private)]
extern crate arena;
| use arena::TypedArena;
#[cfg(not(test))]
fn main() {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
let arena = TypedArena::new();
// The arena crate contains two types of arenas: TypedArena and Arena. Arena is
// reflection-basd and slower, but can allocate objects of any type. TypedArena is faster, and
// can allocate only objects of one type. The type is determined by type inference--if you try
// to allocate an integer, then Rust's compiler knows it is an integer arena.
let v1 = arena.alloc(1i32);
// TypedArena returns a mutable reference
let v2 = arena.alloc(3);
*v2 += 38;
println!("{}", *v1 + *v2);
// The arena's destructor is called as it goes out of scope, at which point it deallocates
// everything stored within it at once.
} | random_line_split |
|
arena_storage_pool.rs | // Implements http://rosettacode.org/wiki/Arena_storage_pool
#![feature(rustc_private)]
extern crate arena;
use arena::TypedArena;
#[cfg(not(test))]
fn | () {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
let arena = TypedArena::new();
// The arena crate contains two types of arenas: TypedArena and Arena. Arena is
// reflection-basd and slower, but can allocate objects of any type. TypedArena is faster, and
// can allocate only objects of one type. The type is determined by type inference--if you try
// to allocate an integer, then Rust's compiler knows it is an integer arena.
let v1 = arena.alloc(1i32);
// TypedArena returns a mutable reference
let v2 = arena.alloc(3);
*v2 += 38;
println!("{}", *v1 + *v2);
// The arena's destructor is called as it goes out of scope, at which point it deallocates
// everything stored within it at once.
}
| main | identifier_name |
arena_storage_pool.rs | // Implements http://rosettacode.org/wiki/Arena_storage_pool
#![feature(rustc_private)]
extern crate arena;
use arena::TypedArena;
#[cfg(not(test))]
fn main() | {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
let arena = TypedArena::new();
// The arena crate contains two types of arenas: TypedArena and Arena. Arena is
// reflection-basd and slower, but can allocate objects of any type. TypedArena is faster, and
// can allocate only objects of one type. The type is determined by type inference--if you try
// to allocate an integer, then Rust's compiler knows it is an integer arena.
let v1 = arena.alloc(1i32);
// TypedArena returns a mutable reference
let v2 = arena.alloc(3);
*v2 += 38;
println!("{}", *v1 + *v2);
// The arena's destructor is called as it goes out of scope, at which point it deallocates
// everything stored within it at once.
} | identifier_body |
|
common.rs | pub const SYS_DEBUG: usize = 0;
// Linux compatible
pub const SYS_BRK: usize = 45;
pub const SYS_CHDIR: usize = 12;
pub const SYS_CLOSE: usize = 6;
pub const SYS_CLONE: usize = 120;
pub const CLONE_VM: usize = 0x100;
pub const CLONE_FS: usize = 0x200;
pub const CLONE_FILES: usize = 0x400;
pub const SYS_CLOCK_GETTIME: usize = 265;
pub const CLOCK_REALTIME: usize = 0;
pub const CLOCK_MONOTONIC: usize = 1;
pub const SYS_DUP: usize = 41;
pub const SYS_EXECVE: usize = 11;
pub const SYS_EXIT: usize = 1;
pub const SYS_FPATH: usize = 3001;
pub const SYS_FSTAT: usize = 28;
pub const SYS_FSYNC: usize = 118;
pub const SYS_FTRUNCATE: usize = 93;
pub const SYS_LINK: usize = 9;
pub const SYS_LSEEK: usize = 19;
pub const SEEK_SET: usize = 0;
pub const SEEK_CUR: usize = 1;
pub const SEEK_END: usize = 2;
pub const SYS_MKDIR: usize = 39;
pub const SYS_NANOSLEEP: usize = 162;
pub const SYS_OPEN: usize = 5;
pub const O_RDONLY: usize = 0;
pub const O_WRONLY: usize = 1;
pub const O_RDWR: usize = 2;
pub const O_NONBLOCK: usize = 4;
pub const O_APPEND: usize = 8;
pub const O_SHLOCK: usize = 0x10;
pub const O_EXLOCK: usize = 0x20;
pub const O_ASYNC: usize = 0x40;
pub const O_FSYNC: usize = 0x80;
pub const O_CREAT: usize = 0x200;
pub const O_TRUNC: usize = 0x400;
pub const O_EXCL: usize = 0x800;
pub const SYS_READ: usize = 3;
pub const SYS_UNLINK: usize = 10;
pub const SYS_WRITE: usize = 4;
pub const SYS_YIELD: usize = 158;
// Rust Memory
pub const SYS_ALLOC: usize = 1000;
pub const SYS_REALLOC: usize = 1001;
pub const SYS_REALLOC_INPLACE: usize = 1002;
pub const SYS_UNALLOC: usize = 1003;
// Structures
#[repr(packed)]
pub struct | {
pub tv_sec: i64,
pub tv_nsec: i32,
}
| TimeSpec | identifier_name |
common.rs | pub const SYS_DEBUG: usize = 0;
// Linux compatible
pub const SYS_BRK: usize = 45;
pub const SYS_CHDIR: usize = 12; | pub const SYS_CLOCK_GETTIME: usize = 265;
pub const CLOCK_REALTIME: usize = 0;
pub const CLOCK_MONOTONIC: usize = 1;
pub const SYS_DUP: usize = 41;
pub const SYS_EXECVE: usize = 11;
pub const SYS_EXIT: usize = 1;
pub const SYS_FPATH: usize = 3001;
pub const SYS_FSTAT: usize = 28;
pub const SYS_FSYNC: usize = 118;
pub const SYS_FTRUNCATE: usize = 93;
pub const SYS_LINK: usize = 9;
pub const SYS_LSEEK: usize = 19;
pub const SEEK_SET: usize = 0;
pub const SEEK_CUR: usize = 1;
pub const SEEK_END: usize = 2;
pub const SYS_MKDIR: usize = 39;
pub const SYS_NANOSLEEP: usize = 162;
pub const SYS_OPEN: usize = 5;
pub const O_RDONLY: usize = 0;
pub const O_WRONLY: usize = 1;
pub const O_RDWR: usize = 2;
pub const O_NONBLOCK: usize = 4;
pub const O_APPEND: usize = 8;
pub const O_SHLOCK: usize = 0x10;
pub const O_EXLOCK: usize = 0x20;
pub const O_ASYNC: usize = 0x40;
pub const O_FSYNC: usize = 0x80;
pub const O_CREAT: usize = 0x200;
pub const O_TRUNC: usize = 0x400;
pub const O_EXCL: usize = 0x800;
pub const SYS_READ: usize = 3;
pub const SYS_UNLINK: usize = 10;
pub const SYS_WRITE: usize = 4;
pub const SYS_YIELD: usize = 158;
// Rust Memory
pub const SYS_ALLOC: usize = 1000;
pub const SYS_REALLOC: usize = 1001;
pub const SYS_REALLOC_INPLACE: usize = 1002;
pub const SYS_UNALLOC: usize = 1003;
// Structures
#[repr(packed)]
pub struct TimeSpec {
pub tv_sec: i64,
pub tv_nsec: i32,
} | pub const SYS_CLOSE: usize = 6;
pub const SYS_CLONE: usize = 120;
pub const CLONE_VM: usize = 0x100;
pub const CLONE_FS: usize = 0x200;
pub const CLONE_FILES: usize = 0x400; | random_line_split |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// Create a new decoder that decodes from the stream ```r```
pub fn new(r: R) -> JPEGDecoder<R> {
JPEGDecoder {
decoder: jpeg_decoder::Decoder::new(r),
metadata: None,
}
}
fn metadata(&mut self) -> ImageResult<jpeg_decoder::ImageInfo> {
match self.metadata {
Some(metadata) => Ok(metadata),
None => {
try!(self.decoder.read_info());
let mut metadata = self.decoder.info().unwrap();
// We convert CMYK data to RGB before returning it to the user.
if metadata.pixel_format == jpeg_decoder::PixelFormat::CMYK32 {
metadata.pixel_format = jpeg_decoder::PixelFormat::RGB24;
}
self.metadata = Some(metadata);
Ok(metadata)
},
}
}
}
impl<R: Read> ImageDecoder for JPEGDecoder<R> {
fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
let metadata = try!(self.metadata());
Ok((metadata.width as u32, metadata.height as u32))
}
fn colortype(&mut self) -> ImageResult<ColorType> {
let metadata = try!(self.metadata());
Ok(metadata.pixel_format.into())
}
fn row_len(&mut self) -> ImageResult<usize> {
let metadata = try!(self.metadata());
Ok(metadata.width as usize * color::num_components(metadata.pixel_format.into()))
}
fn read_scanline(&mut self, _buf: &mut [u8]) -> ImageResult<u32> {
unimplemented!();
}
fn read_image(&mut self) -> ImageResult<DecodingResult> { |
Ok(DecodingResult::U8(data))
}
}
fn cmyk_to_rgb(input: &[u8]) -> Vec<u8> {
let size = input.len() - input.len() / 4;
let mut output = Vec::with_capacity(size);
for pixel in input.chunks(4) {
let c = pixel[0] as f32 / 255.0;
let m = pixel[1] as f32 / 255.0;
let y = pixel[2] as f32 / 255.0;
let k = pixel[3] as f32 / 255.0;
// CMYK -> CMY
let c = c * (1.0 - k) + k;
let m = m * (1.0 - k) + k;
let y = y * (1.0 - k) + k;
// CMY -> RGB
let r = (1.0 - c) * 255.0;
let g = (1.0 - m) * 255.0;
let b = (1.0 - y) * 255.0;
output.push(r as u8);
output.push(g as u8);
output.push(b as u8);
}
output
}
impl From<jpeg_decoder::PixelFormat> for ColorType {
fn from(pixel_format: jpeg_decoder::PixelFormat) -> ColorType {
use self::jpeg_decoder::PixelFormat::*;
match pixel_format {
L8 => ColorType::Gray(8),
RGB24 => ColorType::RGB(8),
CMYK32 => panic!(),
}
}
}
impl From<jpeg_decoder::Error> for ImageError {
fn from(err: jpeg_decoder::Error) -> ImageError {
use self::jpeg_decoder::Error::*;
match err {
Format(desc) => ImageError::FormatError(desc),
Unsupported(desc) => ImageError::UnsupportedError(format!("{:?}", desc)),
Io(err) => ImageError::IoError(err),
Internal(err) => ImageError::FormatError(err.description().to_owned()),
}
}
} | let mut data = try!(self.decoder.decode());
data = match self.decoder.info().unwrap().pixel_format {
jpeg_decoder::PixelFormat::CMYK32 => cmyk_to_rgb(&data),
_ => data,
}; | random_line_split |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// Create a new decoder that decodes from the stream ```r```
pub fn new(r: R) -> JPEGDecoder<R> {
JPEGDecoder {
decoder: jpeg_decoder::Decoder::new(r),
metadata: None,
}
}
fn metadata(&mut self) -> ImageResult<jpeg_decoder::ImageInfo> {
match self.metadata {
Some(metadata) => Ok(metadata),
None => {
try!(self.decoder.read_info());
let mut metadata = self.decoder.info().unwrap();
// We convert CMYK data to RGB before returning it to the user.
if metadata.pixel_format == jpeg_decoder::PixelFormat::CMYK32 {
metadata.pixel_format = jpeg_decoder::PixelFormat::RGB24;
}
self.metadata = Some(metadata);
Ok(metadata)
},
}
}
}
impl<R: Read> ImageDecoder for JPEGDecoder<R> {
fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
let metadata = try!(self.metadata());
Ok((metadata.width as u32, metadata.height as u32))
}
fn colortype(&mut self) -> ImageResult<ColorType> {
let metadata = try!(self.metadata());
Ok(metadata.pixel_format.into())
}
fn row_len(&mut self) -> ImageResult<usize> |
fn read_scanline(&mut self, _buf: &mut [u8]) -> ImageResult<u32> {
unimplemented!();
}
fn read_image(&mut self) -> ImageResult<DecodingResult> {
let mut data = try!(self.decoder.decode());
data = match self.decoder.info().unwrap().pixel_format {
jpeg_decoder::PixelFormat::CMYK32 => cmyk_to_rgb(&data),
_ => data,
};
Ok(DecodingResult::U8(data))
}
}
fn cmyk_to_rgb(input: &[u8]) -> Vec<u8> {
let size = input.len() - input.len() / 4;
let mut output = Vec::with_capacity(size);
for pixel in input.chunks(4) {
let c = pixel[0] as f32 / 255.0;
let m = pixel[1] as f32 / 255.0;
let y = pixel[2] as f32 / 255.0;
let k = pixel[3] as f32 / 255.0;
// CMYK -> CMY
let c = c * (1.0 - k) + k;
let m = m * (1.0 - k) + k;
let y = y * (1.0 - k) + k;
// CMY -> RGB
let r = (1.0 - c) * 255.0;
let g = (1.0 - m) * 255.0;
let b = (1.0 - y) * 255.0;
output.push(r as u8);
output.push(g as u8);
output.push(b as u8);
}
output
}
impl From<jpeg_decoder::PixelFormat> for ColorType {
fn from(pixel_format: jpeg_decoder::PixelFormat) -> ColorType {
use self::jpeg_decoder::PixelFormat::*;
match pixel_format {
L8 => ColorType::Gray(8),
RGB24 => ColorType::RGB(8),
CMYK32 => panic!(),
}
}
}
impl From<jpeg_decoder::Error> for ImageError {
fn from(err: jpeg_decoder::Error) -> ImageError {
use self::jpeg_decoder::Error::*;
match err {
Format(desc) => ImageError::FormatError(desc),
Unsupported(desc) => ImageError::UnsupportedError(format!("{:?}", desc)),
Io(err) => ImageError::IoError(err),
Internal(err) => ImageError::FormatError(err.description().to_owned()),
}
}
}
| {
let metadata = try!(self.metadata());
Ok(metadata.width as usize * color::num_components(metadata.pixel_format.into()))
} | identifier_body |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// Create a new decoder that decodes from the stream ```r```
pub fn new(r: R) -> JPEGDecoder<R> {
JPEGDecoder {
decoder: jpeg_decoder::Decoder::new(r),
metadata: None,
}
}
fn metadata(&mut self) -> ImageResult<jpeg_decoder::ImageInfo> {
match self.metadata {
Some(metadata) => Ok(metadata),
None => {
try!(self.decoder.read_info());
let mut metadata = self.decoder.info().unwrap();
// We convert CMYK data to RGB before returning it to the user.
if metadata.pixel_format == jpeg_decoder::PixelFormat::CMYK32 {
metadata.pixel_format = jpeg_decoder::PixelFormat::RGB24;
}
self.metadata = Some(metadata);
Ok(metadata)
},
}
}
}
impl<R: Read> ImageDecoder for JPEGDecoder<R> {
fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
let metadata = try!(self.metadata());
Ok((metadata.width as u32, metadata.height as u32))
}
fn colortype(&mut self) -> ImageResult<ColorType> {
let metadata = try!(self.metadata());
Ok(metadata.pixel_format.into())
}
fn | (&mut self) -> ImageResult<usize> {
let metadata = try!(self.metadata());
Ok(metadata.width as usize * color::num_components(metadata.pixel_format.into()))
}
fn read_scanline(&mut self, _buf: &mut [u8]) -> ImageResult<u32> {
unimplemented!();
}
fn read_image(&mut self) -> ImageResult<DecodingResult> {
let mut data = try!(self.decoder.decode());
data = match self.decoder.info().unwrap().pixel_format {
jpeg_decoder::PixelFormat::CMYK32 => cmyk_to_rgb(&data),
_ => data,
};
Ok(DecodingResult::U8(data))
}
}
fn cmyk_to_rgb(input: &[u8]) -> Vec<u8> {
let size = input.len() - input.len() / 4;
let mut output = Vec::with_capacity(size);
for pixel in input.chunks(4) {
let c = pixel[0] as f32 / 255.0;
let m = pixel[1] as f32 / 255.0;
let y = pixel[2] as f32 / 255.0;
let k = pixel[3] as f32 / 255.0;
// CMYK -> CMY
let c = c * (1.0 - k) + k;
let m = m * (1.0 - k) + k;
let y = y * (1.0 - k) + k;
// CMY -> RGB
let r = (1.0 - c) * 255.0;
let g = (1.0 - m) * 255.0;
let b = (1.0 - y) * 255.0;
output.push(r as u8);
output.push(g as u8);
output.push(b as u8);
}
output
}
impl From<jpeg_decoder::PixelFormat> for ColorType {
fn from(pixel_format: jpeg_decoder::PixelFormat) -> ColorType {
use self::jpeg_decoder::PixelFormat::*;
match pixel_format {
L8 => ColorType::Gray(8),
RGB24 => ColorType::RGB(8),
CMYK32 => panic!(),
}
}
}
impl From<jpeg_decoder::Error> for ImageError {
fn from(err: jpeg_decoder::Error) -> ImageError {
use self::jpeg_decoder::Error::*;
match err {
Format(desc) => ImageError::FormatError(desc),
Unsupported(desc) => ImageError::UnsupportedError(format!("{:?}", desc)),
Io(err) => ImageError::IoError(err),
Internal(err) => ImageError::FormatError(err.description().to_owned()),
}
}
}
| row_len | identifier_name |
object-safety-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that we correctly prevent users from making trait objects
// from traits with generic methods, unless `where Self : Sized` is
// present.
trait Bar {
fn bar<T>(&self, t: T);
}
trait Quux {
fn bar<T>(&self, t: T)
where Self : Sized;
}
fn make_bar<T:Bar>(t: &T) -> &Bar {
t
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_bar_explicit<T:Bar>(t: &T) -> &Bar {
t as &Bar
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_quux<T:Quux>(t: &T) -> &Quux |
fn make_quux_explicit<T:Quux>(t: &T) -> &Quux {
t as &Quux
}
fn main() {
}
| {
t
} | identifier_body |
object-safety-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that we correctly prevent users from making trait objects
// from traits with generic methods, unless `where Self : Sized` is
// present.
trait Bar {
fn bar<T>(&self, t: T);
}
trait Quux {
fn bar<T>(&self, t: T)
where Self : Sized;
}
fn make_bar<T:Bar>(t: &T) -> &Bar {
t
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_bar_explicit<T:Bar>(t: &T) -> &Bar {
t as &Bar
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_quux<T:Quux>(t: &T) -> &Quux {
t
}
fn make_quux_explicit<T:Quux>(t: &T) -> &Quux {
t as &Quux
} | fn main() {
} | random_line_split |
|
object-safety-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that we correctly prevent users from making trait objects
// from traits with generic methods, unless `where Self : Sized` is
// present.
trait Bar {
fn bar<T>(&self, t: T);
}
trait Quux {
fn bar<T>(&self, t: T)
where Self : Sized;
}
fn make_bar<T:Bar>(t: &T) -> &Bar {
t
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_bar_explicit<T:Bar>(t: &T) -> &Bar {
t as &Bar
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn | <T:Quux>(t: &T) -> &Quux {
t
}
fn make_quux_explicit<T:Quux>(t: &T) -> &Quux {
t as &Quux
}
fn main() {
}
| make_quux | identifier_name |
game.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use dat::{EmpiresDb, EmpiresDbRef};
use media::{self, MediaRef};
use resource::{DrsManager, DrsManagerRef, GameDir, ShapeManager, ShapeManagerRef, ShapeMetadataStore,
ShapeMetadataStoreRef};
use super::state::GameState;
use time;
use types::Fixed;
const WINDOW_TITLE: &'static str = "OpenAOE";
const WINDOW_WIDTH: u32 = 1024;
const WINDOW_HEIGHT: u32 = 768;
pub struct Game {
game_dir: GameDir,
drs_manager: DrsManagerRef,
shape_manager: ShapeManagerRef,
shape_metadata: ShapeMetadataStoreRef,
empires: EmpiresDbRef,
media: MediaRef,
states: Vec<Box<GameState>>,
}
impl Game {
pub fn new(game_data_dir: &str) -> Game {
let game_dir = GameDir::new(game_data_dir).unwrap_or_else(|err| {
unrecoverable!("{}", err);
});
let drs_manager = DrsManager::new(&game_dir);
if let Err(err) = drs_manager.borrow_mut().preload() {
unrecoverable!("Failed to preload DRS archives: {}", err);
}
let shape_manager = ShapeManager::new(drs_manager.clone()).unwrap_or_else(|err| {
unrecoverable!("Failed to initialize the shape manager: {}", err);
});
let shape_metadata = ShapeMetadataStoreRef::new(ShapeMetadataStore::load(&*drs_manager.borrow()));
let empires_dat_location = game_dir.find_file("data/empires.dat").unwrap();
let empires = EmpiresDbRef::new(EmpiresDb::read_from_file(empires_dat_location)
.unwrap_or_else(|err| {
unrecoverable!("Failed to load empires.dat: {}", err);
}));
let media = media::create_media(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE).unwrap_or_else(|err| {
unrecoverable!("Failed to create media window: {}", err);
});
Game {
game_dir: game_dir,
drs_manager: drs_manager,
shape_manager: shape_manager,
shape_metadata: shape_metadata,
empires: empires,
media: media,
states: Vec::new(),
}
}
pub fn push_state(&mut self, mut state: Box<GameState>) {
if let Some(mut prev_state) = self.current_state() {
prev_state.stop();
}
state.start();
self.states.push(state);
}
pub fn game_loop(&mut self) {
let time_step_nanos = 1000000000 / 60u64;
let time_step_seconds = Fixed::from(1) / Fixed::from(60);
let mut accumulator: u64 = 0;
let mut last_time = time::precise_time_ns();
while self.media.borrow().is_open() {
self.media.borrow_mut().update();
self.media.borrow_mut().renderer().present();
let new_time = time::precise_time_ns();
accumulator += new_time - last_time;
last_time = new_time;
while accumulator >= time_step_nanos {
self.media.borrow_mut().update_input();
self.update(time_step_seconds);
accumulator -= time_step_nanos;
}
let lerp = Fixed::from(accumulator as f64 / time_step_nanos as f64);
if let Some(state) = self.current_state() {
state.render(lerp);
}
}
}
fn pop_state(&mut self) {
if let Some(state) = self.current_state() {
state.stop();
}
if!self.states.is_empty() {
self.states.pop();
}
}
fn update(&mut self, time_step: Fixed) -> bool {
let mut pop_required = false;
let result = if let Some(state) = self.current_state() {
if!state.update(time_step) {
pop_required = true;
false
} else {
true
}
} else {
false
};
if pop_required {
self.pop_state();
}
result
}
fn current_state<'a>(&'a mut self) -> Option<&'a mut GameState> {
if!self.states.is_empty() {
let index = self.states.len() - 1; // satisfy the borrow checker
Some(&mut *self.states[index])
} else {
None
}
}
pub fn game_dir<'a>(&'a self) -> &'a GameDir {
&self.game_dir
}
pub fn drs_manager(&self) -> DrsManagerRef {
self.drs_manager.clone()
}
pub fn | (&self) -> ShapeManagerRef {
self.shape_manager.clone()
}
pub fn shape_metadata(&self) -> ShapeMetadataStoreRef {
self.shape_metadata.clone()
}
pub fn empires_db(&self) -> EmpiresDbRef {
self.empires.clone()
}
pub fn media(&self) -> MediaRef {
self.media.clone()
}
}
| shape_manager | identifier_name |
game.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use dat::{EmpiresDb, EmpiresDbRef};
use media::{self, MediaRef};
use resource::{DrsManager, DrsManagerRef, GameDir, ShapeManager, ShapeManagerRef, ShapeMetadataStore,
ShapeMetadataStoreRef};
use super::state::GameState;
use time;
use types::Fixed;
const WINDOW_TITLE: &'static str = "OpenAOE";
const WINDOW_WIDTH: u32 = 1024;
const WINDOW_HEIGHT: u32 = 768;
pub struct Game {
game_dir: GameDir,
drs_manager: DrsManagerRef,
shape_manager: ShapeManagerRef,
shape_metadata: ShapeMetadataStoreRef,
empires: EmpiresDbRef,
media: MediaRef,
states: Vec<Box<GameState>>,
}
impl Game {
pub fn new(game_data_dir: &str) -> Game {
let game_dir = GameDir::new(game_data_dir).unwrap_or_else(|err| {
unrecoverable!("{}", err);
});
let drs_manager = DrsManager::new(&game_dir);
if let Err(err) = drs_manager.borrow_mut().preload() {
unrecoverable!("Failed to preload DRS archives: {}", err);
}
let shape_manager = ShapeManager::new(drs_manager.clone()).unwrap_or_else(|err| {
unrecoverable!("Failed to initialize the shape manager: {}", err);
});
let shape_metadata = ShapeMetadataStoreRef::new(ShapeMetadataStore::load(&*drs_manager.borrow()));
let empires_dat_location = game_dir.find_file("data/empires.dat").unwrap();
let empires = EmpiresDbRef::new(EmpiresDb::read_from_file(empires_dat_location)
.unwrap_or_else(|err| {
unrecoverable!("Failed to load empires.dat: {}", err);
}));
let media = media::create_media(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE).unwrap_or_else(|err| {
unrecoverable!("Failed to create media window: {}", err);
});
Game {
game_dir: game_dir,
drs_manager: drs_manager,
shape_manager: shape_manager,
shape_metadata: shape_metadata,
empires: empires,
media: media,
states: Vec::new(),
}
}
pub fn push_state(&mut self, mut state: Box<GameState>) {
if let Some(mut prev_state) = self.current_state() {
prev_state.stop();
}
state.start();
self.states.push(state);
}
pub fn game_loop(&mut self) {
let time_step_nanos = 1000000000 / 60u64;
let time_step_seconds = Fixed::from(1) / Fixed::from(60);
let mut accumulator: u64 = 0;
let mut last_time = time::precise_time_ns();
while self.media.borrow().is_open() {
self.media.borrow_mut().update();
self.media.borrow_mut().renderer().present();
let new_time = time::precise_time_ns();
accumulator += new_time - last_time;
last_time = new_time;
while accumulator >= time_step_nanos {
self.media.borrow_mut().update_input();
self.update(time_step_seconds);
accumulator -= time_step_nanos;
}
let lerp = Fixed::from(accumulator as f64 / time_step_nanos as f64);
if let Some(state) = self.current_state() {
state.render(lerp);
}
}
}
fn pop_state(&mut self) {
if let Some(state) = self.current_state() { | }
}
fn update(&mut self, time_step: Fixed) -> bool {
let mut pop_required = false;
let result = if let Some(state) = self.current_state() {
if!state.update(time_step) {
pop_required = true;
false
} else {
true
}
} else {
false
};
if pop_required {
self.pop_state();
}
result
}
fn current_state<'a>(&'a mut self) -> Option<&'a mut GameState> {
if!self.states.is_empty() {
let index = self.states.len() - 1; // satisfy the borrow checker
Some(&mut *self.states[index])
} else {
None
}
}
pub fn game_dir<'a>(&'a self) -> &'a GameDir {
&self.game_dir
}
pub fn drs_manager(&self) -> DrsManagerRef {
self.drs_manager.clone()
}
pub fn shape_manager(&self) -> ShapeManagerRef {
self.shape_manager.clone()
}
pub fn shape_metadata(&self) -> ShapeMetadataStoreRef {
self.shape_metadata.clone()
}
pub fn empires_db(&self) -> EmpiresDbRef {
self.empires.clone()
}
pub fn media(&self) -> MediaRef {
self.media.clone()
}
} | state.stop();
}
if !self.states.is_empty() {
self.states.pop(); | random_line_split |
game.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use dat::{EmpiresDb, EmpiresDbRef};
use media::{self, MediaRef};
use resource::{DrsManager, DrsManagerRef, GameDir, ShapeManager, ShapeManagerRef, ShapeMetadataStore,
ShapeMetadataStoreRef};
use super::state::GameState;
use time;
use types::Fixed;
const WINDOW_TITLE: &'static str = "OpenAOE";
const WINDOW_WIDTH: u32 = 1024;
const WINDOW_HEIGHT: u32 = 768;
pub struct Game {
game_dir: GameDir,
drs_manager: DrsManagerRef,
shape_manager: ShapeManagerRef,
shape_metadata: ShapeMetadataStoreRef,
empires: EmpiresDbRef,
media: MediaRef,
states: Vec<Box<GameState>>,
}
impl Game {
pub fn new(game_data_dir: &str) -> Game {
let game_dir = GameDir::new(game_data_dir).unwrap_or_else(|err| {
unrecoverable!("{}", err);
});
let drs_manager = DrsManager::new(&game_dir);
if let Err(err) = drs_manager.borrow_mut().preload() {
unrecoverable!("Failed to preload DRS archives: {}", err);
}
let shape_manager = ShapeManager::new(drs_manager.clone()).unwrap_or_else(|err| {
unrecoverable!("Failed to initialize the shape manager: {}", err);
});
let shape_metadata = ShapeMetadataStoreRef::new(ShapeMetadataStore::load(&*drs_manager.borrow()));
let empires_dat_location = game_dir.find_file("data/empires.dat").unwrap();
let empires = EmpiresDbRef::new(EmpiresDb::read_from_file(empires_dat_location)
.unwrap_or_else(|err| {
unrecoverable!("Failed to load empires.dat: {}", err);
}));
let media = media::create_media(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE).unwrap_or_else(|err| {
unrecoverable!("Failed to create media window: {}", err);
});
Game {
game_dir: game_dir,
drs_manager: drs_manager,
shape_manager: shape_manager,
shape_metadata: shape_metadata,
empires: empires,
media: media,
states: Vec::new(),
}
}
pub fn push_state(&mut self, mut state: Box<GameState>) {
if let Some(mut prev_state) = self.current_state() {
prev_state.stop();
}
state.start();
self.states.push(state);
}
pub fn game_loop(&mut self) {
let time_step_nanos = 1000000000 / 60u64;
let time_step_seconds = Fixed::from(1) / Fixed::from(60);
let mut accumulator: u64 = 0;
let mut last_time = time::precise_time_ns();
while self.media.borrow().is_open() {
self.media.borrow_mut().update();
self.media.borrow_mut().renderer().present();
let new_time = time::precise_time_ns();
accumulator += new_time - last_time;
last_time = new_time;
while accumulator >= time_step_nanos {
self.media.borrow_mut().update_input();
self.update(time_step_seconds);
accumulator -= time_step_nanos;
}
let lerp = Fixed::from(accumulator as f64 / time_step_nanos as f64);
if let Some(state) = self.current_state() {
state.render(lerp);
}
}
}
fn pop_state(&mut self) {
if let Some(state) = self.current_state() {
state.stop();
}
if!self.states.is_empty() {
self.states.pop();
}
}
fn update(&mut self, time_step: Fixed) -> bool {
let mut pop_required = false;
let result = if let Some(state) = self.current_state() {
if!state.update(time_step) {
pop_required = true;
false
} else {
true
}
} else {
false
};
if pop_required {
self.pop_state();
}
result
}
fn current_state<'a>(&'a mut self) -> Option<&'a mut GameState> {
if!self.states.is_empty() {
let index = self.states.len() - 1; // satisfy the borrow checker
Some(&mut *self.states[index])
} else {
None
}
}
pub fn game_dir<'a>(&'a self) -> &'a GameDir {
&self.game_dir
}
pub fn drs_manager(&self) -> DrsManagerRef |
pub fn shape_manager(&self) -> ShapeManagerRef {
self.shape_manager.clone()
}
pub fn shape_metadata(&self) -> ShapeMetadataStoreRef {
self.shape_metadata.clone()
}
pub fn empires_db(&self) -> EmpiresDbRef {
self.empires.clone()
}
pub fn media(&self) -> MediaRef {
self.media.clone()
}
}
| {
self.drs_manager.clone()
} | identifier_body |
game.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use dat::{EmpiresDb, EmpiresDbRef};
use media::{self, MediaRef};
use resource::{DrsManager, DrsManagerRef, GameDir, ShapeManager, ShapeManagerRef, ShapeMetadataStore,
ShapeMetadataStoreRef};
use super::state::GameState;
use time;
use types::Fixed;
const WINDOW_TITLE: &'static str = "OpenAOE";
const WINDOW_WIDTH: u32 = 1024;
const WINDOW_HEIGHT: u32 = 768;
pub struct Game {
game_dir: GameDir,
drs_manager: DrsManagerRef,
shape_manager: ShapeManagerRef,
shape_metadata: ShapeMetadataStoreRef,
empires: EmpiresDbRef,
media: MediaRef,
states: Vec<Box<GameState>>,
}
impl Game {
pub fn new(game_data_dir: &str) -> Game {
let game_dir = GameDir::new(game_data_dir).unwrap_or_else(|err| {
unrecoverable!("{}", err);
});
let drs_manager = DrsManager::new(&game_dir);
if let Err(err) = drs_manager.borrow_mut().preload() {
unrecoverable!("Failed to preload DRS archives: {}", err);
}
let shape_manager = ShapeManager::new(drs_manager.clone()).unwrap_or_else(|err| {
unrecoverable!("Failed to initialize the shape manager: {}", err);
});
let shape_metadata = ShapeMetadataStoreRef::new(ShapeMetadataStore::load(&*drs_manager.borrow()));
let empires_dat_location = game_dir.find_file("data/empires.dat").unwrap();
let empires = EmpiresDbRef::new(EmpiresDb::read_from_file(empires_dat_location)
.unwrap_or_else(|err| {
unrecoverable!("Failed to load empires.dat: {}", err);
}));
let media = media::create_media(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE).unwrap_or_else(|err| {
unrecoverable!("Failed to create media window: {}", err);
});
Game {
game_dir: game_dir,
drs_manager: drs_manager,
shape_manager: shape_manager,
shape_metadata: shape_metadata,
empires: empires,
media: media,
states: Vec::new(),
}
}
pub fn push_state(&mut self, mut state: Box<GameState>) {
if let Some(mut prev_state) = self.current_state() {
prev_state.stop();
}
state.start();
self.states.push(state);
}
pub fn game_loop(&mut self) {
let time_step_nanos = 1000000000 / 60u64;
let time_step_seconds = Fixed::from(1) / Fixed::from(60);
let mut accumulator: u64 = 0;
let mut last_time = time::precise_time_ns();
while self.media.borrow().is_open() {
self.media.borrow_mut().update();
self.media.borrow_mut().renderer().present();
let new_time = time::precise_time_ns();
accumulator += new_time - last_time;
last_time = new_time;
while accumulator >= time_step_nanos {
self.media.borrow_mut().update_input();
self.update(time_step_seconds);
accumulator -= time_step_nanos;
}
let lerp = Fixed::from(accumulator as f64 / time_step_nanos as f64);
if let Some(state) = self.current_state() {
state.render(lerp);
}
}
}
fn pop_state(&mut self) {
if let Some(state) = self.current_state() {
state.stop();
}
if!self.states.is_empty() |
}
fn update(&mut self, time_step: Fixed) -> bool {
let mut pop_required = false;
let result = if let Some(state) = self.current_state() {
if!state.update(time_step) {
pop_required = true;
false
} else {
true
}
} else {
false
};
if pop_required {
self.pop_state();
}
result
}
fn current_state<'a>(&'a mut self) -> Option<&'a mut GameState> {
if!self.states.is_empty() {
let index = self.states.len() - 1; // satisfy the borrow checker
Some(&mut *self.states[index])
} else {
None
}
}
pub fn game_dir<'a>(&'a self) -> &'a GameDir {
&self.game_dir
}
pub fn drs_manager(&self) -> DrsManagerRef {
self.drs_manager.clone()
}
pub fn shape_manager(&self) -> ShapeManagerRef {
self.shape_manager.clone()
}
pub fn shape_metadata(&self) -> ShapeMetadataStoreRef {
self.shape_metadata.clone()
}
pub fn empires_db(&self) -> EmpiresDbRef {
self.empires.clone()
}
pub fn media(&self) -> MediaRef {
self.media.clone()
}
}
| {
self.states.pop();
} | conditional_block |
regions-static-closure.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // 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 closure_box<'a> {
cl: 'a ||,
}
fn box_it<'r>(x: 'r ||) -> closure_box<'r> {
closure_box {cl: x}
}
fn call_static_closure(cl: closure_box<'static>) {
(cl.cl)();
}
pub fn main() {
let cl_box = box_it(|| println!("Hello, world!"));
call_static_closure(cl_box);
} | // 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 | random_line_split |
regions-static-closure.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 closure_box<'a> {
cl: 'a ||,
}
fn box_it<'r>(x: 'r ||) -> closure_box<'r> {
closure_box {cl: x}
}
fn call_static_closure(cl: closure_box<'static>) {
(cl.cl)();
}
pub fn | () {
let cl_box = box_it(|| println!("Hello, world!"));
call_static_closure(cl_box);
}
| main | identifier_name |
lib.rs | #![feature(unboxed_closures)]
extern crate libc;
macro_rules! assert_enum {
(@as_expr $e:expr) => {$e};
(@as_pat $p:pat) => {$p};
($left:expr, $($right:tt)*) => (
{
match &($left) {
assert_enum!(@as_pat &$($right)*(..)) => {},
_ => {
panic!("assertion failed: `(if let left = right(..))` \
(left: `{:?}`, right: `{:?}`)",
$left,
stringify!($($right)*)
)
}
}
}
)
}
pub mod ffi;
pub mod stack;
pub mod collections;
mod context;
mod value;
mod borrow;
mod function;
pub use context::*;
pub use collections::*;
pub use value::*;
pub use borrow::*;
pub use function::*;
pub struct | ;
#[macro_export]
macro_rules! push {
($cxt:expr, $($arg:expr),*) => (
$(
$cxt.push($arg);
)*
)
}
| nil | identifier_name |
lib.rs | #![feature(unboxed_closures)]
extern crate libc;
macro_rules! assert_enum {
(@as_expr $e:expr) => {$e};
(@as_pat $p:pat) => {$p};
($left:expr, $($right:tt)*) => (
{
match &($left) {
assert_enum!(@as_pat &$($right)*(..)) => {},
_ => {
panic!("assertion failed: `(if let left = right(..))` \
(left: `{:?}`, right: `{:?}`)",
$left,
stringify!($($right)*)
)
}
}
}
)
}
pub mod ffi;
pub mod stack;
pub mod collections;
mod context;
mod value; | pub use context::*;
pub use collections::*;
pub use value::*;
pub use borrow::*;
pub use function::*;
pub struct nil;
#[macro_export]
macro_rules! push {
($cxt:expr, $($arg:expr),*) => (
$(
$cxt.push($arg);
)*
)
} | mod borrow;
mod function;
| random_line_split |
issue-50706.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-pass
pub struct Stats;
#[derive(PartialEq, Eq)]
pub struct StatVariant {
pub id: u8,
_priv: (),
}
#[derive(PartialEq, Eq)]
pub struct Stat {
pub variant: StatVariant,
pub index: usize,
_priv: (),
}
impl Stats {
pub const TEST: StatVariant = StatVariant{id: 0, _priv: (),};
#[allow(non_upper_case_globals)]
pub const A: Stat = Stat{
variant: Self::TEST,
index: 0,
_priv: (),};
}
impl Stat {
pub fn from_index(variant: StatVariant, index: usize) -> Option<Stat> {
let stat = Stat{variant, index, _priv: (),}; | match stat {
Stats::A => Some(Stats::A),
_ => None,
}
}
}
fn main() {} | random_line_split |
|
issue-50706.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-pass
pub struct | ;
#[derive(PartialEq, Eq)]
pub struct StatVariant {
pub id: u8,
_priv: (),
}
#[derive(PartialEq, Eq)]
pub struct Stat {
pub variant: StatVariant,
pub index: usize,
_priv: (),
}
impl Stats {
pub const TEST: StatVariant = StatVariant{id: 0, _priv: (),};
#[allow(non_upper_case_globals)]
pub const A: Stat = Stat{
variant: Self::TEST,
index: 0,
_priv: (),};
}
impl Stat {
pub fn from_index(variant: StatVariant, index: usize) -> Option<Stat> {
let stat = Stat{variant, index, _priv: (),};
match stat {
Stats::A => Some(Stats::A),
_ => None,
}
}
}
fn main() {}
| Stats | identifier_name |
main.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate hoedown;
extern crate rayon;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;
extern crate inflector;
#[macro_use]
extern crate lazy_static;
extern crate regex;
#[macro_use]
extern crate log;
extern crate env_logger;
mod botocore;
mod cargo;
mod commands;
mod config;
mod service;
mod util;
mod doco;
use std::path::Path;
use clap::{Arg, App, SubCommand};
use service::Service;
use config::ServiceConfig;
use botocore::ServiceDefinition;
fn main() {
let matches = App::new("Rusoto Service Crate Generator")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(SubCommand::with_name("check")
.arg(Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true)))
.subcommand(SubCommand::with_name("generate")
.arg(Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true))
.arg(Arg::with_name("out_dir")
.long("outdir")
.short("o")
.takes_value(true)
.required(true)))
.get_matches();
if let Some(matches) = matches.subcommand_matches("check") |
if let Some(matches) = matches.subcommand_matches("generate") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file.");
let out_dir = Path::new(matches.value_of("out_dir").unwrap());
commands::generate::generate_services(&service_configs, out_dir);
}
}
| {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file.");
commands::check::check(service_configs);
} | conditional_block |
main.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate hoedown;
extern crate rayon;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;
extern crate inflector;
#[macro_use]
extern crate lazy_static;
extern crate regex;
#[macro_use]
extern crate log;
extern crate env_logger;
mod botocore;
mod cargo;
mod commands;
mod config;
mod service; | use clap::{Arg, App, SubCommand};
use service::Service;
use config::ServiceConfig;
use botocore::ServiceDefinition;
fn main() {
let matches = App::new("Rusoto Service Crate Generator")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(SubCommand::with_name("check")
.arg(Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true)))
.subcommand(SubCommand::with_name("generate")
.arg(Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true))
.arg(Arg::with_name("out_dir")
.long("outdir")
.short("o")
.takes_value(true)
.required(true)))
.get_matches();
if let Some(matches) = matches.subcommand_matches("check") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file.");
commands::check::check(service_configs);
}
if let Some(matches) = matches.subcommand_matches("generate") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file.");
let out_dir = Path::new(matches.value_of("out_dir").unwrap());
commands::generate::generate_services(&service_configs, out_dir);
}
} | mod util;
mod doco;
use std::path::Path;
| random_line_split |
main.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate hoedown;
extern crate rayon;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;
extern crate inflector;
#[macro_use]
extern crate lazy_static;
extern crate regex;
#[macro_use]
extern crate log;
extern crate env_logger;
mod botocore;
mod cargo;
mod commands;
mod config;
mod service;
mod util;
mod doco;
use std::path::Path;
use clap::{Arg, App, SubCommand};
use service::Service;
use config::ServiceConfig;
use botocore::ServiceDefinition;
fn main() | .get_matches();
if let Some(matches) = matches.subcommand_matches("check") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file.");
commands::check::check(service_configs);
}
if let Some(matches) = matches.subcommand_matches("generate") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file.");
let out_dir = Path::new(matches.value_of("out_dir").unwrap());
commands::generate::generate_services(&service_configs, out_dir);
}
}
| {
let matches = App::new("Rusoto Service Crate Generator")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(SubCommand::with_name("check")
.arg(Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true)))
.subcommand(SubCommand::with_name("generate")
.arg(Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true))
.arg(Arg::with_name("out_dir")
.long("outdir")
.short("o")
.takes_value(true)
.required(true))) | identifier_body |
main.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate hoedown;
extern crate rayon;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;
extern crate inflector;
#[macro_use]
extern crate lazy_static;
extern crate regex;
#[macro_use]
extern crate log;
extern crate env_logger;
mod botocore;
mod cargo;
mod commands;
mod config;
mod service;
mod util;
mod doco;
use std::path::Path;
use clap::{Arg, App, SubCommand};
use service::Service;
use config::ServiceConfig;
use botocore::ServiceDefinition;
fn | () {
let matches = App::new("Rusoto Service Crate Generator")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(SubCommand::with_name("check")
.arg(Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true)))
.subcommand(SubCommand::with_name("generate")
.arg(Arg::with_name("services_config")
.long("config")
.short("c")
.takes_value(true))
.arg(Arg::with_name("out_dir")
.long("outdir")
.short("o")
.takes_value(true)
.required(true)))
.get_matches();
if let Some(matches) = matches.subcommand_matches("check") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file.");
commands::check::check(service_configs);
}
if let Some(matches) = matches.subcommand_matches("generate") {
let services_config_path = matches.value_of("services_config").unwrap();
let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file.");
let out_dir = Path::new(matches.value_of("out_dir").unwrap());
commands::generate::generate_services(&service_configs, out_dir);
}
}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.