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 |
---|---|---|---|---|
cursor.rs
|
//! Cursor movement.
use std::fmt;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor.", Show, "?25h");
derive_csi_sequence!("Restore the cursor.", Restore, "u");
derive_csi_sequence!("Save the cursor.", Save, "s");
/// Goto some position ((1,1)-based).
///
/// # Why one-based?
///
/// ANSI escapes are very poorly designed, and one of the many odd aspects is being one-based. This
/// can be quite strange at first, but it is not that big of an obstruction once you get used to
/// it.
///
/// # Example
///
/// ```rust
/// extern crate termion;
///
/// fn main() {
/// print!("{}{}Stuff", termion::clear::All, termion::cursor::Goto(5, 3));
/// }
/// ```
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Goto(pub u16, pub u16);
impl Default for Goto {
fn default() -> Goto {
Goto(1, 1)
}
}
impl fmt::Display for Goto {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self!= &Goto(0, 0), "Goto is one-based.");
write!(f, csi!("{};{}H"), self.1, self.0)
}
}
/// Move cursor left.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Left(pub u16);
impl fmt::Display for Left {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}D"), self.0)
}
}
/// Move cursor right.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Right(pub u16);
impl fmt::Display for Right {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}C"), self.0)
|
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Up(pub u16);
impl fmt::Display for Up {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}A"), self.0)
}
}
/// Move cursor down.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Down(pub u16);
impl fmt::Display for Down {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}B"), self.0)
}
}
/// Types that allow detection of the cursor position.
pub trait DetectCursorPos {
/// Get the (1,1)-based cursor position from the terminal.
fn cursor_pos(&mut self) -> io::Result<(u16, u16)>;
}
impl<W: Write> DetectCursorPos for W {
fn cursor_pos(&mut self) -> io::Result<(u16, u16)> {
let mut stdin = async_stdin();
// Where is the cursor?
// Use `ESC [ 6 n`.
write!(self, "\x1B[6n")?;
self.flush()?;
let mut buf: [u8; 1] = [0];
let mut read_chars = Vec::new();
let timeout = Duration::from_millis(CONTROL_SEQUENCE_TIMEOUT);
let now = SystemTime::now();
// Either consume all data up to R or wait for a timeout.
while buf[0]!= b'R' && now.elapsed().unwrap() < timeout {
if stdin.read(&mut buf)? > 0 {
read_chars.push(buf[0]);
}
}
if read_chars.len() == 0 {
return Err(Error::new(ErrorKind::Other, "Cursor position detection timed out."));
}
// The answer will look like `ESC [ Cy ; Cx R`.
read_chars.pop(); // remove trailing R.
let read_str = String::from_utf8(read_chars).unwrap();
let beg = read_str.rfind('[').unwrap();
let coords: String = read_str.chars().skip(beg + 1).collect();
let mut nums = coords.split(';');
let cy = nums.next()
.unwrap()
.parse::<u16>()
.unwrap();
let cx = nums.next()
.unwrap()
.parse::<u16>()
.unwrap();
Ok((cx, cy))
}
}
|
}
}
/// Move cursor up.
|
random_line_split
|
cursor.rs
|
//! Cursor movement.
use std::fmt;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor.", Show, "?25h");
derive_csi_sequence!("Restore the cursor.", Restore, "u");
derive_csi_sequence!("Save the cursor.", Save, "s");
/// Goto some position ((1,1)-based).
///
/// # Why one-based?
///
/// ANSI escapes are very poorly designed, and one of the many odd aspects is being one-based. This
/// can be quite strange at first, but it is not that big of an obstruction once you get used to
/// it.
///
/// # Example
///
/// ```rust
/// extern crate termion;
///
/// fn main() {
/// print!("{}{}Stuff", termion::clear::All, termion::cursor::Goto(5, 3));
/// }
/// ```
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Goto(pub u16, pub u16);
impl Default for Goto {
fn default() -> Goto {
Goto(1, 1)
}
}
impl fmt::Display for Goto {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self!= &Goto(0, 0), "Goto is one-based.");
write!(f, csi!("{};{}H"), self.1, self.0)
}
}
/// Move cursor left.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Left(pub u16);
impl fmt::Display for Left {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}D"), self.0)
}
}
/// Move cursor right.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct
|
(pub u16);
impl fmt::Display for Right {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}C"), self.0)
}
}
/// Move cursor up.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Up(pub u16);
impl fmt::Display for Up {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}A"), self.0)
}
}
/// Move cursor down.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Down(pub u16);
impl fmt::Display for Down {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}B"), self.0)
}
}
/// Types that allow detection of the cursor position.
pub trait DetectCursorPos {
/// Get the (1,1)-based cursor position from the terminal.
fn cursor_pos(&mut self) -> io::Result<(u16, u16)>;
}
impl<W: Write> DetectCursorPos for W {
fn cursor_pos(&mut self) -> io::Result<(u16, u16)> {
let mut stdin = async_stdin();
// Where is the cursor?
// Use `ESC [ 6 n`.
write!(self, "\x1B[6n")?;
self.flush()?;
let mut buf: [u8; 1] = [0];
let mut read_chars = Vec::new();
let timeout = Duration::from_millis(CONTROL_SEQUENCE_TIMEOUT);
let now = SystemTime::now();
// Either consume all data up to R or wait for a timeout.
while buf[0]!= b'R' && now.elapsed().unwrap() < timeout {
if stdin.read(&mut buf)? > 0 {
read_chars.push(buf[0]);
}
}
if read_chars.len() == 0 {
return Err(Error::new(ErrorKind::Other, "Cursor position detection timed out."));
}
// The answer will look like `ESC [ Cy ; Cx R`.
read_chars.pop(); // remove trailing R.
let read_str = String::from_utf8(read_chars).unwrap();
let beg = read_str.rfind('[').unwrap();
let coords: String = read_str.chars().skip(beg + 1).collect();
let mut nums = coords.split(';');
let cy = nums.next()
.unwrap()
.parse::<u16>()
.unwrap();
let cx = nums.next()
.unwrap()
.parse::<u16>()
.unwrap();
Ok((cx, cy))
}
}
|
Right
|
identifier_name
|
cursor.rs
|
//! Cursor movement.
use std::fmt;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor.", Show, "?25h");
derive_csi_sequence!("Restore the cursor.", Restore, "u");
derive_csi_sequence!("Save the cursor.", Save, "s");
/// Goto some position ((1,1)-based).
///
/// # Why one-based?
///
/// ANSI escapes are very poorly designed, and one of the many odd aspects is being one-based. This
/// can be quite strange at first, but it is not that big of an obstruction once you get used to
/// it.
///
/// # Example
///
/// ```rust
/// extern crate termion;
///
/// fn main() {
/// print!("{}{}Stuff", termion::clear::All, termion::cursor::Goto(5, 3));
/// }
/// ```
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Goto(pub u16, pub u16);
impl Default for Goto {
fn default() -> Goto {
Goto(1, 1)
}
}
impl fmt::Display for Goto {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self!= &Goto(0, 0), "Goto is one-based.");
write!(f, csi!("{};{}H"), self.1, self.0)
}
}
/// Move cursor left.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Left(pub u16);
impl fmt::Display for Left {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}D"), self.0)
}
}
/// Move cursor right.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Right(pub u16);
impl fmt::Display for Right {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}C"), self.0)
}
}
/// Move cursor up.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Up(pub u16);
impl fmt::Display for Up {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}A"), self.0)
}
}
/// Move cursor down.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Down(pub u16);
impl fmt::Display for Down {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
|
}
/// Types that allow detection of the cursor position.
pub trait DetectCursorPos {
/// Get the (1,1)-based cursor position from the terminal.
fn cursor_pos(&mut self) -> io::Result<(u16, u16)>;
}
impl<W: Write> DetectCursorPos for W {
fn cursor_pos(&mut self) -> io::Result<(u16, u16)> {
let mut stdin = async_stdin();
// Where is the cursor?
// Use `ESC [ 6 n`.
write!(self, "\x1B[6n")?;
self.flush()?;
let mut buf: [u8; 1] = [0];
let mut read_chars = Vec::new();
let timeout = Duration::from_millis(CONTROL_SEQUENCE_TIMEOUT);
let now = SystemTime::now();
// Either consume all data up to R or wait for a timeout.
while buf[0]!= b'R' && now.elapsed().unwrap() < timeout {
if stdin.read(&mut buf)? > 0 {
read_chars.push(buf[0]);
}
}
if read_chars.len() == 0 {
return Err(Error::new(ErrorKind::Other, "Cursor position detection timed out."));
}
// The answer will look like `ESC [ Cy ; Cx R`.
read_chars.pop(); // remove trailing R.
let read_str = String::from_utf8(read_chars).unwrap();
let beg = read_str.rfind('[').unwrap();
let coords: String = read_str.chars().skip(beg + 1).collect();
let mut nums = coords.split(';');
let cy = nums.next()
.unwrap()
.parse::<u16>()
.unwrap();
let cx = nums.next()
.unwrap()
.parse::<u16>()
.unwrap();
Ok((cx, cy))
}
}
|
{
write!(f, csi!("{}B"), self.0)
}
|
identifier_body
|
cursor.rs
|
//! Cursor movement.
use std::fmt;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor.", Show, "?25h");
derive_csi_sequence!("Restore the cursor.", Restore, "u");
derive_csi_sequence!("Save the cursor.", Save, "s");
/// Goto some position ((1,1)-based).
///
/// # Why one-based?
///
/// ANSI escapes are very poorly designed, and one of the many odd aspects is being one-based. This
/// can be quite strange at first, but it is not that big of an obstruction once you get used to
/// it.
///
/// # Example
///
/// ```rust
/// extern crate termion;
///
/// fn main() {
/// print!("{}{}Stuff", termion::clear::All, termion::cursor::Goto(5, 3));
/// }
/// ```
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Goto(pub u16, pub u16);
impl Default for Goto {
fn default() -> Goto {
Goto(1, 1)
}
}
impl fmt::Display for Goto {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self!= &Goto(0, 0), "Goto is one-based.");
write!(f, csi!("{};{}H"), self.1, self.0)
}
}
/// Move cursor left.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Left(pub u16);
impl fmt::Display for Left {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}D"), self.0)
}
}
/// Move cursor right.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Right(pub u16);
impl fmt::Display for Right {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}C"), self.0)
}
}
/// Move cursor up.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Up(pub u16);
impl fmt::Display for Up {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}A"), self.0)
}
}
/// Move cursor down.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Down(pub u16);
impl fmt::Display for Down {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}B"), self.0)
}
}
/// Types that allow detection of the cursor position.
pub trait DetectCursorPos {
/// Get the (1,1)-based cursor position from the terminal.
fn cursor_pos(&mut self) -> io::Result<(u16, u16)>;
}
impl<W: Write> DetectCursorPos for W {
fn cursor_pos(&mut self) -> io::Result<(u16, u16)> {
let mut stdin = async_stdin();
// Where is the cursor?
// Use `ESC [ 6 n`.
write!(self, "\x1B[6n")?;
self.flush()?;
let mut buf: [u8; 1] = [0];
let mut read_chars = Vec::new();
let timeout = Duration::from_millis(CONTROL_SEQUENCE_TIMEOUT);
let now = SystemTime::now();
// Either consume all data up to R or wait for a timeout.
while buf[0]!= b'R' && now.elapsed().unwrap() < timeout {
if stdin.read(&mut buf)? > 0
|
}
if read_chars.len() == 0 {
return Err(Error::new(ErrorKind::Other, "Cursor position detection timed out."));
}
// The answer will look like `ESC [ Cy ; Cx R`.
read_chars.pop(); // remove trailing R.
let read_str = String::from_utf8(read_chars).unwrap();
let beg = read_str.rfind('[').unwrap();
let coords: String = read_str.chars().skip(beg + 1).collect();
let mut nums = coords.split(';');
let cy = nums.next()
.unwrap()
.parse::<u16>()
.unwrap();
let cx = nums.next()
.unwrap()
.parse::<u16>()
.unwrap();
Ok((cx, cy))
}
}
|
{
read_chars.push(buf[0]);
}
|
conditional_block
|
union-abi.rs
|
// ignore-emscripten vectors passed directly
// compile-flags: -C no-prepopulate-passes
// This test that using union forward the abi of the inner type, as
// discussed in #54668
#![crate_type="lib"]
#![feature(repr_simd)]
#[derive(Copy, Clone)]
pub enum Unhab {}
#[repr(simd)]
#[derive(Copy, Clone)]
pub struct i64x4(i64, i64, i64, i64);
#[derive(Copy, Clone)]
pub union UnionI64x4{ a:(), b: i64x4 }
// CHECK: define void @test_UnionI64x4(<4 x i64>* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4(_: UnionI64x4) { loop {} }
pub union UnionI64x4_{ a: i64x4, b: (), c:i64x4, d: Unhab, e: ((),()), f: UnionI64x4 }
// CHECK: define void @test_UnionI64x4_(<4 x i64>* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4_(_: UnionI64x4_) { loop {} }
pub union UnionI64x4I64{ a: i64x4, b: i64 }
// CHECK: define void @test_UnionI64x4I64(%UnionI64x4I64* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4I64(_: UnionI64x4I64) { loop {} }
pub union UnionI64x4Tuple{ a: i64x4, b: (i64, i64, i64, i64) }
// CHECK: define void @test_UnionI64x4Tuple(%UnionI64x4Tuple* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4Tuple(_: UnionI64x4Tuple)
|
pub union UnionF32{a:f32}
// CHECK: define float @test_UnionF32(float %_1)
#[no_mangle]
pub fn test_UnionF32(_: UnionF32) -> UnionF32 { loop {} }
pub union UnionF32F32{a:f32, b:f32}
// CHECK: define float @test_UnionF32F32(float %_1)
#[no_mangle]
pub fn test_UnionF32F32(_: UnionF32F32) -> UnionF32F32 { loop {} }
pub union UnionF32U32{a:f32, b:u32}
// CHECK: define i32 @test_UnionF32U32(i32{{( %0)?}})
#[no_mangle]
pub fn test_UnionF32U32(_: UnionF32U32) -> UnionF32U32 { loop {} }
pub union UnionU128{a:u128}
// CHECK: define i128 @test_UnionU128(i128 %_1)
#[no_mangle]
pub fn test_UnionU128(_: UnionU128) -> UnionU128 { loop {} }
pub union UnionU128x2{a:(u128, u128)}
// CHECK: define void @test_UnionU128x2(i128 %_1.0, i128 %_1.1)
#[no_mangle]
pub fn test_UnionU128x2(_: UnionU128x2) { loop {} }
#[repr(C)]
pub union CUnionU128x2{a:(u128, u128)}
// CHECK: define void @test_CUnionU128x2(%CUnionU128x2* {{.*}} %_1)
#[no_mangle]
pub fn test_CUnionU128x2(_: CUnionU128x2) { loop {} }
pub union UnionBool { b:bool }
// CHECK: define zeroext i1 @test_UnionBool(i8 %b)
#[no_mangle]
pub fn test_UnionBool(b: UnionBool) -> bool { unsafe { b.b } }
// CHECK: %0 = trunc i8 %b to i1
|
{ loop {} }
|
identifier_body
|
union-abi.rs
|
// ignore-emscripten vectors passed directly
// compile-flags: -C no-prepopulate-passes
// This test that using union forward the abi of the inner type, as
// discussed in #54668
#![crate_type="lib"]
#![feature(repr_simd)]
#[derive(Copy, Clone)]
pub enum Unhab {}
#[repr(simd)]
#[derive(Copy, Clone)]
pub struct i64x4(i64, i64, i64, i64);
#[derive(Copy, Clone)]
pub union UnionI64x4{ a:(), b: i64x4 }
// CHECK: define void @test_UnionI64x4(<4 x i64>* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4(_: UnionI64x4) { loop {} }
pub union UnionI64x4_{ a: i64x4, b: (), c:i64x4, d: Unhab, e: ((),()), f: UnionI64x4 }
// CHECK: define void @test_UnionI64x4_(<4 x i64>* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4_(_: UnionI64x4_) { loop {} }
pub union UnionI64x4I64{ a: i64x4, b: i64 }
// CHECK: define void @test_UnionI64x4I64(%UnionI64x4I64* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4I64(_: UnionI64x4I64) { loop {} }
pub union UnionI64x4Tuple{ a: i64x4, b: (i64, i64, i64, i64) }
// CHECK: define void @test_UnionI64x4Tuple(%UnionI64x4Tuple* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4Tuple(_: UnionI64x4Tuple) { loop {} }
pub union UnionF32{a:f32}
// CHECK: define float @test_UnionF32(float %_1)
#[no_mangle]
pub fn test_UnionF32(_: UnionF32) -> UnionF32 { loop {} }
pub union UnionF32F32{a:f32, b:f32}
// CHECK: define float @test_UnionF32F32(float %_1)
|
pub union UnionF32U32{a:f32, b:u32}
// CHECK: define i32 @test_UnionF32U32(i32{{( %0)?}})
#[no_mangle]
pub fn test_UnionF32U32(_: UnionF32U32) -> UnionF32U32 { loop {} }
pub union UnionU128{a:u128}
// CHECK: define i128 @test_UnionU128(i128 %_1)
#[no_mangle]
pub fn test_UnionU128(_: UnionU128) -> UnionU128 { loop {} }
pub union UnionU128x2{a:(u128, u128)}
// CHECK: define void @test_UnionU128x2(i128 %_1.0, i128 %_1.1)
#[no_mangle]
pub fn test_UnionU128x2(_: UnionU128x2) { loop {} }
#[repr(C)]
pub union CUnionU128x2{a:(u128, u128)}
// CHECK: define void @test_CUnionU128x2(%CUnionU128x2* {{.*}} %_1)
#[no_mangle]
pub fn test_CUnionU128x2(_: CUnionU128x2) { loop {} }
pub union UnionBool { b:bool }
// CHECK: define zeroext i1 @test_UnionBool(i8 %b)
#[no_mangle]
pub fn test_UnionBool(b: UnionBool) -> bool { unsafe { b.b } }
// CHECK: %0 = trunc i8 %b to i1
|
#[no_mangle]
pub fn test_UnionF32F32(_: UnionF32F32) -> UnionF32F32 { loop {} }
|
random_line_split
|
union-abi.rs
|
// ignore-emscripten vectors passed directly
// compile-flags: -C no-prepopulate-passes
// This test that using union forward the abi of the inner type, as
// discussed in #54668
#![crate_type="lib"]
#![feature(repr_simd)]
#[derive(Copy, Clone)]
pub enum Unhab {}
#[repr(simd)]
#[derive(Copy, Clone)]
pub struct i64x4(i64, i64, i64, i64);
#[derive(Copy, Clone)]
pub union UnionI64x4{ a:(), b: i64x4 }
// CHECK: define void @test_UnionI64x4(<4 x i64>* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4(_: UnionI64x4) { loop {} }
pub union UnionI64x4_{ a: i64x4, b: (), c:i64x4, d: Unhab, e: ((),()), f: UnionI64x4 }
// CHECK: define void @test_UnionI64x4_(<4 x i64>* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4_(_: UnionI64x4_) { loop {} }
pub union UnionI64x4I64{ a: i64x4, b: i64 }
// CHECK: define void @test_UnionI64x4I64(%UnionI64x4I64* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4I64(_: UnionI64x4I64) { loop {} }
pub union UnionI64x4Tuple{ a: i64x4, b: (i64, i64, i64, i64) }
// CHECK: define void @test_UnionI64x4Tuple(%UnionI64x4Tuple* {{.*}} %_1)
#[no_mangle]
pub fn test_UnionI64x4Tuple(_: UnionI64x4Tuple) { loop {} }
pub union UnionF32{a:f32}
// CHECK: define float @test_UnionF32(float %_1)
#[no_mangle]
pub fn test_UnionF32(_: UnionF32) -> UnionF32 { loop {} }
pub union UnionF32F32{a:f32, b:f32}
// CHECK: define float @test_UnionF32F32(float %_1)
#[no_mangle]
pub fn test_UnionF32F32(_: UnionF32F32) -> UnionF32F32 { loop {} }
pub union UnionF32U32{a:f32, b:u32}
// CHECK: define i32 @test_UnionF32U32(i32{{( %0)?}})
#[no_mangle]
pub fn test_UnionF32U32(_: UnionF32U32) -> UnionF32U32 { loop {} }
pub union UnionU128{a:u128}
// CHECK: define i128 @test_UnionU128(i128 %_1)
#[no_mangle]
pub fn test_UnionU128(_: UnionU128) -> UnionU128 { loop {} }
pub union UnionU128x2{a:(u128, u128)}
// CHECK: define void @test_UnionU128x2(i128 %_1.0, i128 %_1.1)
#[no_mangle]
pub fn test_UnionU128x2(_: UnionU128x2) { loop {} }
#[repr(C)]
pub union CUnionU128x2{a:(u128, u128)}
// CHECK: define void @test_CUnionU128x2(%CUnionU128x2* {{.*}} %_1)
#[no_mangle]
pub fn test_CUnionU128x2(_: CUnionU128x2) { loop {} }
pub union UnionBool { b:bool }
// CHECK: define zeroext i1 @test_UnionBool(i8 %b)
#[no_mangle]
pub fn
|
(b: UnionBool) -> bool { unsafe { b.b } }
// CHECK: %0 = trunc i8 %b to i1
|
test_UnionBool
|
identifier_name
|
error.rs
|
use serde_json::Error as SerdeError;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IoError;
#[derive(Debug)]
pub enum LatticeError {
IoError(IoError),
JsonParseError(SerdeError),
InconsistentVertices,
NegativeSize,
}
impl StdError for LatticeError {
fn description(&self) -> &str
|
fn cause(&self) -> Option<&StdError> {
match self {
LatticeError::IoError(err) => Some(err),
LatticeError::JsonParseError(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for LatticeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LatticeError::IoError(_) => f.write_str("IoError"),
LatticeError::JsonParseError(_) => f.write_str("JsonParseError"),
LatticeError::InconsistentVertices => f.write_str("InconsistentVertices"),
LatticeError::NegativeSize => f.write_str("NegativeSize"),
}
}
}
impl From<SerdeError> for LatticeError {
fn from(err: SerdeError) -> Self {
LatticeError::JsonParseError(err)
}
}
impl From<IoError> for LatticeError {
fn from(err: IoError) -> Self {
LatticeError::IoError(err)
}
}
|
{
match self {
LatticeError::IoError(_) => "There was an error reading your file",
LatticeError::JsonParseError(_) => "There was a problem parsing json",
LatticeError::InconsistentVertices => "These vertices are inconsistent",
LatticeError::NegativeSize => "What are you up to don't give me a negative size",
}
}
|
identifier_body
|
error.rs
|
use serde_json::Error as SerdeError;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IoError;
#[derive(Debug)]
pub enum LatticeError {
IoError(IoError),
|
impl StdError for LatticeError {
fn description(&self) -> &str {
match self {
LatticeError::IoError(_) => "There was an error reading your file",
LatticeError::JsonParseError(_) => "There was a problem parsing json",
LatticeError::InconsistentVertices => "These vertices are inconsistent",
LatticeError::NegativeSize => "What are you up to don't give me a negative size",
}
}
fn cause(&self) -> Option<&StdError> {
match self {
LatticeError::IoError(err) => Some(err),
LatticeError::JsonParseError(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for LatticeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LatticeError::IoError(_) => f.write_str("IoError"),
LatticeError::JsonParseError(_) => f.write_str("JsonParseError"),
LatticeError::InconsistentVertices => f.write_str("InconsistentVertices"),
LatticeError::NegativeSize => f.write_str("NegativeSize"),
}
}
}
impl From<SerdeError> for LatticeError {
fn from(err: SerdeError) -> Self {
LatticeError::JsonParseError(err)
}
}
impl From<IoError> for LatticeError {
fn from(err: IoError) -> Self {
LatticeError::IoError(err)
}
}
|
JsonParseError(SerdeError),
InconsistentVertices,
NegativeSize,
}
|
random_line_split
|
error.rs
|
use serde_json::Error as SerdeError;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IoError;
#[derive(Debug)]
pub enum LatticeError {
IoError(IoError),
JsonParseError(SerdeError),
InconsistentVertices,
NegativeSize,
}
impl StdError for LatticeError {
fn description(&self) -> &str {
match self {
LatticeError::IoError(_) => "There was an error reading your file",
LatticeError::JsonParseError(_) => "There was a problem parsing json",
LatticeError::InconsistentVertices => "These vertices are inconsistent",
LatticeError::NegativeSize => "What are you up to don't give me a negative size",
}
}
fn cause(&self) -> Option<&StdError> {
match self {
LatticeError::IoError(err) => Some(err),
LatticeError::JsonParseError(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for LatticeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LatticeError::IoError(_) => f.write_str("IoError"),
LatticeError::JsonParseError(_) => f.write_str("JsonParseError"),
LatticeError::InconsistentVertices => f.write_str("InconsistentVertices"),
LatticeError::NegativeSize => f.write_str("NegativeSize"),
}
}
}
impl From<SerdeError> for LatticeError {
fn from(err: SerdeError) -> Self {
LatticeError::JsonParseError(err)
}
}
impl From<IoError> for LatticeError {
fn
|
(err: IoError) -> Self {
LatticeError::IoError(err)
}
}
|
from
|
identifier_name
|
archive.rs
|
// Copyright 2013-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.
//! A helper class for dealing with static archives
use std::io::process::{Command, ProcessOutput};
use std::io::{fs, TempDir};
use std::io;
use std::os;
use std::str;
use syntax::abi;
use ErrorHandler = syntax::diagnostic::Handler;
pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
pub struct ArchiveConfig<'a> {
pub handler: &'a ErrorHandler,
pub dst: Path,
pub lib_search_paths: Vec<Path>,
pub os: abi::Os,
pub maybe_ar_prog: Option<String>
}
pub struct Archive<'a> {
handler: &'a ErrorHandler,
dst: Path,
lib_search_paths: Vec<Path>,
os: abi::Os,
maybe_ar_prog: Option<String>
}
fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
args: &str, cwd: Option<&Path>,
paths: &[&Path]) -> ProcessOutput {
let ar = match *maybe_ar_prog {
Some(ref ar) => ar.as_slice(),
None => "ar"
};
let mut cmd = Command::new(ar);
cmd.arg(args).args(paths);
debug!("{}", cmd);
match cwd {
Some(p) => {
cmd.cwd(p);
debug!("inside {}", p.display());
}
None => {}
}
match cmd.spawn() {
Ok(prog) => {
let o = prog.wait_with_output().unwrap();
if!o.status.success() {
handler.err(format!("{} failed with: {}",
cmd,
o.status).as_slice());
handler.note(format!("stdout ---\n{}",
str::from_utf8(o.output
.as_slice()).unwrap())
.as_slice());
handler.note(format!("stderr ---\n{}",
str::from_utf8(o.error
.as_slice()).unwrap())
.as_slice());
handler.abort_if_errors();
}
o
},
Err(e) => {
handler.err(format!("could not exec `{}`: {}", ar.as_slice(),
e).as_slice());
handler.abort_if_errors();
fail!("rustc::back::archive::run_ar() should not reach this point");
}
}
}
impl<'a> Archive<'a> {
/// Initializes a new static archive with the given object file
pub fn create<'b>(config: ArchiveConfig<'a>, initial_object: &'b Path) -> Archive<'a> {
let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config;
run_ar(handler, &maybe_ar_prog, "crus", None, [&dst, initial_object]);
Archive {
handler: handler,
dst: dst,
lib_search_paths: lib_search_paths,
os: os,
maybe_ar_prog: maybe_ar_prog
}
}
/// Opens an existing static archive
pub fn open(config: ArchiveConfig<'a>) -> Archive<'a> {
let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config;
assert!(dst.exists());
Archive {
handler: handler,
dst: dst,
lib_search_paths: lib_search_paths,
os: os,
maybe_ar_prog: maybe_ar_prog
}
}
/// Adds all of the contents of a native library to this archive. This will
/// search in the relevant locations for a library named `name`.
pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()> {
let location = self.find_library(name);
self.add_archive(&location, name, [])
}
/// Adds all of the contents of the rlib at the specified path to this
/// archive.
///
/// This ignores adding the bytecode from the rlib, and if LTO is enabled
/// then the object file also isn't added.
pub fn add_rlib(&mut self, rlib: &Path, name: &str,
lto: bool) -> io::IoResult<()> {
let object = format!("{}.o", name);
let bytecode = format!("{}.bytecode.deflate", name);
let mut ignore = vec!(bytecode.as_slice(), METADATA_FILENAME);
if lto {
ignore.push(object.as_slice());
}
self.add_archive(rlib, name, ignore.as_slice())
}
/// Adds an arbitrary file to this archive
pub fn add_file(&mut self, file: &Path, has_symbols: bool) {
let cmd = if has_symbols {"r"} else {"rS"};
run_ar(self.handler, &self.maybe_ar_prog, cmd, None, [&self.dst, file]);
}
/// Removes a file from this archive
pub fn remove_file(&mut self, file: &str) {
run_ar(self.handler, &self.maybe_ar_prog, "d", None, [&self.dst, &Path::new(file)]);
}
/// Updates all symbols in the archive (runs 'ar s' over it)
pub fn update_symbols(&mut self) {
run_ar(self.handler, &self.maybe_ar_prog, "s", None, [&self.dst]);
}
/// Lists all files in an archive
pub fn
|
(&self) -> Vec<String> {
let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, [&self.dst]);
let output = str::from_utf8(output.output.as_slice()).unwrap();
// use lines_any because windows delimits output with `\r\n` instead of
// just `\n`
output.lines_any().map(|s| s.to_string()).collect()
}
fn add_archive(&mut self, archive: &Path, name: &str,
skip: &[&str]) -> io::IoResult<()> {
let loc = TempDir::new("rsar").unwrap();
// First, extract the contents of the archive to a temporary directory
let archive = os::make_absolute(archive);
run_ar(self.handler, &self.maybe_ar_prog, "x", Some(loc.path()), [&archive]);
// Next, we must rename all of the inputs to "guaranteed unique names".
// The reason for this is that archives are keyed off the name of the
// files, so if two files have the same name they will override one
// another in the archive (bad).
//
// We skip any files explicitly desired for skipping, and we also skip
// all SYMDEF files as these are just magical placeholders which get
// re-created when we make a new archive anyway.
let files = try!(fs::readdir(loc.path()));
let mut inputs = Vec::new();
for file in files.iter() {
let filename = file.filename_str().unwrap();
if skip.iter().any(|s| *s == filename) { continue }
if filename.contains(".SYMDEF") { continue }
let filename = format!("r-{}-{}", name, filename);
// LLDB (as mentioned in back::link) crashes on filenames of exactly
// 16 bytes in length. If we're including an object file with
// exactly 16-bytes of characters, give it some prefix so that it's
// not 16 bytes.
let filename = if filename.len() == 16 {
format!("lldb-fix-{}", filename)
} else {
filename
};
let new_filename = file.with_filename(filename);
try!(fs::rename(file, &new_filename));
inputs.push(new_filename);
}
if inputs.len() == 0 { return Ok(()) }
// Finally, add all the renamed files to this archive
let mut args = vec!(&self.dst);
args.extend(inputs.iter());
run_ar(self.handler, &self.maybe_ar_prog, "r", None, args.as_slice());
Ok(())
}
fn find_library(&self, name: &str) -> Path {
let (osprefix, osext) = match self.os {
abi::OsWin32 => ("", "lib"), _ => ("lib", "a"),
};
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = format!("{}{}.{}", osprefix, name, osext);
let unixlibname = format!("lib{}.a", name);
for path in self.lib_search_paths.iter() {
debug!("looking for {} inside {}", name, path.display());
let test = path.join(oslibname.as_slice());
if test.exists() { return test }
if oslibname!= unixlibname {
let test = path.join(unixlibname.as_slice());
if test.exists() { return test }
}
}
self.handler.fatal(format!("could not find native static library `{}`, \
perhaps an -L flag is missing?",
name).as_slice());
}
}
|
files
|
identifier_name
|
archive.rs
|
// Copyright 2013-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.
//! A helper class for dealing with static archives
use std::io::process::{Command, ProcessOutput};
use std::io::{fs, TempDir};
use std::io;
use std::os;
use std::str;
use syntax::abi;
use ErrorHandler = syntax::diagnostic::Handler;
pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
pub struct ArchiveConfig<'a> {
pub handler: &'a ErrorHandler,
pub dst: Path,
pub lib_search_paths: Vec<Path>,
pub os: abi::Os,
pub maybe_ar_prog: Option<String>
}
pub struct Archive<'a> {
handler: &'a ErrorHandler,
dst: Path,
lib_search_paths: Vec<Path>,
os: abi::Os,
maybe_ar_prog: Option<String>
}
fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
args: &str, cwd: Option<&Path>,
paths: &[&Path]) -> ProcessOutput {
let ar = match *maybe_ar_prog {
Some(ref ar) => ar.as_slice(),
None => "ar"
};
let mut cmd = Command::new(ar);
cmd.arg(args).args(paths);
debug!("{}", cmd);
match cwd {
Some(p) => {
cmd.cwd(p);
debug!("inside {}", p.display());
}
None => {}
}
match cmd.spawn() {
Ok(prog) => {
let o = prog.wait_with_output().unwrap();
if!o.status.success() {
handler.err(format!("{} failed with: {}",
cmd,
o.status).as_slice());
handler.note(format!("stdout ---\n{}",
str::from_utf8(o.output
.as_slice()).unwrap())
.as_slice());
handler.note(format!("stderr ---\n{}",
str::from_utf8(o.error
.as_slice()).unwrap())
.as_slice());
handler.abort_if_errors();
}
o
},
Err(e) => {
handler.err(format!("could not exec `{}`: {}", ar.as_slice(),
e).as_slice());
handler.abort_if_errors();
fail!("rustc::back::archive::run_ar() should not reach this point");
}
}
}
impl<'a> Archive<'a> {
/// Initializes a new static archive with the given object file
pub fn create<'b>(config: ArchiveConfig<'a>, initial_object: &'b Path) -> Archive<'a> {
let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config;
run_ar(handler, &maybe_ar_prog, "crus", None, [&dst, initial_object]);
Archive {
handler: handler,
dst: dst,
lib_search_paths: lib_search_paths,
os: os,
maybe_ar_prog: maybe_ar_prog
}
}
/// Opens an existing static archive
pub fn open(config: ArchiveConfig<'a>) -> Archive<'a> {
let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config;
assert!(dst.exists());
Archive {
handler: handler,
dst: dst,
lib_search_paths: lib_search_paths,
os: os,
maybe_ar_prog: maybe_ar_prog
}
}
/// Adds all of the contents of a native library to this archive. This will
/// search in the relevant locations for a library named `name`.
pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()> {
let location = self.find_library(name);
self.add_archive(&location, name, [])
}
/// Adds all of the contents of the rlib at the specified path to this
/// archive.
///
/// This ignores adding the bytecode from the rlib, and if LTO is enabled
/// then the object file also isn't added.
pub fn add_rlib(&mut self, rlib: &Path, name: &str,
lto: bool) -> io::IoResult<()> {
let object = format!("{}.o", name);
let bytecode = format!("{}.bytecode.deflate", name);
let mut ignore = vec!(bytecode.as_slice(), METADATA_FILENAME);
if lto {
ignore.push(object.as_slice());
}
self.add_archive(rlib, name, ignore.as_slice())
}
/// Adds an arbitrary file to this archive
|
run_ar(self.handler, &self.maybe_ar_prog, cmd, None, [&self.dst, file]);
}
/// Removes a file from this archive
pub fn remove_file(&mut self, file: &str) {
run_ar(self.handler, &self.maybe_ar_prog, "d", None, [&self.dst, &Path::new(file)]);
}
/// Updates all symbols in the archive (runs 'ar s' over it)
pub fn update_symbols(&mut self) {
run_ar(self.handler, &self.maybe_ar_prog, "s", None, [&self.dst]);
}
/// Lists all files in an archive
pub fn files(&self) -> Vec<String> {
let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, [&self.dst]);
let output = str::from_utf8(output.output.as_slice()).unwrap();
// use lines_any because windows delimits output with `\r\n` instead of
// just `\n`
output.lines_any().map(|s| s.to_string()).collect()
}
fn add_archive(&mut self, archive: &Path, name: &str,
skip: &[&str]) -> io::IoResult<()> {
let loc = TempDir::new("rsar").unwrap();
// First, extract the contents of the archive to a temporary directory
let archive = os::make_absolute(archive);
run_ar(self.handler, &self.maybe_ar_prog, "x", Some(loc.path()), [&archive]);
// Next, we must rename all of the inputs to "guaranteed unique names".
// The reason for this is that archives are keyed off the name of the
// files, so if two files have the same name they will override one
// another in the archive (bad).
//
// We skip any files explicitly desired for skipping, and we also skip
// all SYMDEF files as these are just magical placeholders which get
// re-created when we make a new archive anyway.
let files = try!(fs::readdir(loc.path()));
let mut inputs = Vec::new();
for file in files.iter() {
let filename = file.filename_str().unwrap();
if skip.iter().any(|s| *s == filename) { continue }
if filename.contains(".SYMDEF") { continue }
let filename = format!("r-{}-{}", name, filename);
// LLDB (as mentioned in back::link) crashes on filenames of exactly
// 16 bytes in length. If we're including an object file with
// exactly 16-bytes of characters, give it some prefix so that it's
// not 16 bytes.
let filename = if filename.len() == 16 {
format!("lldb-fix-{}", filename)
} else {
filename
};
let new_filename = file.with_filename(filename);
try!(fs::rename(file, &new_filename));
inputs.push(new_filename);
}
if inputs.len() == 0 { return Ok(()) }
// Finally, add all the renamed files to this archive
let mut args = vec!(&self.dst);
args.extend(inputs.iter());
run_ar(self.handler, &self.maybe_ar_prog, "r", None, args.as_slice());
Ok(())
}
fn find_library(&self, name: &str) -> Path {
let (osprefix, osext) = match self.os {
abi::OsWin32 => ("", "lib"), _ => ("lib", "a"),
};
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = format!("{}{}.{}", osprefix, name, osext);
let unixlibname = format!("lib{}.a", name);
for path in self.lib_search_paths.iter() {
debug!("looking for {} inside {}", name, path.display());
let test = path.join(oslibname.as_slice());
if test.exists() { return test }
if oslibname!= unixlibname {
let test = path.join(unixlibname.as_slice());
if test.exists() { return test }
}
}
self.handler.fatal(format!("could not find native static library `{}`, \
perhaps an -L flag is missing?",
name).as_slice());
}
}
|
pub fn add_file(&mut self, file: &Path, has_symbols: bool) {
let cmd = if has_symbols {"r"} else {"rS"};
|
random_line_split
|
archive.rs
|
// Copyright 2013-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.
//! A helper class for dealing with static archives
use std::io::process::{Command, ProcessOutput};
use std::io::{fs, TempDir};
use std::io;
use std::os;
use std::str;
use syntax::abi;
use ErrorHandler = syntax::diagnostic::Handler;
pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
pub struct ArchiveConfig<'a> {
pub handler: &'a ErrorHandler,
pub dst: Path,
pub lib_search_paths: Vec<Path>,
pub os: abi::Os,
pub maybe_ar_prog: Option<String>
}
pub struct Archive<'a> {
handler: &'a ErrorHandler,
dst: Path,
lib_search_paths: Vec<Path>,
os: abi::Os,
maybe_ar_prog: Option<String>
}
fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
args: &str, cwd: Option<&Path>,
paths: &[&Path]) -> ProcessOutput {
let ar = match *maybe_ar_prog {
Some(ref ar) => ar.as_slice(),
None => "ar"
};
let mut cmd = Command::new(ar);
cmd.arg(args).args(paths);
debug!("{}", cmd);
match cwd {
Some(p) => {
cmd.cwd(p);
debug!("inside {}", p.display());
}
None => {}
}
match cmd.spawn() {
Ok(prog) =>
|
,
Err(e) => {
handler.err(format!("could not exec `{}`: {}", ar.as_slice(),
e).as_slice());
handler.abort_if_errors();
fail!("rustc::back::archive::run_ar() should not reach this point");
}
}
}
impl<'a> Archive<'a> {
/// Initializes a new static archive with the given object file
pub fn create<'b>(config: ArchiveConfig<'a>, initial_object: &'b Path) -> Archive<'a> {
let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config;
run_ar(handler, &maybe_ar_prog, "crus", None, [&dst, initial_object]);
Archive {
handler: handler,
dst: dst,
lib_search_paths: lib_search_paths,
os: os,
maybe_ar_prog: maybe_ar_prog
}
}
/// Opens an existing static archive
pub fn open(config: ArchiveConfig<'a>) -> Archive<'a> {
let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config;
assert!(dst.exists());
Archive {
handler: handler,
dst: dst,
lib_search_paths: lib_search_paths,
os: os,
maybe_ar_prog: maybe_ar_prog
}
}
/// Adds all of the contents of a native library to this archive. This will
/// search in the relevant locations for a library named `name`.
pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()> {
let location = self.find_library(name);
self.add_archive(&location, name, [])
}
/// Adds all of the contents of the rlib at the specified path to this
/// archive.
///
/// This ignores adding the bytecode from the rlib, and if LTO is enabled
/// then the object file also isn't added.
pub fn add_rlib(&mut self, rlib: &Path, name: &str,
lto: bool) -> io::IoResult<()> {
let object = format!("{}.o", name);
let bytecode = format!("{}.bytecode.deflate", name);
let mut ignore = vec!(bytecode.as_slice(), METADATA_FILENAME);
if lto {
ignore.push(object.as_slice());
}
self.add_archive(rlib, name, ignore.as_slice())
}
/// Adds an arbitrary file to this archive
pub fn add_file(&mut self, file: &Path, has_symbols: bool) {
let cmd = if has_symbols {"r"} else {"rS"};
run_ar(self.handler, &self.maybe_ar_prog, cmd, None, [&self.dst, file]);
}
/// Removes a file from this archive
pub fn remove_file(&mut self, file: &str) {
run_ar(self.handler, &self.maybe_ar_prog, "d", None, [&self.dst, &Path::new(file)]);
}
/// Updates all symbols in the archive (runs 'ar s' over it)
pub fn update_symbols(&mut self) {
run_ar(self.handler, &self.maybe_ar_prog, "s", None, [&self.dst]);
}
/// Lists all files in an archive
pub fn files(&self) -> Vec<String> {
let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, [&self.dst]);
let output = str::from_utf8(output.output.as_slice()).unwrap();
// use lines_any because windows delimits output with `\r\n` instead of
// just `\n`
output.lines_any().map(|s| s.to_string()).collect()
}
fn add_archive(&mut self, archive: &Path, name: &str,
skip: &[&str]) -> io::IoResult<()> {
let loc = TempDir::new("rsar").unwrap();
// First, extract the contents of the archive to a temporary directory
let archive = os::make_absolute(archive);
run_ar(self.handler, &self.maybe_ar_prog, "x", Some(loc.path()), [&archive]);
// Next, we must rename all of the inputs to "guaranteed unique names".
// The reason for this is that archives are keyed off the name of the
// files, so if two files have the same name they will override one
// another in the archive (bad).
//
// We skip any files explicitly desired for skipping, and we also skip
// all SYMDEF files as these are just magical placeholders which get
// re-created when we make a new archive anyway.
let files = try!(fs::readdir(loc.path()));
let mut inputs = Vec::new();
for file in files.iter() {
let filename = file.filename_str().unwrap();
if skip.iter().any(|s| *s == filename) { continue }
if filename.contains(".SYMDEF") { continue }
let filename = format!("r-{}-{}", name, filename);
// LLDB (as mentioned in back::link) crashes on filenames of exactly
// 16 bytes in length. If we're including an object file with
// exactly 16-bytes of characters, give it some prefix so that it's
// not 16 bytes.
let filename = if filename.len() == 16 {
format!("lldb-fix-{}", filename)
} else {
filename
};
let new_filename = file.with_filename(filename);
try!(fs::rename(file, &new_filename));
inputs.push(new_filename);
}
if inputs.len() == 0 { return Ok(()) }
// Finally, add all the renamed files to this archive
let mut args = vec!(&self.dst);
args.extend(inputs.iter());
run_ar(self.handler, &self.maybe_ar_prog, "r", None, args.as_slice());
Ok(())
}
fn find_library(&self, name: &str) -> Path {
let (osprefix, osext) = match self.os {
abi::OsWin32 => ("", "lib"), _ => ("lib", "a"),
};
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = format!("{}{}.{}", osprefix, name, osext);
let unixlibname = format!("lib{}.a", name);
for path in self.lib_search_paths.iter() {
debug!("looking for {} inside {}", name, path.display());
let test = path.join(oslibname.as_slice());
if test.exists() { return test }
if oslibname!= unixlibname {
let test = path.join(unixlibname.as_slice());
if test.exists() { return test }
}
}
self.handler.fatal(format!("could not find native static library `{}`, \
perhaps an -L flag is missing?",
name).as_slice());
}
}
|
{
let o = prog.wait_with_output().unwrap();
if !o.status.success() {
handler.err(format!("{} failed with: {}",
cmd,
o.status).as_slice());
handler.note(format!("stdout ---\n{}",
str::from_utf8(o.output
.as_slice()).unwrap())
.as_slice());
handler.note(format!("stderr ---\n{}",
str::from_utf8(o.error
.as_slice()).unwrap())
.as_slice());
handler.abort_if_errors();
}
o
}
|
conditional_block
|
archive.rs
|
// Copyright 2013-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.
//! A helper class for dealing with static archives
use std::io::process::{Command, ProcessOutput};
use std::io::{fs, TempDir};
use std::io;
use std::os;
use std::str;
use syntax::abi;
use ErrorHandler = syntax::diagnostic::Handler;
pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
pub struct ArchiveConfig<'a> {
pub handler: &'a ErrorHandler,
pub dst: Path,
pub lib_search_paths: Vec<Path>,
pub os: abi::Os,
pub maybe_ar_prog: Option<String>
}
pub struct Archive<'a> {
handler: &'a ErrorHandler,
dst: Path,
lib_search_paths: Vec<Path>,
os: abi::Os,
maybe_ar_prog: Option<String>
}
fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
args: &str, cwd: Option<&Path>,
paths: &[&Path]) -> ProcessOutput {
let ar = match *maybe_ar_prog {
Some(ref ar) => ar.as_slice(),
None => "ar"
};
let mut cmd = Command::new(ar);
cmd.arg(args).args(paths);
debug!("{}", cmd);
match cwd {
Some(p) => {
cmd.cwd(p);
debug!("inside {}", p.display());
}
None => {}
}
match cmd.spawn() {
Ok(prog) => {
let o = prog.wait_with_output().unwrap();
if!o.status.success() {
handler.err(format!("{} failed with: {}",
cmd,
o.status).as_slice());
handler.note(format!("stdout ---\n{}",
str::from_utf8(o.output
.as_slice()).unwrap())
.as_slice());
handler.note(format!("stderr ---\n{}",
str::from_utf8(o.error
.as_slice()).unwrap())
.as_slice());
handler.abort_if_errors();
}
o
},
Err(e) => {
handler.err(format!("could not exec `{}`: {}", ar.as_slice(),
e).as_slice());
handler.abort_if_errors();
fail!("rustc::back::archive::run_ar() should not reach this point");
}
}
}
impl<'a> Archive<'a> {
/// Initializes a new static archive with the given object file
pub fn create<'b>(config: ArchiveConfig<'a>, initial_object: &'b Path) -> Archive<'a> {
let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config;
run_ar(handler, &maybe_ar_prog, "crus", None, [&dst, initial_object]);
Archive {
handler: handler,
dst: dst,
lib_search_paths: lib_search_paths,
os: os,
maybe_ar_prog: maybe_ar_prog
}
}
/// Opens an existing static archive
pub fn open(config: ArchiveConfig<'a>) -> Archive<'a> {
let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config;
assert!(dst.exists());
Archive {
handler: handler,
dst: dst,
lib_search_paths: lib_search_paths,
os: os,
maybe_ar_prog: maybe_ar_prog
}
}
/// Adds all of the contents of a native library to this archive. This will
/// search in the relevant locations for a library named `name`.
pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()>
|
/// Adds all of the contents of the rlib at the specified path to this
/// archive.
///
/// This ignores adding the bytecode from the rlib, and if LTO is enabled
/// then the object file also isn't added.
pub fn add_rlib(&mut self, rlib: &Path, name: &str,
lto: bool) -> io::IoResult<()> {
let object = format!("{}.o", name);
let bytecode = format!("{}.bytecode.deflate", name);
let mut ignore = vec!(bytecode.as_slice(), METADATA_FILENAME);
if lto {
ignore.push(object.as_slice());
}
self.add_archive(rlib, name, ignore.as_slice())
}
/// Adds an arbitrary file to this archive
pub fn add_file(&mut self, file: &Path, has_symbols: bool) {
let cmd = if has_symbols {"r"} else {"rS"};
run_ar(self.handler, &self.maybe_ar_prog, cmd, None, [&self.dst, file]);
}
/// Removes a file from this archive
pub fn remove_file(&mut self, file: &str) {
run_ar(self.handler, &self.maybe_ar_prog, "d", None, [&self.dst, &Path::new(file)]);
}
/// Updates all symbols in the archive (runs 'ar s' over it)
pub fn update_symbols(&mut self) {
run_ar(self.handler, &self.maybe_ar_prog, "s", None, [&self.dst]);
}
/// Lists all files in an archive
pub fn files(&self) -> Vec<String> {
let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, [&self.dst]);
let output = str::from_utf8(output.output.as_slice()).unwrap();
// use lines_any because windows delimits output with `\r\n` instead of
// just `\n`
output.lines_any().map(|s| s.to_string()).collect()
}
fn add_archive(&mut self, archive: &Path, name: &str,
skip: &[&str]) -> io::IoResult<()> {
let loc = TempDir::new("rsar").unwrap();
// First, extract the contents of the archive to a temporary directory
let archive = os::make_absolute(archive);
run_ar(self.handler, &self.maybe_ar_prog, "x", Some(loc.path()), [&archive]);
// Next, we must rename all of the inputs to "guaranteed unique names".
// The reason for this is that archives are keyed off the name of the
// files, so if two files have the same name they will override one
// another in the archive (bad).
//
// We skip any files explicitly desired for skipping, and we also skip
// all SYMDEF files as these are just magical placeholders which get
// re-created when we make a new archive anyway.
let files = try!(fs::readdir(loc.path()));
let mut inputs = Vec::new();
for file in files.iter() {
let filename = file.filename_str().unwrap();
if skip.iter().any(|s| *s == filename) { continue }
if filename.contains(".SYMDEF") { continue }
let filename = format!("r-{}-{}", name, filename);
// LLDB (as mentioned in back::link) crashes on filenames of exactly
// 16 bytes in length. If we're including an object file with
// exactly 16-bytes of characters, give it some prefix so that it's
// not 16 bytes.
let filename = if filename.len() == 16 {
format!("lldb-fix-{}", filename)
} else {
filename
};
let new_filename = file.with_filename(filename);
try!(fs::rename(file, &new_filename));
inputs.push(new_filename);
}
if inputs.len() == 0 { return Ok(()) }
// Finally, add all the renamed files to this archive
let mut args = vec!(&self.dst);
args.extend(inputs.iter());
run_ar(self.handler, &self.maybe_ar_prog, "r", None, args.as_slice());
Ok(())
}
fn find_library(&self, name: &str) -> Path {
let (osprefix, osext) = match self.os {
abi::OsWin32 => ("", "lib"), _ => ("lib", "a"),
};
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = format!("{}{}.{}", osprefix, name, osext);
let unixlibname = format!("lib{}.a", name);
for path in self.lib_search_paths.iter() {
debug!("looking for {} inside {}", name, path.display());
let test = path.join(oslibname.as_slice());
if test.exists() { return test }
if oslibname!= unixlibname {
let test = path.join(unixlibname.as_slice());
if test.exists() { return test }
}
}
self.handler.fatal(format!("could not find native static library `{}`, \
perhaps an -L flag is missing?",
name).as_slice());
}
}
|
{
let location = self.find_library(name);
self.add_archive(&location, name, [])
}
|
identifier_body
|
linear-for-loop.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.
pub fn
|
() {
let x = ~[1, 2, 3];
let mut y = 0;
for x.each |i| { debug!(*i); y += *i; }
debug!(y);
assert!((y == 6));
let s = ~"hello there";
let mut i: int = 0;
for str::each(s) |c| {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 { assert!((c == 'l' as u8)); }
if i == 4 { assert!((c == 'o' as u8)); }
//...
i += 1;
debug!(i);
debug!(c);
}
assert!((i == 11));
}
|
main
|
identifier_name
|
linear-for-loop.rs
|
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn main() {
let x = ~[1, 2, 3];
let mut y = 0;
for x.each |i| { debug!(*i); y += *i; }
debug!(y);
assert!((y == 6));
let s = ~"hello there";
let mut i: int = 0;
for str::each(s) |c| {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 { assert!((c == 'l' as u8)); }
if i == 4 { assert!((c == 'o' as u8)); }
//...
i += 1;
debug!(i);
debug!(c);
}
assert!((i == 11));
}
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
random_line_split
|
|
linear-for-loop.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.
pub fn main()
|
debug!(y);
assert!((y == 6));
let s = ~"hello there";
let mut i: int = 0;
for str::each(s) |c| {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 { assert!((c == 'l' as u8)); }
if i == 4 { assert!((c == 'o' as u8)); }
//...
i += 1;
debug!(i);
debug!(c);
}
assert!((i == 11));
}
|
{
let x = ~[1, 2, 3];
let mut y = 0;
for x.each |i| { debug!(*i); y += *i; }
|
identifier_body
|
linear-for-loop.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.
pub fn main() {
let x = ~[1, 2, 3];
let mut y = 0;
for x.each |i| { debug!(*i); y += *i; }
debug!(y);
assert!((y == 6));
let s = ~"hello there";
let mut i: int = 0;
for str::each(s) |c| {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3
|
if i == 4 { assert!((c == 'o' as u8)); }
//...
i += 1;
debug!(i);
debug!(c);
}
assert!((i == 11));
}
|
{ assert!((c == 'l' as u8)); }
|
conditional_block
|
cargo_run.rs
|
use std::os;
use ops::{self, ExecEngine};
use util::{CargoResult, human, process, ProcessError, ChainError};
use core::manifest::TargetKind;
use core::source::Source;
use sources::PathSource;
pub fn run(manifest_path: &Path,
target_kind: TargetKind,
name: Option<String>,
options: &mut ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>>
|
human("`cargo run` requires that a project only have one executable. \
Use the `--bin` option to specify which one to run")),
None => {}
}
let compile = try!(ops::compile(manifest_path, options));
let dst = manifest_path.dir_path().join("target");
let dst = match options.target {
Some(target) => dst.join(target),
None => dst,
};
let exe = match (bin.get_profile().get_dest(), bin.is_example()) {
(Some(s), true) => dst.join(s).join("examples").join(bin.get_name()),
(Some(s), false) => dst.join(s).join(bin.get_name()),
(None, true) => dst.join("examples").join(bin.get_name()),
(None, false) => dst.join(bin.get_name()),
};
let exe = match exe.path_relative_from(&try!(os::getcwd())) {
Some(path) => path,
None => exe,
};
let process = try!(try!(compile.target_process(exe, &root))
.into_process_builder())
.args(args)
.cwd(try!(os::getcwd()));
try!(options.shell.status("Running", process.to_string()));
Ok(process.exec().err())
}
|
{
let mut src = try!(PathSource::for_path(&manifest_path.dir_path()));
try!(src.update());
let root = try!(src.get_root_package());
let env = options.env;
let mut bins = root.get_manifest().get_targets().iter().filter(|a| {
let matches_kind = match target_kind {
TargetKind::Bin => a.is_bin(),
TargetKind::Example => a.is_example(),
TargetKind::Lib(_) => false,
};
let matches_name = name.as_ref().map_or(true, |n| n.as_slice() == a.get_name());
matches_kind && matches_name && a.get_profile().get_env() == env &&
!a.get_profile().is_custom_build()
});
let bin = try!(bins.next().chain_error(|| {
human("a bin target must be available for `cargo run`")
}));
match bins.next() {
Some(..) => return Err(
|
identifier_body
|
cargo_run.rs
|
use std::os;
use ops::{self, ExecEngine};
use util::{CargoResult, human, process, ProcessError, ChainError};
use core::manifest::TargetKind;
use core::source::Source;
use sources::PathSource;
pub fn run(manifest_path: &Path,
target_kind: TargetKind,
name: Option<String>,
options: &mut ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> {
let mut src = try!(PathSource::for_path(&manifest_path.dir_path()));
try!(src.update());
let root = try!(src.get_root_package());
let env = options.env;
let mut bins = root.get_manifest().get_targets().iter().filter(|a| {
let matches_kind = match target_kind {
TargetKind::Bin => a.is_bin(),
TargetKind::Example => a.is_example(),
TargetKind::Lib(_) => false,
};
let matches_name = name.as_ref().map_or(true, |n| n.as_slice() == a.get_name());
matches_kind && matches_name && a.get_profile().get_env() == env &&
!a.get_profile().is_custom_build()
});
let bin = try!(bins.next().chain_error(|| {
human("a bin target must be available for `cargo run`")
}));
match bins.next() {
Some(..) => return Err(
human("`cargo run` requires that a project only have one executable. \
Use the `--bin` option to specify which one to run")),
None =>
|
}
let compile = try!(ops::compile(manifest_path, options));
let dst = manifest_path.dir_path().join("target");
let dst = match options.target {
Some(target) => dst.join(target),
None => dst,
};
let exe = match (bin.get_profile().get_dest(), bin.is_example()) {
(Some(s), true) => dst.join(s).join("examples").join(bin.get_name()),
(Some(s), false) => dst.join(s).join(bin.get_name()),
(None, true) => dst.join("examples").join(bin.get_name()),
(None, false) => dst.join(bin.get_name()),
};
let exe = match exe.path_relative_from(&try!(os::getcwd())) {
Some(path) => path,
None => exe,
};
let process = try!(try!(compile.target_process(exe, &root))
.into_process_builder())
.args(args)
.cwd(try!(os::getcwd()));
try!(options.shell.status("Running", process.to_string()));
Ok(process.exec().err())
}
|
{}
|
conditional_block
|
cargo_run.rs
|
use std::os;
use ops::{self, ExecEngine};
use util::{CargoResult, human, process, ProcessError, ChainError};
use core::manifest::TargetKind;
use core::source::Source;
use sources::PathSource;
pub fn
|
(manifest_path: &Path,
target_kind: TargetKind,
name: Option<String>,
options: &mut ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> {
let mut src = try!(PathSource::for_path(&manifest_path.dir_path()));
try!(src.update());
let root = try!(src.get_root_package());
let env = options.env;
let mut bins = root.get_manifest().get_targets().iter().filter(|a| {
let matches_kind = match target_kind {
TargetKind::Bin => a.is_bin(),
TargetKind::Example => a.is_example(),
TargetKind::Lib(_) => false,
};
let matches_name = name.as_ref().map_or(true, |n| n.as_slice() == a.get_name());
matches_kind && matches_name && a.get_profile().get_env() == env &&
!a.get_profile().is_custom_build()
});
let bin = try!(bins.next().chain_error(|| {
human("a bin target must be available for `cargo run`")
}));
match bins.next() {
Some(..) => return Err(
human("`cargo run` requires that a project only have one executable. \
Use the `--bin` option to specify which one to run")),
None => {}
}
let compile = try!(ops::compile(manifest_path, options));
let dst = manifest_path.dir_path().join("target");
let dst = match options.target {
Some(target) => dst.join(target),
None => dst,
};
let exe = match (bin.get_profile().get_dest(), bin.is_example()) {
(Some(s), true) => dst.join(s).join("examples").join(bin.get_name()),
(Some(s), false) => dst.join(s).join(bin.get_name()),
(None, true) => dst.join("examples").join(bin.get_name()),
(None, false) => dst.join(bin.get_name()),
};
let exe = match exe.path_relative_from(&try!(os::getcwd())) {
Some(path) => path,
None => exe,
};
let process = try!(try!(compile.target_process(exe, &root))
.into_process_builder())
.args(args)
.cwd(try!(os::getcwd()));
try!(options.shell.status("Running", process.to_string()));
Ok(process.exec().err())
}
|
run
|
identifier_name
|
cargo_run.rs
|
use std::os;
use ops::{self, ExecEngine};
use util::{CargoResult, human, process, ProcessError, ChainError};
use core::manifest::TargetKind;
use core::source::Source;
use sources::PathSource;
pub fn run(manifest_path: &Path,
target_kind: TargetKind,
name: Option<String>,
options: &mut ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> {
let mut src = try!(PathSource::for_path(&manifest_path.dir_path()));
try!(src.update());
let root = try!(src.get_root_package());
let env = options.env;
let mut bins = root.get_manifest().get_targets().iter().filter(|a| {
let matches_kind = match target_kind {
TargetKind::Bin => a.is_bin(),
TargetKind::Example => a.is_example(),
TargetKind::Lib(_) => false,
};
let matches_name = name.as_ref().map_or(true, |n| n.as_slice() == a.get_name());
matches_kind && matches_name && a.get_profile().get_env() == env &&
!a.get_profile().is_custom_build()
});
let bin = try!(bins.next().chain_error(|| {
human("a bin target must be available for `cargo run`")
}));
match bins.next() {
Some(..) => return Err(
human("`cargo run` requires that a project only have one executable. \
Use the `--bin` option to specify which one to run")),
None => {}
}
let compile = try!(ops::compile(manifest_path, options));
let dst = manifest_path.dir_path().join("target");
let dst = match options.target {
Some(target) => dst.join(target),
None => dst,
};
let exe = match (bin.get_profile().get_dest(), bin.is_example()) {
(Some(s), true) => dst.join(s).join("examples").join(bin.get_name()),
|
Some(path) => path,
None => exe,
};
let process = try!(try!(compile.target_process(exe, &root))
.into_process_builder())
.args(args)
.cwd(try!(os::getcwd()));
try!(options.shell.status("Running", process.to_string()));
Ok(process.exec().err())
}
|
(Some(s), false) => dst.join(s).join(bin.get_name()),
(None, true) => dst.join("examples").join(bin.get_name()),
(None, false) => dst.join(bin.get_name()),
};
let exe = match exe.path_relative_from(&try!(os::getcwd())) {
|
random_line_split
|
lib.rs
|
//! FFI bindings for `energymon-osp-polling.h`.
extern crate libc;
extern crate energymon_sys;
pub use energymon_sys::energymon;
use libc::{c_int, uint64_t, c_char, size_t};
extern "C" {
pub fn energymon_init_osp_polling(em: *mut energymon) -> c_int;
pub fn energymon_read_total_osp_polling(em: *const energymon) -> uint64_t;
pub fn energymon_finish_osp_polling(em: *mut energymon) -> c_int;
pub fn energymon_get_source_osp_polling(buffer: *mut c_char, n: size_t) -> *mut c_char;
pub fn energymon_get_interval_osp_polling(em: *const energymon) -> uint64_t;
pub fn energymon_get_precision_osp_polling(em: *const energymon) -> uint64_t;
|
pub fn energymon_is_exclusive_osp_polling() -> c_int;
pub fn energymon_get_osp_polling(em: *mut energymon) -> c_int;
}
|
random_line_split
|
|
skia.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/.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
|
#![allow(non_snake_case)]
use libc::*;
pub type SkiaGrContextRef = *mut c_void;
pub type SkiaGrGLInterfaceRef = *const c_void;
#[link(name = "skia")]
extern {
pub fn SkiaGrGLCreateNativeInterface() -> SkiaGrGLInterfaceRef;
pub fn SkiaGrGLInterfaceRetain(anInterface: SkiaGrGLInterfaceRef);
pub fn SkiaGrGLInterfaceRelease(anInterface: SkiaGrGLInterfaceRef);
pub fn SkiaGrGLInterfaceHasExtension(anInterface: SkiaGrGLInterfaceRef, extension: *const c_char) -> bool;
pub fn SkiaGrGLInterfaceGLVersionGreaterThanOrEqualTo(anInterface: SkiaGrGLInterfaceRef, major: i32, minor: i32) -> bool;
pub fn SkiaGrContextCreate(anInterface: SkiaGrGLInterfaceRef) -> SkiaGrContextRef;
pub fn SkiaGrContextRetain(aContext: SkiaGrContextRef);
pub fn SkiaGrContextRelease(aContext: SkiaGrContextRef);
}
|
random_line_split
|
|
zero.rs
|
use crate::driver::cmd::Args;
use crate::gc::bump::BumpAllocator;
use crate::gc::{Address, Collector, GcReason, Region};
use crate::os::{self, MemoryPermission};
use crate::vm::VM;
pub struct ZeroCollector {
start: Address,
end: Address,
alloc: BumpAllocator,
}
impl ZeroCollector {
pub fn new(args: &Args) -> ZeroCollector {
let heap_size: usize = args.max_heap_size();
let reservation = os::reserve_align(heap_size, 0, false);
let start = reservation.start;
let end = start.offset(heap_size);
os::commit_at(start, heap_size, MemoryPermission::ReadWrite);
ZeroCollector {
start,
end,
alloc: BumpAllocator::new(start, end),
}
}
}
impl Collector for ZeroCollector {
fn supports_tlab(&self) -> bool {
true
}
fn alloc_tlab_area(&self, _vm: &VM, size: usize) -> Option<Region> {
let ptr = self.alloc.bump_alloc(size);
if ptr.is_null() {
None
} else {
Some(ptr.region_start(size))
}
}
fn
|
(&self, _vm: &VM, size: usize, _array_ref: bool) -> Address {
self.alloc.bump_alloc(size)
}
fn collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn minor_collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn dump_summary(&self, runtime: f32) {
let mutator = runtime;
let gc = 0.0f32;
println!("GC stats: total={:.1}", runtime);
println!("GC stats: mutator={:.1}", mutator);
println!("GC stats: collection={:.1}", gc);
println!(
"GC summary: 0ms collection (0), {:.1}ms mutator, {:.1}ms total (100% mutator, 0% GC)",
mutator, runtime,
);
}
}
impl Drop for ZeroCollector {
fn drop(&mut self) {
let size = self.end.offset_from(self.start);
os::free(self.start, size);
}
}
|
alloc
|
identifier_name
|
zero.rs
|
use crate::driver::cmd::Args;
use crate::gc::bump::BumpAllocator;
use crate::gc::{Address, Collector, GcReason, Region};
use crate::os::{self, MemoryPermission};
use crate::vm::VM;
pub struct ZeroCollector {
start: Address,
end: Address,
alloc: BumpAllocator,
}
impl ZeroCollector {
pub fn new(args: &Args) -> ZeroCollector {
let heap_size: usize = args.max_heap_size();
let reservation = os::reserve_align(heap_size, 0, false);
let start = reservation.start;
let end = start.offset(heap_size);
os::commit_at(start, heap_size, MemoryPermission::ReadWrite);
ZeroCollector {
start,
end,
alloc: BumpAllocator::new(start, end),
}
}
}
impl Collector for ZeroCollector {
fn supports_tlab(&self) -> bool {
true
}
fn alloc_tlab_area(&self, _vm: &VM, size: usize) -> Option<Region> {
let ptr = self.alloc.bump_alloc(size);
if ptr.is_null()
|
else {
Some(ptr.region_start(size))
}
}
fn alloc(&self, _vm: &VM, size: usize, _array_ref: bool) -> Address {
self.alloc.bump_alloc(size)
}
fn collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn minor_collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn dump_summary(&self, runtime: f32) {
let mutator = runtime;
let gc = 0.0f32;
println!("GC stats: total={:.1}", runtime);
println!("GC stats: mutator={:.1}", mutator);
println!("GC stats: collection={:.1}", gc);
println!(
"GC summary: 0ms collection (0), {:.1}ms mutator, {:.1}ms total (100% mutator, 0% GC)",
mutator, runtime,
);
}
}
impl Drop for ZeroCollector {
fn drop(&mut self) {
let size = self.end.offset_from(self.start);
os::free(self.start, size);
}
}
|
{
None
}
|
conditional_block
|
zero.rs
|
use crate::driver::cmd::Args;
use crate::gc::bump::BumpAllocator;
use crate::gc::{Address, Collector, GcReason, Region};
use crate::os::{self, MemoryPermission};
use crate::vm::VM;
pub struct ZeroCollector {
start: Address,
end: Address,
alloc: BumpAllocator,
}
impl ZeroCollector {
pub fn new(args: &Args) -> ZeroCollector
|
}
impl Collector for ZeroCollector {
fn supports_tlab(&self) -> bool {
true
}
fn alloc_tlab_area(&self, _vm: &VM, size: usize) -> Option<Region> {
let ptr = self.alloc.bump_alloc(size);
if ptr.is_null() {
None
} else {
Some(ptr.region_start(size))
}
}
fn alloc(&self, _vm: &VM, size: usize, _array_ref: bool) -> Address {
self.alloc.bump_alloc(size)
}
fn collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn minor_collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn dump_summary(&self, runtime: f32) {
let mutator = runtime;
let gc = 0.0f32;
println!("GC stats: total={:.1}", runtime);
println!("GC stats: mutator={:.1}", mutator);
println!("GC stats: collection={:.1}", gc);
println!(
"GC summary: 0ms collection (0), {:.1}ms mutator, {:.1}ms total (100% mutator, 0% GC)",
mutator, runtime,
);
}
}
impl Drop for ZeroCollector {
fn drop(&mut self) {
let size = self.end.offset_from(self.start);
os::free(self.start, size);
}
}
|
{
let heap_size: usize = args.max_heap_size();
let reservation = os::reserve_align(heap_size, 0, false);
let start = reservation.start;
let end = start.offset(heap_size);
os::commit_at(start, heap_size, MemoryPermission::ReadWrite);
ZeroCollector {
start,
end,
alloc: BumpAllocator::new(start, end),
}
}
|
identifier_body
|
zero.rs
|
use crate::driver::cmd::Args;
use crate::gc::bump::BumpAllocator;
use crate::gc::{Address, Collector, GcReason, Region};
use crate::os::{self, MemoryPermission};
use crate::vm::VM;
pub struct ZeroCollector {
start: Address,
end: Address,
alloc: BumpAllocator,
}
impl ZeroCollector {
pub fn new(args: &Args) -> ZeroCollector {
let heap_size: usize = args.max_heap_size();
let reservation = os::reserve_align(heap_size, 0, false);
let start = reservation.start;
let end = start.offset(heap_size);
os::commit_at(start, heap_size, MemoryPermission::ReadWrite);
ZeroCollector {
start,
end,
alloc: BumpAllocator::new(start, end),
}
}
}
impl Collector for ZeroCollector {
fn supports_tlab(&self) -> bool {
true
}
fn alloc_tlab_area(&self, _vm: &VM, size: usize) -> Option<Region> {
let ptr = self.alloc.bump_alloc(size);
if ptr.is_null() {
None
} else {
Some(ptr.region_start(size))
}
}
fn alloc(&self, _vm: &VM, size: usize, _array_ref: bool) -> Address {
self.alloc.bump_alloc(size)
}
fn collect(&self, _: &VM, _: GcReason) {
// do nothing
}
|
// do nothing
}
fn dump_summary(&self, runtime: f32) {
let mutator = runtime;
let gc = 0.0f32;
println!("GC stats: total={:.1}", runtime);
println!("GC stats: mutator={:.1}", mutator);
println!("GC stats: collection={:.1}", gc);
println!(
"GC summary: 0ms collection (0), {:.1}ms mutator, {:.1}ms total (100% mutator, 0% GC)",
mutator, runtime,
);
}
}
impl Drop for ZeroCollector {
fn drop(&mut self) {
let size = self.end.offset_from(self.start);
os::free(self.start, size);
}
}
|
fn minor_collect(&self, _: &VM, _: GcReason) {
|
random_line_split
|
position.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/. */
//! CSS handling for the computed value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.org/css-backgrounds-3/#position
use cssparser::ToCss;
use std::fmt;
use values::computed::LengthOrPercentage;
#[derive(Debug, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Position {
pub horizontal: LengthOrPercentage,
pub vertical: LengthOrPercentage,
}
impl ToCss for Position {
fn
|
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizontal.to_css(dest));
try!(dest.write_str(" "));
try!(self.vertical.to_css(dest));
Ok(())
}
}
|
to_css
|
identifier_name
|
position.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/. */
//! CSS handling for the computed value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.org/css-backgrounds-3/#position
use cssparser::ToCss;
use std::fmt;
use values::computed::LengthOrPercentage;
|
#[derive(Debug, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Position {
pub horizontal: LengthOrPercentage,
pub vertical: LengthOrPercentage,
}
impl ToCss for Position {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizontal.to_css(dest));
try!(dest.write_str(" "));
try!(self.vertical.to_css(dest));
Ok(())
}
}
|
random_line_split
|
|
lint-dead-code-5.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.
#![allow(unused_variables)]
#![deny(dead_code)]
enum Enum1 {
Variant1(isize),
Variant2 //~ ERROR: variant is never constructed
}
enum Enum2 {
Variant3(bool),
|
Variant5 { _x: isize }, //~ ERROR: variant is never constructed: `Variant5`
Variant6(isize), //~ ERROR: variant is never constructed: `Variant6`
_Variant7,
}
enum Enum3 { //~ ERROR: enum is never used
Variant8,
Variant9
}
fn main() {
let v = Enum1::Variant1(1);
match v {
Enum1::Variant1(_) => (),
Enum1::Variant2 => ()
}
let x = Enum2::Variant3(true);
}
|
#[allow(dead_code)]
Variant4(isize),
|
random_line_split
|
lint-dead-code-5.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.
#![allow(unused_variables)]
#![deny(dead_code)]
enum Enum1 {
Variant1(isize),
Variant2 //~ ERROR: variant is never constructed
}
enum Enum2 {
Variant3(bool),
#[allow(dead_code)]
Variant4(isize),
Variant5 { _x: isize }, //~ ERROR: variant is never constructed: `Variant5`
Variant6(isize), //~ ERROR: variant is never constructed: `Variant6`
_Variant7,
}
enum
|
{ //~ ERROR: enum is never used
Variant8,
Variant9
}
fn main() {
let v = Enum1::Variant1(1);
match v {
Enum1::Variant1(_) => (),
Enum1::Variant2 => ()
}
let x = Enum2::Variant3(true);
}
|
Enum3
|
identifier_name
|
space.rs
|
use parking_lot::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::gc::arena;
use crate::gc::{Address, Region};
use crate::mem;
/// Configuration for a space.
/// This makes it possible to use `Space` both for the
/// code space and the permanent space.
pub struct SpaceConfig {
pub executable: bool,
pub chunk: usize,
pub limit: usize,
pub align: usize,
}
fn adapt_to_page_size(config: SpaceConfig) -> SpaceConfig {
SpaceConfig {
executable: config.executable,
chunk: mem::page_align(config.chunk),
limit: mem::page_align(config.limit),
align: config.align,
}
}
/// Non-contiguous space of memory. Used for permanent space
/// and code space.
pub struct Space {
name: &'static str,
config: SpaceConfig,
total: Region,
top: AtomicUsize,
end: AtomicUsize,
allocate: Mutex<()>,
}
impl Space {
/// initializes `Space` and reserves the maximum size.
pub fn new(config: SpaceConfig, name: &'static str) -> Space {
let config = adapt_to_page_size(config);
let space_start = arena::reserve(config.limit);
let space_end = space_start.offset(config.limit);
arena::commit(space_start, config.chunk, config.executable);
let end = space_start.offset(config.chunk);
Space {
name,
config,
total: Region::new(space_start, space_end),
top: AtomicUsize::new(space_start.to_usize()),
end: AtomicUsize::new(end.to_usize()),
allocate: Mutex::new(()),
}
}
/// allocate memory in this space. This first tries to allocate space
/// in the current chunk. If this fails a new chunk is allocated.
/// Doesn't use a freelist right now so memory at the end of a chunk
/// is probably lost.
pub fn alloc(&self, size: usize) -> Address {
let size = mem::align_usize(size, self.config.align);
loop {
let ptr = self.raw_alloc(size);
if!ptr.is_null() {
return ptr;
}
if!self.extend(size) {
return Address::null();
}
}
}
fn raw_alloc(&self, size: usize) -> Address {
let mut old = self.top.load(Ordering::Relaxed);
let mut new;
loop {
new = old + size;
if new > self.end.load(Ordering::Relaxed) {
return Address::null();
}
let res = self
.top
.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed);
match res {
Ok(_) => break,
Err(x) => old = x,
}
}
old.into()
}
fn extend(&self, size: usize) -> bool {
let _lock = self.allocate.lock();
let top = self.top.load(Ordering::Relaxed);
let end = self.end.load(Ordering::Relaxed);
if top + size <= end {
return true;
}
let size = size - (end - top);
let size = mem::align_usize(size, self.config.chunk);
let new_end = end + size;
if new_end <= self.total.end.to_usize() {
arena::commit(end.into(), size, self.config.executable);
self.end.store(new_end, Ordering::SeqCst);
true
} else {
false
}
}
pub fn contains(&self, addr: Address) -> bool {
self.total.contains(addr)
}
pub fn
|
(&self) -> Region {
self.total.clone()
}
pub fn used_region(&self) -> Region {
let start = self.total.start;
let end = self.top.load(Ordering::Relaxed).into();
Region::new(start, end)
}
}
|
total
|
identifier_name
|
space.rs
|
use parking_lot::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::gc::arena;
use crate::gc::{Address, Region};
use crate::mem;
/// Configuration for a space.
/// This makes it possible to use `Space` both for the
/// code space and the permanent space.
pub struct SpaceConfig {
pub executable: bool,
pub chunk: usize,
pub limit: usize,
pub align: usize,
}
fn adapt_to_page_size(config: SpaceConfig) -> SpaceConfig {
SpaceConfig {
executable: config.executable,
chunk: mem::page_align(config.chunk),
limit: mem::page_align(config.limit),
align: config.align,
}
}
/// Non-contiguous space of memory. Used for permanent space
/// and code space.
pub struct Space {
name: &'static str,
config: SpaceConfig,
total: Region,
top: AtomicUsize,
end: AtomicUsize,
allocate: Mutex<()>,
}
impl Space {
/// initializes `Space` and reserves the maximum size.
pub fn new(config: SpaceConfig, name: &'static str) -> Space {
let config = adapt_to_page_size(config);
let space_start = arena::reserve(config.limit);
let space_end = space_start.offset(config.limit);
arena::commit(space_start, config.chunk, config.executable);
let end = space_start.offset(config.chunk);
Space {
name,
config,
total: Region::new(space_start, space_end),
top: AtomicUsize::new(space_start.to_usize()),
end: AtomicUsize::new(end.to_usize()),
allocate: Mutex::new(()),
}
}
/// allocate memory in this space. This first tries to allocate space
/// in the current chunk. If this fails a new chunk is allocated.
/// Doesn't use a freelist right now so memory at the end of a chunk
/// is probably lost.
pub fn alloc(&self, size: usize) -> Address {
let size = mem::align_usize(size, self.config.align);
loop {
let ptr = self.raw_alloc(size);
if!ptr.is_null() {
return ptr;
}
if!self.extend(size) {
return Address::null();
}
}
}
fn raw_alloc(&self, size: usize) -> Address {
let mut old = self.top.load(Ordering::Relaxed);
let mut new;
loop {
new = old + size;
if new > self.end.load(Ordering::Relaxed) {
return Address::null();
}
let res = self
.top
.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed);
match res {
Ok(_) => break,
Err(x) => old = x,
}
}
old.into()
}
fn extend(&self, size: usize) -> bool {
let _lock = self.allocate.lock();
let top = self.top.load(Ordering::Relaxed);
let end = self.end.load(Ordering::Relaxed);
if top + size <= end
|
let size = size - (end - top);
let size = mem::align_usize(size, self.config.chunk);
let new_end = end + size;
if new_end <= self.total.end.to_usize() {
arena::commit(end.into(), size, self.config.executable);
self.end.store(new_end, Ordering::SeqCst);
true
} else {
false
}
}
pub fn contains(&self, addr: Address) -> bool {
self.total.contains(addr)
}
pub fn total(&self) -> Region {
self.total.clone()
}
pub fn used_region(&self) -> Region {
let start = self.total.start;
let end = self.top.load(Ordering::Relaxed).into();
Region::new(start, end)
}
}
|
{
return true;
}
|
conditional_block
|
space.rs
|
use parking_lot::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::gc::arena;
use crate::gc::{Address, Region};
use crate::mem;
/// Configuration for a space.
/// This makes it possible to use `Space` both for the
/// code space and the permanent space.
pub struct SpaceConfig {
pub executable: bool,
pub chunk: usize,
pub limit: usize,
pub align: usize,
}
fn adapt_to_page_size(config: SpaceConfig) -> SpaceConfig {
SpaceConfig {
executable: config.executable,
chunk: mem::page_align(config.chunk),
limit: mem::page_align(config.limit),
align: config.align,
}
}
/// Non-contiguous space of memory. Used for permanent space
/// and code space.
pub struct Space {
name: &'static str,
config: SpaceConfig,
total: Region,
top: AtomicUsize,
end: AtomicUsize,
allocate: Mutex<()>,
}
impl Space {
/// initializes `Space` and reserves the maximum size.
pub fn new(config: SpaceConfig, name: &'static str) -> Space {
let config = adapt_to_page_size(config);
let space_start = arena::reserve(config.limit);
let space_end = space_start.offset(config.limit);
|
Space {
name,
config,
total: Region::new(space_start, space_end),
top: AtomicUsize::new(space_start.to_usize()),
end: AtomicUsize::new(end.to_usize()),
allocate: Mutex::new(()),
}
}
/// allocate memory in this space. This first tries to allocate space
/// in the current chunk. If this fails a new chunk is allocated.
/// Doesn't use a freelist right now so memory at the end of a chunk
/// is probably lost.
pub fn alloc(&self, size: usize) -> Address {
let size = mem::align_usize(size, self.config.align);
loop {
let ptr = self.raw_alloc(size);
if!ptr.is_null() {
return ptr;
}
if!self.extend(size) {
return Address::null();
}
}
}
fn raw_alloc(&self, size: usize) -> Address {
let mut old = self.top.load(Ordering::Relaxed);
let mut new;
loop {
new = old + size;
if new > self.end.load(Ordering::Relaxed) {
return Address::null();
}
let res = self
.top
.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed);
match res {
Ok(_) => break,
Err(x) => old = x,
}
}
old.into()
}
fn extend(&self, size: usize) -> bool {
let _lock = self.allocate.lock();
let top = self.top.load(Ordering::Relaxed);
let end = self.end.load(Ordering::Relaxed);
if top + size <= end {
return true;
}
let size = size - (end - top);
let size = mem::align_usize(size, self.config.chunk);
let new_end = end + size;
if new_end <= self.total.end.to_usize() {
arena::commit(end.into(), size, self.config.executable);
self.end.store(new_end, Ordering::SeqCst);
true
} else {
false
}
}
pub fn contains(&self, addr: Address) -> bool {
self.total.contains(addr)
}
pub fn total(&self) -> Region {
self.total.clone()
}
pub fn used_region(&self) -> Region {
let start = self.total.start;
let end = self.top.load(Ordering::Relaxed).into();
Region::new(start, end)
}
}
|
arena::commit(space_start, config.chunk, config.executable);
let end = space_start.offset(config.chunk);
|
random_line_split
|
thread_dummy.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.
//! No threads
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(hidden)]
use prelude::v1::*;
use any::Any;
use fmt;
use rt::unwind;
use time::Duration;
use sys_common::thread_info;
#[stable(feature = "rust1", since = "1.0.0")]
pub fn current() -> Thread {
Thread
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn yield_now() {
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool {
unwind::panicking()
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn park() {
}
#[unstable(feature = "std_misc", reason = "recently introduced, depends on Duration")]
pub fn park_timeout(_: Duration) {
}
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Thread;
impl Thread {
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn current() -> Thread {
Thread
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "name may change")]
pub fn yield_now() {
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool {
unwind::panicking()
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "recently introduced")]
pub fn park() {
|
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "recently introduced")]
pub fn park_timeout(_: Duration) {
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unpark(&self) {
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn name(&self) -> Option<&str> {
Some("main")
}
}
impl thread_info::NewThread for Thread {
fn new(_: Option<String>) -> Thread { Thread }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Thread {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.name(), f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
pub type Result<T> = ::result::Result<T, Box<Any + Send +'static>>;
|
}
/// Deprecated: use module-level free function.
|
random_line_split
|
thread_dummy.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.
//! No threads
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(hidden)]
use prelude::v1::*;
use any::Any;
use fmt;
use rt::unwind;
use time::Duration;
use sys_common::thread_info;
#[stable(feature = "rust1", since = "1.0.0")]
pub fn current() -> Thread
|
#[stable(feature = "rust1", since = "1.0.0")]
pub fn yield_now() {
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool {
unwind::panicking()
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn park() {
}
#[unstable(feature = "std_misc", reason = "recently introduced, depends on Duration")]
pub fn park_timeout(_: Duration) {
}
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Thread;
impl Thread {
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn current() -> Thread {
Thread
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "name may change")]
pub fn yield_now() {
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool {
unwind::panicking()
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "recently introduced")]
pub fn park() {
}
/// Deprecated: use module-level free function.
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "recently introduced")]
pub fn park_timeout(_: Duration) {
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unpark(&self) {
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn name(&self) -> Option<&str> {
Some("main")
}
}
impl thread_info::NewThread for Thread {
fn new(_: Option<String>) -> Thread { Thread }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Thread {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.name(), f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
pub type Result<T> = ::result::Result<T, Box<Any + Send +'static>>;
|
{
Thread
}
|
identifier_body
|
thread_dummy.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.
//! No threads
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(hidden)]
use prelude::v1::*;
use any::Any;
use fmt;
use rt::unwind;
use time::Duration;
use sys_common::thread_info;
#[stable(feature = "rust1", since = "1.0.0")]
pub fn current() -> Thread {
Thread
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn yield_now() {
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool {
unwind::panicking()
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn park() {
}
#[unstable(feature = "std_misc", reason = "recently introduced, depends on Duration")]
pub fn park_timeout(_: Duration) {
}
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Thread;
impl Thread {
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn
|
() -> Thread {
Thread
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "name may change")]
pub fn yield_now() {
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool {
unwind::panicking()
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "recently introduced")]
pub fn park() {
}
/// Deprecated: use module-level free function.
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "recently introduced")]
pub fn park_timeout(_: Duration) {
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unpark(&self) {
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn name(&self) -> Option<&str> {
Some("main")
}
}
impl thread_info::NewThread for Thread {
fn new(_: Option<String>) -> Thread { Thread }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Thread {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.name(), f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
pub type Result<T> = ::result::Result<T, Box<Any + Send +'static>>;
|
current
|
identifier_name
|
logger.rs
|
// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use core::fmt::Write;
use log::{LogLevelFilter, LogMetadata, SetLoggerError, ShutdownLoggerError};
pub struct
|
;
impl SimpleLogger {
pub fn new() -> Self {
SimpleLogger
}
pub fn init(&self) -> Result<(), SetLoggerError> {
unsafe {
log::set_logger_raw(move |max_log_level| {
max_log_level.set(LogLevelFilter::Info);
self.ptr()
})
}
}
fn flush(&self) {}
fn ptr(&self) -> *const log::Log {
&*self
}
}
impl log::Log for SimpleLogger {
fn enabled(&self, _: &LogMetadata) -> bool {
false
}
fn log(&self, record: &log::LogRecord) {
unsafe {
crate::CONSOLE
.write_fmt(format_args!(
"{} [{}] - {}\n",
record.level(),
record.target(),
record.args()
))
.unwrap();
}
}
}
pub fn shutdown() -> Result<(), ShutdownLoggerError> {
log::shutdown_logger_raw().map(|logger| {
let logger = unsafe { &*(logger as *const SimpleLogger) };
logger.flush();
})
}
|
SimpleLogger
|
identifier_name
|
logger.rs
|
// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use core::fmt::Write;
use log::{LogLevelFilter, LogMetadata, SetLoggerError, ShutdownLoggerError};
pub struct SimpleLogger;
impl SimpleLogger {
pub fn new() -> Self {
SimpleLogger
}
pub fn init(&self) -> Result<(), SetLoggerError> {
unsafe {
log::set_logger_raw(move |max_log_level| {
max_log_level.set(LogLevelFilter::Info);
self.ptr()
})
}
}
fn flush(&self) {}
fn ptr(&self) -> *const log::Log {
&*self
}
}
impl log::Log for SimpleLogger {
fn enabled(&self, _: &LogMetadata) -> bool {
false
}
fn log(&self, record: &log::LogRecord) {
unsafe {
crate::CONSOLE
.write_fmt(format_args!(
"{} [{}] - {}\n",
record.level(),
record.target(),
record.args()
))
.unwrap();
}
}
|
log::shutdown_logger_raw().map(|logger| {
let logger = unsafe { &*(logger as *const SimpleLogger) };
logger.flush();
})
}
|
}
pub fn shutdown() -> Result<(), ShutdownLoggerError> {
|
random_line_split
|
parser.rs
|
use std::str;
use combine::*;
use combine::byte::*;
use combine::primitives::RangeStream;
use combine::range::*;
use types::Source;
/// Whether or not a character is valid for a nickname when it is not the first character.
fn is_nick_trailing_char(c: u8) -> bool {
match c {
b'A'...b'Z'
| b'a'...b'z'
| b'0'...b'9'
| b'['
| b']'
| b'`'
| b'^'
| b'\\'
| b'-'
| b'{'
| b'}' => true,
_ => false,
}
}
/// Whether or not a character is valid for an ident.
///
/// RFC 1459 and 2811 only go so far as to specify it must be non-whitespace. However,
/// in practice, they are limited to alphanumeric + `~`.
///
/// As such, this will accept non-compliant identifiers, but they will be valid for the server that
/// sends them.
fn is_ident_char(c: u8) -> bool {
match c {
b'\0' | b''| b'\t' | b'\r' | b'\n' | b'@' => false,
_ => true,
}
}
/// Whether or not a character is valid for a hostname.
///
/// This will result in accepting not-strictly-compliant hostnames, but some IRCDs (e.g., Freenode)
/// will provide vhosts that are not FQDNs, such as `unaffilliated/username`.
fn is_host_char(c: u8) -> bool {
match c {
b'\0' | b''| b'\t' | b'\r' | b'\n' => false,
_ => true,
}
}
/// Parse the source of a message.
pub fn source<'a, I>() -> impl Parser<Input = I, Output = Source>
where
I: RangeStream<Item = u8, Range = &'a [u8]>,
I::Error: ParseError<u8, &'a [u8], I::Position>,
<I::Error as ParseError<I::Item, I::Range, I::Position>>::StreamError: From<str::Utf8Error>,
|
),
host().map(|host| {
let host = unsafe { str::from_utf8_unchecked(host) };
Source::Server { host: host.into() }
})
)
}
|
{
let nick = || recognize((letter(), skip_many(satisfy(is_nick_trailing_char))));
let ident = || take_while1(is_ident_char);
let host = || take_while1(is_host_char);
let user = || (nick().skip(byte(b'!')), ident().skip(byte(b'@')), host());
choice!(
try(
user().and_then(|(nick, ident, host)| -> Result<Source, str::Utf8Error> {
let nick = unsafe { str::from_utf8_unchecked(nick) };
let ident = str::from_utf8(ident)?;
let host = str::from_utf8(host)?;
Ok(Source::User {
nick: nick.into(),
ident: ident.into(),
host: host.into(),
})
})
|
identifier_body
|
parser.rs
|
use std::str;
use combine::*;
use combine::byte::*;
use combine::primitives::RangeStream;
use combine::range::*;
use types::Source;
/// Whether or not a character is valid for a nickname when it is not the first character.
fn
|
(c: u8) -> bool {
match c {
b'A'...b'Z'
| b'a'...b'z'
| b'0'...b'9'
| b'['
| b']'
| b'`'
| b'^'
| b'\\'
| b'-'
| b'{'
| b'}' => true,
_ => false,
}
}
/// Whether or not a character is valid for an ident.
///
/// RFC 1459 and 2811 only go so far as to specify it must be non-whitespace. However,
/// in practice, they are limited to alphanumeric + `~`.
///
/// As such, this will accept non-compliant identifiers, but they will be valid for the server that
/// sends them.
fn is_ident_char(c: u8) -> bool {
match c {
b'\0' | b''| b'\t' | b'\r' | b'\n' | b'@' => false,
_ => true,
}
}
/// Whether or not a character is valid for a hostname.
///
/// This will result in accepting not-strictly-compliant hostnames, but some IRCDs (e.g., Freenode)
/// will provide vhosts that are not FQDNs, such as `unaffilliated/username`.
fn is_host_char(c: u8) -> bool {
match c {
b'\0' | b''| b'\t' | b'\r' | b'\n' => false,
_ => true,
}
}
/// Parse the source of a message.
pub fn source<'a, I>() -> impl Parser<Input = I, Output = Source>
where
I: RangeStream<Item = u8, Range = &'a [u8]>,
I::Error: ParseError<u8, &'a [u8], I::Position>,
<I::Error as ParseError<I::Item, I::Range, I::Position>>::StreamError: From<str::Utf8Error>,
{
let nick = || recognize((letter(), skip_many(satisfy(is_nick_trailing_char))));
let ident = || take_while1(is_ident_char);
let host = || take_while1(is_host_char);
let user = || (nick().skip(byte(b'!')), ident().skip(byte(b'@')), host());
choice!(
try(
user().and_then(|(nick, ident, host)| -> Result<Source, str::Utf8Error> {
let nick = unsafe { str::from_utf8_unchecked(nick) };
let ident = str::from_utf8(ident)?;
let host = str::from_utf8(host)?;
Ok(Source::User {
nick: nick.into(),
ident: ident.into(),
host: host.into(),
})
})
),
host().map(|host| {
let host = unsafe { str::from_utf8_unchecked(host) };
Source::Server { host: host.into() }
})
)
}
|
is_nick_trailing_char
|
identifier_name
|
parser.rs
|
use std::str;
use combine::*;
use combine::byte::*;
use combine::primitives::RangeStream;
use combine::range::*;
use types::Source;
/// Whether or not a character is valid for a nickname when it is not the first character.
fn is_nick_trailing_char(c: u8) -> bool {
match c {
b'A'...b'Z'
| b'a'...b'z'
| b'0'...b'9'
| b'['
| b']'
| b'`'
| b'^'
| b'\\'
| b'-'
| b'{'
| b'}' => true,
_ => false,
}
}
/// Whether or not a character is valid for an ident.
///
/// RFC 1459 and 2811 only go so far as to specify it must be non-whitespace. However,
/// in practice, they are limited to alphanumeric + `~`.
///
/// As such, this will accept non-compliant identifiers, but they will be valid for the server that
/// sends them.
fn is_ident_char(c: u8) -> bool {
match c {
b'\0' | b''| b'\t' | b'\r' | b'\n' | b'@' => false,
_ => true,
}
}
/// Whether or not a character is valid for a hostname.
///
/// This will result in accepting not-strictly-compliant hostnames, but some IRCDs (e.g., Freenode)
/// will provide vhosts that are not FQDNs, such as `unaffilliated/username`.
fn is_host_char(c: u8) -> bool {
match c {
b'\0' | b''| b'\t' | b'\r' | b'\n' => false,
|
}
}
/// Parse the source of a message.
pub fn source<'a, I>() -> impl Parser<Input = I, Output = Source>
where
I: RangeStream<Item = u8, Range = &'a [u8]>,
I::Error: ParseError<u8, &'a [u8], I::Position>,
<I::Error as ParseError<I::Item, I::Range, I::Position>>::StreamError: From<str::Utf8Error>,
{
let nick = || recognize((letter(), skip_many(satisfy(is_nick_trailing_char))));
let ident = || take_while1(is_ident_char);
let host = || take_while1(is_host_char);
let user = || (nick().skip(byte(b'!')), ident().skip(byte(b'@')), host());
choice!(
try(
user().and_then(|(nick, ident, host)| -> Result<Source, str::Utf8Error> {
let nick = unsafe { str::from_utf8_unchecked(nick) };
let ident = str::from_utf8(ident)?;
let host = str::from_utf8(host)?;
Ok(Source::User {
nick: nick.into(),
ident: ident.into(),
host: host.into(),
})
})
),
host().map(|host| {
let host = unsafe { str::from_utf8_unchecked(host) };
Source::Server { host: host.into() }
})
)
}
|
_ => true,
|
random_line_split
|
features.rs
|
//! Feature tests for OS functionality
pub use self::os::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod os {
use crate::sys::utsname::uname;
// Features:
// * atomic cloexec on socket: 2.6.27
// * pipe2: 2.6.27
// * accept4: 2.6.28
static VERS_UNKNOWN: usize = 1;
static VERS_2_6_18: usize = 2;
static VERS_2_6_27: usize = 3;
static VERS_2_6_28: usize = 4;
static VERS_3: usize = 5;
#[inline]
fn digit(dst: &mut usize, b: u8) {
*dst *= 10;
*dst += (b - b'0') as usize;
}
fn parse_kernel_version() -> usize {
let u = uname();
let mut curr: usize = 0;
let mut major: usize = 0;
let mut minor: usize = 0;
let mut patch: usize = 0;
for b in u.release().bytes() {
if curr >= 3 {
break;
}
match b {
b'.' | b'-' => {
curr += 1;
}
b'0'..=b'9' => {
match curr {
0 => digit(&mut major, b),
1 => digit(&mut minor, b),
_ => digit(&mut patch, b),
}
}
_ => break,
}
}
if major >= 3 {
VERS_3
} else if major >= 2 {
if minor >= 7 {
VERS_UNKNOWN
} else if minor >= 6 {
if patch >= 28 {
VERS_2_6_28
} else if patch >= 27 {
VERS_2_6_27
} else {
VERS_2_6_18
}
} else {
VERS_UNKNOWN
}
} else {
VERS_UNKNOWN
}
}
fn kernel_version() -> usize {
static mut KERNEL_VERS: usize = 0;
unsafe {
if KERNEL_VERS == 0 {
KERNEL_VERS = parse_kernel_version();
}
KERNEL_VERS
}
}
/// Check if the OS supports atomic close-on-exec for sockets
pub fn
|
() -> bool {
kernel_version() >= VERS_2_6_27
}
#[test]
pub fn test_parsing_kernel_version() {
assert!(kernel_version() > 0);
}
}
#[cfg(any(target_os = "illumos"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
true
}
}
#[cfg(any(target_os = "macos", target_os = "freebsd",
target_os = "dragonfly", target_os = "ios",
target_os = "openbsd", target_os = "netbsd",
target_os = "redox", target_os = "fuchsia",
target_os = "solaris"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
false
}
}
|
socket_atomic_cloexec
|
identifier_name
|
features.rs
|
//! Feature tests for OS functionality
pub use self::os::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod os {
use crate::sys::utsname::uname;
// Features:
// * atomic cloexec on socket: 2.6.27
// * pipe2: 2.6.27
// * accept4: 2.6.28
static VERS_UNKNOWN: usize = 1;
static VERS_2_6_18: usize = 2;
static VERS_2_6_27: usize = 3;
static VERS_2_6_28: usize = 4;
static VERS_3: usize = 5;
#[inline]
fn digit(dst: &mut usize, b: u8) {
*dst *= 10;
*dst += (b - b'0') as usize;
}
fn parse_kernel_version() -> usize {
let u = uname();
let mut curr: usize = 0;
let mut major: usize = 0;
let mut minor: usize = 0;
let mut patch: usize = 0;
for b in u.release().bytes() {
if curr >= 3 {
break;
}
match b {
b'.' | b'-' => {
curr += 1;
}
b'0'..=b'9' => {
match curr {
0 => digit(&mut major, b),
1 => digit(&mut minor, b),
_ => digit(&mut patch, b),
}
}
_ => break,
}
}
if major >= 3
|
else if major >= 2 {
if minor >= 7 {
VERS_UNKNOWN
} else if minor >= 6 {
if patch >= 28 {
VERS_2_6_28
} else if patch >= 27 {
VERS_2_6_27
} else {
VERS_2_6_18
}
} else {
VERS_UNKNOWN
}
} else {
VERS_UNKNOWN
}
}
fn kernel_version() -> usize {
static mut KERNEL_VERS: usize = 0;
unsafe {
if KERNEL_VERS == 0 {
KERNEL_VERS = parse_kernel_version();
}
KERNEL_VERS
}
}
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
kernel_version() >= VERS_2_6_27
}
#[test]
pub fn test_parsing_kernel_version() {
assert!(kernel_version() > 0);
}
}
#[cfg(any(target_os = "illumos"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
true
}
}
#[cfg(any(target_os = "macos", target_os = "freebsd",
target_os = "dragonfly", target_os = "ios",
target_os = "openbsd", target_os = "netbsd",
target_os = "redox", target_os = "fuchsia",
target_os = "solaris"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
false
}
}
|
{
VERS_3
}
|
conditional_block
|
features.rs
|
//! Feature tests for OS functionality
pub use self::os::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod os {
use crate::sys::utsname::uname;
// Features:
// * atomic cloexec on socket: 2.6.27
// * pipe2: 2.6.27
// * accept4: 2.6.28
static VERS_UNKNOWN: usize = 1;
static VERS_2_6_18: usize = 2;
static VERS_2_6_27: usize = 3;
static VERS_2_6_28: usize = 4;
static VERS_3: usize = 5;
#[inline]
fn digit(dst: &mut usize, b: u8) {
*dst *= 10;
*dst += (b - b'0') as usize;
}
fn parse_kernel_version() -> usize {
let u = uname();
let mut curr: usize = 0;
let mut major: usize = 0;
let mut minor: usize = 0;
let mut patch: usize = 0;
for b in u.release().bytes() {
if curr >= 3 {
break;
}
match b {
b'.' | b'-' => {
curr += 1;
}
b'0'..=b'9' => {
match curr {
0 => digit(&mut major, b),
1 => digit(&mut minor, b),
_ => digit(&mut patch, b),
}
}
_ => break,
}
}
if major >= 3 {
VERS_3
} else if major >= 2 {
if minor >= 7 {
VERS_UNKNOWN
} else if minor >= 6 {
if patch >= 28 {
VERS_2_6_28
} else if patch >= 27 {
VERS_2_6_27
} else {
VERS_2_6_18
}
} else {
VERS_UNKNOWN
}
} else {
VERS_UNKNOWN
}
}
fn kernel_version() -> usize {
static mut KERNEL_VERS: usize = 0;
unsafe {
if KERNEL_VERS == 0 {
KERNEL_VERS = parse_kernel_version();
}
KERNEL_VERS
}
}
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
kernel_version() >= VERS_2_6_27
}
#[test]
pub fn test_parsing_kernel_version() {
assert!(kernel_version() > 0);
}
}
#[cfg(any(target_os = "illumos"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
true
}
}
|
target_os = "openbsd", target_os = "netbsd",
target_os = "redox", target_os = "fuchsia",
target_os = "solaris"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
false
}
}
|
#[cfg(any(target_os = "macos", target_os = "freebsd",
target_os = "dragonfly", target_os = "ios",
|
random_line_split
|
features.rs
|
//! Feature tests for OS functionality
pub use self::os::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod os {
use crate::sys::utsname::uname;
// Features:
// * atomic cloexec on socket: 2.6.27
// * pipe2: 2.6.27
// * accept4: 2.6.28
static VERS_UNKNOWN: usize = 1;
static VERS_2_6_18: usize = 2;
static VERS_2_6_27: usize = 3;
static VERS_2_6_28: usize = 4;
static VERS_3: usize = 5;
#[inline]
fn digit(dst: &mut usize, b: u8)
|
fn parse_kernel_version() -> usize {
let u = uname();
let mut curr: usize = 0;
let mut major: usize = 0;
let mut minor: usize = 0;
let mut patch: usize = 0;
for b in u.release().bytes() {
if curr >= 3 {
break;
}
match b {
b'.' | b'-' => {
curr += 1;
}
b'0'..=b'9' => {
match curr {
0 => digit(&mut major, b),
1 => digit(&mut minor, b),
_ => digit(&mut patch, b),
}
}
_ => break,
}
}
if major >= 3 {
VERS_3
} else if major >= 2 {
if minor >= 7 {
VERS_UNKNOWN
} else if minor >= 6 {
if patch >= 28 {
VERS_2_6_28
} else if patch >= 27 {
VERS_2_6_27
} else {
VERS_2_6_18
}
} else {
VERS_UNKNOWN
}
} else {
VERS_UNKNOWN
}
}
fn kernel_version() -> usize {
static mut KERNEL_VERS: usize = 0;
unsafe {
if KERNEL_VERS == 0 {
KERNEL_VERS = parse_kernel_version();
}
KERNEL_VERS
}
}
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
kernel_version() >= VERS_2_6_27
}
#[test]
pub fn test_parsing_kernel_version() {
assert!(kernel_version() > 0);
}
}
#[cfg(any(target_os = "illumos"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
true
}
}
#[cfg(any(target_os = "macos", target_os = "freebsd",
target_os = "dragonfly", target_os = "ios",
target_os = "openbsd", target_os = "netbsd",
target_os = "redox", target_os = "fuchsia",
target_os = "solaris"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
false
}
}
|
{
*dst *= 10;
*dst += (b - b'0') as usize;
}
|
identifier_body
|
main.rs
|
mod system;
mod math;
mod renderer;
mod canvas;
use renderer::context::*;
use renderer::mesh;
use renderer::shader::{Program, Shader, ShaderType};
use renderer::texture;
use math::mat4::*;
use math::transform;
use math::vec3::*;
use canvas::Canvas;
extern crate rand;
extern crate time;
extern crate gl;
extern crate specs;
use specs::Join;
use gl::types::*;
use std::mem;
use std::ptr;
use std::ffi::CString;
use rand::Rng;
// Vertex data
static VERTEX_DATA: [GLfloat; 9] = [
200.0, 100.5, 0.11,
100.5, 200.5, 0.11,
300.5, 200.5, 0.11
];
static VERTEX_TEX_DATA: [GLfloat; 6] = [
0.5, 0.0,
0.0, 1.0,
1.0, 1.0
];
static INDEX_DATA: [u32; 3] = [
0, 1, 2
];
#[derive(Clone, Debug)]
struct CompPos(f32,f32);
impl specs::Component for CompPos{
type Storage = specs::VecStorage<CompPos>;
}
#[derive(Clone, Debug)]
struct CompVel(f32,f32);
impl specs::Component for CompVel{
type Storage = specs::VecStorage<CompVel>;
}
struct
|
(mesh::Mesh);
impl specs::Component for CompMesh{
type Storage = specs::VecStorage<CompMesh>;
}
fn main() {
let mut VERTEX_COL_DATA: [GLfloat; 12] = [
1.0, 1.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
0.0, 1.0, 1.0, 1.0
];
let mut ctx = Context::new("data/config.json");
let t = texture::Texture::from_image("data/rust.png");
let mut program = Program::new();
let vs = Shader::new(ShaderType::VERTEX,"data/shaders/test.vs".to_string());
let fs = Shader::new(ShaderType::FRAGMENT,"data/shaders/test.frag".to_string());
program.attach(&vs);
program.attach(&fs);
program.link();
program.register_uniform("ProjMatrix");
program.register_uniform("ModelMatrix");
program.register_uniform("diffuseTexture");
let mut m0 = mesh::Mesh::new(&VERTEX_DATA, &INDEX_DATA, Some(&VERTEX_TEX_DATA), Some(&VERTEX_COL_DATA));
program.set_uniform_matrix4fv("ProjMatrix", &ctx.proj_matrix_2d);
program.set_uniform_matrix4fv("ModelMatrix", &Mat4::identity());
program.set_uniform_1i("diffuseTexture", 0);
let mut canvas_program = Program::new();
let canvas_vs = Shader::new(ShaderType::VERTEX, "data/shaders/canvas.vs".to_string());
let canvas_fs = Shader::new(ShaderType::FRAGMENT, "data/shaders/canvas.frag".to_string());
canvas_program.attach(&canvas_vs);
canvas_program.attach(&canvas_fs);
canvas_program.link();
canvas_program.register_uniform("ProjMatrix");
canvas_program.register_uniform("ModelMatrix");
canvas_program.register_uniform("backColor");
canvas_program.register_uniform("diffuseTexture");
canvas_program.register_uniform("canvasPosition");
canvas_program.register_uniform("canvasSize");
canvas_program.set_uniform_matrix4fv("ProjMatrix", &ctx.proj_matrix_2d);
canvas_program.set_uniform_1i("diffuseTexture", 0);
let mut canvas1 = Canvas::new((400, 200), (200, 100), &canvas_program);
let mut rng = rand::thread_rng();
let mut start_time = time::now();
let mut accum = 0.0;
while ctx.is_running() {
ctx.start_frame();
let frame_time = time::now();
let elapsed_duration = frame_time - start_time;
start_time = frame_time;
let mut elapsed = elapsed_duration.num_seconds() as f64;
elapsed += (elapsed_duration.num_milliseconds() as f64) / 1_000.0;
accum += elapsed;
if accum >= 1.0 {
accum -= 1.0;
// try modifying tri color
for i in 0..12 {
if i % 4!= 0 {
VERTEX_COL_DATA[i] = rng.gen::<f32>();
}
}
m0.update_buffer(mesh::MeshAttrib::Color, &VERTEX_COL_DATA);
}
//now we update the systems
program.bind();
t.bind();
m0.render();
canvas_program.bind();
canvas1.update(elapsed);
canvas1.render();
ctx.end_frame();
}
}
|
CompMesh
|
identifier_name
|
main.rs
|
mod system;
mod math;
mod renderer;
mod canvas;
|
use renderer::shader::{Program, Shader, ShaderType};
use renderer::texture;
use math::mat4::*;
use math::transform;
use math::vec3::*;
use canvas::Canvas;
extern crate rand;
extern crate time;
extern crate gl;
extern crate specs;
use specs::Join;
use gl::types::*;
use std::mem;
use std::ptr;
use std::ffi::CString;
use rand::Rng;
// Vertex data
static VERTEX_DATA: [GLfloat; 9] = [
200.0, 100.5, 0.11,
100.5, 200.5, 0.11,
300.5, 200.5, 0.11
];
static VERTEX_TEX_DATA: [GLfloat; 6] = [
0.5, 0.0,
0.0, 1.0,
1.0, 1.0
];
static INDEX_DATA: [u32; 3] = [
0, 1, 2
];
#[derive(Clone, Debug)]
struct CompPos(f32,f32);
impl specs::Component for CompPos{
type Storage = specs::VecStorage<CompPos>;
}
#[derive(Clone, Debug)]
struct CompVel(f32,f32);
impl specs::Component for CompVel{
type Storage = specs::VecStorage<CompVel>;
}
struct CompMesh(mesh::Mesh);
impl specs::Component for CompMesh{
type Storage = specs::VecStorage<CompMesh>;
}
fn main() {
let mut VERTEX_COL_DATA: [GLfloat; 12] = [
1.0, 1.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
0.0, 1.0, 1.0, 1.0
];
let mut ctx = Context::new("data/config.json");
let t = texture::Texture::from_image("data/rust.png");
let mut program = Program::new();
let vs = Shader::new(ShaderType::VERTEX,"data/shaders/test.vs".to_string());
let fs = Shader::new(ShaderType::FRAGMENT,"data/shaders/test.frag".to_string());
program.attach(&vs);
program.attach(&fs);
program.link();
program.register_uniform("ProjMatrix");
program.register_uniform("ModelMatrix");
program.register_uniform("diffuseTexture");
let mut m0 = mesh::Mesh::new(&VERTEX_DATA, &INDEX_DATA, Some(&VERTEX_TEX_DATA), Some(&VERTEX_COL_DATA));
program.set_uniform_matrix4fv("ProjMatrix", &ctx.proj_matrix_2d);
program.set_uniform_matrix4fv("ModelMatrix", &Mat4::identity());
program.set_uniform_1i("diffuseTexture", 0);
let mut canvas_program = Program::new();
let canvas_vs = Shader::new(ShaderType::VERTEX, "data/shaders/canvas.vs".to_string());
let canvas_fs = Shader::new(ShaderType::FRAGMENT, "data/shaders/canvas.frag".to_string());
canvas_program.attach(&canvas_vs);
canvas_program.attach(&canvas_fs);
canvas_program.link();
canvas_program.register_uniform("ProjMatrix");
canvas_program.register_uniform("ModelMatrix");
canvas_program.register_uniform("backColor");
canvas_program.register_uniform("diffuseTexture");
canvas_program.register_uniform("canvasPosition");
canvas_program.register_uniform("canvasSize");
canvas_program.set_uniform_matrix4fv("ProjMatrix", &ctx.proj_matrix_2d);
canvas_program.set_uniform_1i("diffuseTexture", 0);
let mut canvas1 = Canvas::new((400, 200), (200, 100), &canvas_program);
let mut rng = rand::thread_rng();
let mut start_time = time::now();
let mut accum = 0.0;
while ctx.is_running() {
ctx.start_frame();
let frame_time = time::now();
let elapsed_duration = frame_time - start_time;
start_time = frame_time;
let mut elapsed = elapsed_duration.num_seconds() as f64;
elapsed += (elapsed_duration.num_milliseconds() as f64) / 1_000.0;
accum += elapsed;
if accum >= 1.0 {
accum -= 1.0;
// try modifying tri color
for i in 0..12 {
if i % 4!= 0 {
VERTEX_COL_DATA[i] = rng.gen::<f32>();
}
}
m0.update_buffer(mesh::MeshAttrib::Color, &VERTEX_COL_DATA);
}
//now we update the systems
program.bind();
t.bind();
m0.render();
canvas_program.bind();
canvas1.update(elapsed);
canvas1.render();
ctx.end_frame();
}
}
|
use renderer::context::*;
use renderer::mesh;
|
random_line_split
|
main.rs
|
mod system;
mod math;
mod renderer;
mod canvas;
use renderer::context::*;
use renderer::mesh;
use renderer::shader::{Program, Shader, ShaderType};
use renderer::texture;
use math::mat4::*;
use math::transform;
use math::vec3::*;
use canvas::Canvas;
extern crate rand;
extern crate time;
extern crate gl;
extern crate specs;
use specs::Join;
use gl::types::*;
use std::mem;
use std::ptr;
use std::ffi::CString;
use rand::Rng;
// Vertex data
static VERTEX_DATA: [GLfloat; 9] = [
200.0, 100.5, 0.11,
100.5, 200.5, 0.11,
300.5, 200.5, 0.11
];
static VERTEX_TEX_DATA: [GLfloat; 6] = [
0.5, 0.0,
0.0, 1.0,
1.0, 1.0
];
static INDEX_DATA: [u32; 3] = [
0, 1, 2
];
#[derive(Clone, Debug)]
struct CompPos(f32,f32);
impl specs::Component for CompPos{
type Storage = specs::VecStorage<CompPos>;
}
#[derive(Clone, Debug)]
struct CompVel(f32,f32);
impl specs::Component for CompVel{
type Storage = specs::VecStorage<CompVel>;
}
struct CompMesh(mesh::Mesh);
impl specs::Component for CompMesh{
type Storage = specs::VecStorage<CompMesh>;
}
fn main() {
let mut VERTEX_COL_DATA: [GLfloat; 12] = [
1.0, 1.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
0.0, 1.0, 1.0, 1.0
];
let mut ctx = Context::new("data/config.json");
let t = texture::Texture::from_image("data/rust.png");
let mut program = Program::new();
let vs = Shader::new(ShaderType::VERTEX,"data/shaders/test.vs".to_string());
let fs = Shader::new(ShaderType::FRAGMENT,"data/shaders/test.frag".to_string());
program.attach(&vs);
program.attach(&fs);
program.link();
program.register_uniform("ProjMatrix");
program.register_uniform("ModelMatrix");
program.register_uniform("diffuseTexture");
let mut m0 = mesh::Mesh::new(&VERTEX_DATA, &INDEX_DATA, Some(&VERTEX_TEX_DATA), Some(&VERTEX_COL_DATA));
program.set_uniform_matrix4fv("ProjMatrix", &ctx.proj_matrix_2d);
program.set_uniform_matrix4fv("ModelMatrix", &Mat4::identity());
program.set_uniform_1i("diffuseTexture", 0);
let mut canvas_program = Program::new();
let canvas_vs = Shader::new(ShaderType::VERTEX, "data/shaders/canvas.vs".to_string());
let canvas_fs = Shader::new(ShaderType::FRAGMENT, "data/shaders/canvas.frag".to_string());
canvas_program.attach(&canvas_vs);
canvas_program.attach(&canvas_fs);
canvas_program.link();
canvas_program.register_uniform("ProjMatrix");
canvas_program.register_uniform("ModelMatrix");
canvas_program.register_uniform("backColor");
canvas_program.register_uniform("diffuseTexture");
canvas_program.register_uniform("canvasPosition");
canvas_program.register_uniform("canvasSize");
canvas_program.set_uniform_matrix4fv("ProjMatrix", &ctx.proj_matrix_2d);
canvas_program.set_uniform_1i("diffuseTexture", 0);
let mut canvas1 = Canvas::new((400, 200), (200, 100), &canvas_program);
let mut rng = rand::thread_rng();
let mut start_time = time::now();
let mut accum = 0.0;
while ctx.is_running() {
ctx.start_frame();
let frame_time = time::now();
let elapsed_duration = frame_time - start_time;
start_time = frame_time;
let mut elapsed = elapsed_duration.num_seconds() as f64;
elapsed += (elapsed_duration.num_milliseconds() as f64) / 1_000.0;
accum += elapsed;
if accum >= 1.0
|
//now we update the systems
program.bind();
t.bind();
m0.render();
canvas_program.bind();
canvas1.update(elapsed);
canvas1.render();
ctx.end_frame();
}
}
|
{
accum -= 1.0;
// try modifying tri color
for i in 0..12 {
if i % 4 != 0 {
VERTEX_COL_DATA[i] = rng.gen::<f32>();
}
}
m0.update_buffer(mesh::MeshAttrib::Color, &VERTEX_COL_DATA);
}
|
conditional_block
|
lib.rs
|
// ssdeep-rs: A Rust wrapper for ssdeep.
//
// Copyright (c) 2016 Petr Zemek <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! A Rust wrapper for [ssdeep by Jesse
//! Kornblum](https://ssdeep-project.github.io/ssdeep/), which is a C library
//! for computing [context triggered piecewise
//! hashes](http://dfrws.org/2006/proceedings/12-Kornblum.pdf) (CTPH). Also
//! called fuzzy hashes, CTPH can match inputs that have homologies. Such
//! inputs have sequences of identical bytes in the same order, although bytes
//! in between these sequences may be different in both content and length. In
//! contrast to standard hashing algorithms, CTPH can be used to identify files
//! that are highly similar but not identical.
//!
//! Usage
//! -----
//!
//! To compute the fuzzy hash of a given buffer, use
//! [`hash()`](fn.hash.html):
//!
//! ```
//! extern crate ssdeep;
//!
//! let h = ssdeep::hash(b"Hello there!").unwrap();
//! assert_eq!(h, "3:aNRn:aNRn");
//! ```
//!
//! If you want to obtain the fuzzy hash of a file, you can use
//! [`hash_from_file()`](fn.hash_from_file.html):
//!
//! ```
//! let h = ssdeep::hash_from_file("tests/file.txt").unwrap();
//! ```
//!
//! To compare two fuzzy hashes, use [`compare()`](fn.compare.html), which
//! returns an integer between 0 (no match) and 100:
//!
//! ```
//! let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
//! let h2 = b"3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2Cx";
//! let score = ssdeep::compare(h1, h2).unwrap();
//! assert_eq!(score, 22);
//! ```
//!
//! Each of these functions returns an
//! [`Option`](https://doc.rust-lang.org/std/option/enum.Option.html), where
//! `None` is returned when the underlying C function fails.
extern crate libc;
extern crate libfuzzy_sys as raw;
use libc::c_char;
use libc::uint32_t;
use std::ffi::CString;
use std::path::Path;
/// Computes the match score between two fuzzy hashes.
///
/// Returns a value from 0 to 100 indicating the match score of the two hashes.
/// A match score of zero indicates that the hashes did not match. When an
/// error occurs, it returns `None`.
///
/// # Examples
///
/// When the hashes are identical, it returns 100:
///
/// ```
/// let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// let h2 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// assert_eq!(ssdeep::compare(h1, h2), Some(100));
/// ```
///
/// When the hashes are similar, it returns a positive integer:
///
/// ```
/// let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// let h2 = b"3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2Cx";
/// assert_eq!(ssdeep::compare(h1, h2), Some(22));
/// ```
///
/// When the hashes have no similarity at all, it returns zero:
///
/// ```
/// let h1 = b"3:u+N:u+N";
/// let h2 = b"3:OWIXTn:OWQ";
/// assert_eq!(ssdeep::compare(h1, h2), Some(0));
/// ```
///
/// When either of the hashes is invalid, it returns `None`:
///
/// ```
/// let h1 = b"XYZ";
/// let h2 = b"3:tc:u";
/// assert_eq!(ssdeep::compare(h1, h2), None);
/// ```
///
/// # Panics
///
/// If either of the hashes contain a null byte. Note that
/// [`hash()`](fn.hash.html) never returns a hash with a null byte, so this may
/// happen only if you handcrafted the hashes or obtained them from other
/// sources.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_compare()` function from the underlying C
/// library. The return value `-1` is translated into `None`.
pub fn compare(hash1: &[u8], hash2: &[u8]) -> Option<i8> {
let h1 = bytes_to_cstring(hash1);
let h2 = bytes_to_cstring(hash2);
let score = unsafe {
raw::fuzzy_compare(h1.as_bytes_with_nul().as_ptr() as *const c_char,
h2.as_bytes_with_nul().as_ptr() as *const c_char)
};
if score == -1 {
None
} else {
Some(score as i8)
}
}
/// Computes the fuzzy hash of a buffer.
///
/// Returns the fuzzy hash of the given buffer. When an error occurs, it
|
/// ```
/// let h = ssdeep::hash(b"Hello there!").unwrap();
/// assert_eq!(h, "3:aNRn:aNRn");
/// ```
///
/// # Panics
///
/// If the size of the buffer is strictly greater than `2^32 - 1` bytes. The
/// reason for this is that the corresponding function from the underlying C
/// library accepts the length of the buffer as an unsigned 32b integer.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_hash_buf()` function from the underlying C
/// library. A non-zero return value is translated into `None`.
pub fn hash(buf: &[u8]) -> Option<String> {
assert!(buf.len() <= uint32_t::max_value() as usize);
let mut result = create_buffer_for_result();
let rc = unsafe {
raw::fuzzy_hash_buf(buf.as_ptr(),
buf.len() as uint32_t,
result.as_mut_ptr() as *mut c_char)
};
result_buffer_to_string(result, rc)
}
/// Computes the fuzzy hash of a file.
///
/// Returns the fuzzy hash of the given file. When an error occurs, it returns
/// `None`.
///
/// # Examples
///
/// ```
/// let h = ssdeep::hash_from_file("tests/file.txt").unwrap();
/// assert_eq!(h, "48:9MABzSwnjpDeSrLp8+nagE4f3ZMvcDT0MIhqy6Ic:9XMwnjdeSHS+n5ZfScX0MJ7");
/// ```
///
/// # Panics
///
/// If the path to the file cannot be converted into bytes or it contains a
/// null byte.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_hash_filename()` function from the
/// underlying C library. A non-zero return value is translated into `None`.
pub fn hash_from_file<P: AsRef<Path>>(file_path: P) -> Option<String> {
let mut result = create_buffer_for_result();
let fp = path_as_cstring(file_path);
let rc = unsafe {
raw::fuzzy_hash_filename(fp.as_bytes_with_nul().as_ptr() as *const c_char,
result.as_mut_ptr() as *mut c_char)
};
result_buffer_to_string(result, rc)
}
fn path_as_cstring<P: AsRef<Path>>(path: P) -> CString {
// We can unwrap() the result because if the path cannot be converted into
// a string, we panic, as documented in functions that call this function.
bytes_to_cstring(path.as_ref().to_str().unwrap().as_bytes())
}
fn bytes_to_cstring(s: &[u8]) -> CString {
// We can unwrap() the result because if there is a null byte, we panic, as
// documented in functions that call this function.
CString::new(s).unwrap()
}
fn create_buffer_for_result() -> Vec<u8> {
// From fuzzy.h: "The buffer into which the fuzzy hash is stored has to be
// allocated to hold at least FUZZY_MAX_RESULT bytes."
Vec::with_capacity(raw::FUZZY_MAX_RESULT)
}
fn result_buffer_to_string(mut result: Vec<u8>, rc: i32) -> Option<String> {
if rc!= 0 {
// The function from libfuzzy failed, so there is no result.
return None;
}
// Since the resulting vector that holds the fuzzy hash was populated in
// the underlying C library, we have to adjust its length because at this
// point, the vector thinks that its length is zero. We do this by finding
// the first null byte.
unsafe {
let mut len = 0;
for i in 0..raw::FUZZY_MAX_RESULT {
if *result.get_unchecked(i) == 0 {
break;
}
len += 1;
}
result.set_len(len);
}
// There should be only ASCII characters in the result, but better be safe
// than sorry. If there happens to be anything else, return None.
String::from_utf8(result).ok()
}
|
/// returns `None`.
///
/// # Examples
///
|
random_line_split
|
lib.rs
|
// ssdeep-rs: A Rust wrapper for ssdeep.
//
// Copyright (c) 2016 Petr Zemek <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! A Rust wrapper for [ssdeep by Jesse
//! Kornblum](https://ssdeep-project.github.io/ssdeep/), which is a C library
//! for computing [context triggered piecewise
//! hashes](http://dfrws.org/2006/proceedings/12-Kornblum.pdf) (CTPH). Also
//! called fuzzy hashes, CTPH can match inputs that have homologies. Such
//! inputs have sequences of identical bytes in the same order, although bytes
//! in between these sequences may be different in both content and length. In
//! contrast to standard hashing algorithms, CTPH can be used to identify files
//! that are highly similar but not identical.
//!
//! Usage
//! -----
//!
//! To compute the fuzzy hash of a given buffer, use
//! [`hash()`](fn.hash.html):
//!
//! ```
//! extern crate ssdeep;
//!
//! let h = ssdeep::hash(b"Hello there!").unwrap();
//! assert_eq!(h, "3:aNRn:aNRn");
//! ```
//!
//! If you want to obtain the fuzzy hash of a file, you can use
//! [`hash_from_file()`](fn.hash_from_file.html):
//!
//! ```
//! let h = ssdeep::hash_from_file("tests/file.txt").unwrap();
//! ```
//!
//! To compare two fuzzy hashes, use [`compare()`](fn.compare.html), which
//! returns an integer between 0 (no match) and 100:
//!
//! ```
//! let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
//! let h2 = b"3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2Cx";
//! let score = ssdeep::compare(h1, h2).unwrap();
//! assert_eq!(score, 22);
//! ```
//!
//! Each of these functions returns an
//! [`Option`](https://doc.rust-lang.org/std/option/enum.Option.html), where
//! `None` is returned when the underlying C function fails.
extern crate libc;
extern crate libfuzzy_sys as raw;
use libc::c_char;
use libc::uint32_t;
use std::ffi::CString;
use std::path::Path;
/// Computes the match score between two fuzzy hashes.
///
/// Returns a value from 0 to 100 indicating the match score of the two hashes.
/// A match score of zero indicates that the hashes did not match. When an
/// error occurs, it returns `None`.
///
/// # Examples
///
/// When the hashes are identical, it returns 100:
///
/// ```
/// let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// let h2 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// assert_eq!(ssdeep::compare(h1, h2), Some(100));
/// ```
///
/// When the hashes are similar, it returns a positive integer:
///
/// ```
/// let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// let h2 = b"3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2Cx";
/// assert_eq!(ssdeep::compare(h1, h2), Some(22));
/// ```
///
/// When the hashes have no similarity at all, it returns zero:
///
/// ```
/// let h1 = b"3:u+N:u+N";
/// let h2 = b"3:OWIXTn:OWQ";
/// assert_eq!(ssdeep::compare(h1, h2), Some(0));
/// ```
///
/// When either of the hashes is invalid, it returns `None`:
///
/// ```
/// let h1 = b"XYZ";
/// let h2 = b"3:tc:u";
/// assert_eq!(ssdeep::compare(h1, h2), None);
/// ```
///
/// # Panics
///
/// If either of the hashes contain a null byte. Note that
/// [`hash()`](fn.hash.html) never returns a hash with a null byte, so this may
/// happen only if you handcrafted the hashes or obtained them from other
/// sources.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_compare()` function from the underlying C
/// library. The return value `-1` is translated into `None`.
pub fn compare(hash1: &[u8], hash2: &[u8]) -> Option<i8> {
let h1 = bytes_to_cstring(hash1);
let h2 = bytes_to_cstring(hash2);
let score = unsafe {
raw::fuzzy_compare(h1.as_bytes_with_nul().as_ptr() as *const c_char,
h2.as_bytes_with_nul().as_ptr() as *const c_char)
};
if score == -1 {
None
} else {
Some(score as i8)
}
}
/// Computes the fuzzy hash of a buffer.
///
/// Returns the fuzzy hash of the given buffer. When an error occurs, it
/// returns `None`.
///
/// # Examples
///
/// ```
/// let h = ssdeep::hash(b"Hello there!").unwrap();
/// assert_eq!(h, "3:aNRn:aNRn");
/// ```
///
/// # Panics
///
/// If the size of the buffer is strictly greater than `2^32 - 1` bytes. The
/// reason for this is that the corresponding function from the underlying C
/// library accepts the length of the buffer as an unsigned 32b integer.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_hash_buf()` function from the underlying C
/// library. A non-zero return value is translated into `None`.
pub fn hash(buf: &[u8]) -> Option<String> {
assert!(buf.len() <= uint32_t::max_value() as usize);
let mut result = create_buffer_for_result();
let rc = unsafe {
raw::fuzzy_hash_buf(buf.as_ptr(),
buf.len() as uint32_t,
result.as_mut_ptr() as *mut c_char)
};
result_buffer_to_string(result, rc)
}
/// Computes the fuzzy hash of a file.
///
/// Returns the fuzzy hash of the given file. When an error occurs, it returns
/// `None`.
///
/// # Examples
///
/// ```
/// let h = ssdeep::hash_from_file("tests/file.txt").unwrap();
/// assert_eq!(h, "48:9MABzSwnjpDeSrLp8+nagE4f3ZMvcDT0MIhqy6Ic:9XMwnjdeSHS+n5ZfScX0MJ7");
/// ```
///
/// # Panics
///
/// If the path to the file cannot be converted into bytes or it contains a
/// null byte.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_hash_filename()` function from the
/// underlying C library. A non-zero return value is translated into `None`.
pub fn hash_from_file<P: AsRef<Path>>(file_path: P) -> Option<String> {
let mut result = create_buffer_for_result();
let fp = path_as_cstring(file_path);
let rc = unsafe {
raw::fuzzy_hash_filename(fp.as_bytes_with_nul().as_ptr() as *const c_char,
result.as_mut_ptr() as *mut c_char)
};
result_buffer_to_string(result, rc)
}
fn path_as_cstring<P: AsRef<Path>>(path: P) -> CString {
// We can unwrap() the result because if the path cannot be converted into
// a string, we panic, as documented in functions that call this function.
bytes_to_cstring(path.as_ref().to_str().unwrap().as_bytes())
}
fn bytes_to_cstring(s: &[u8]) -> CString {
// We can unwrap() the result because if there is a null byte, we panic, as
// documented in functions that call this function.
CString::new(s).unwrap()
}
fn create_buffer_for_result() -> Vec<u8>
|
fn result_buffer_to_string(mut result: Vec<u8>, rc: i32) -> Option<String> {
if rc!= 0 {
// The function from libfuzzy failed, so there is no result.
return None;
}
// Since the resulting vector that holds the fuzzy hash was populated in
// the underlying C library, we have to adjust its length because at this
// point, the vector thinks that its length is zero. We do this by finding
// the first null byte.
unsafe {
let mut len = 0;
for i in 0..raw::FUZZY_MAX_RESULT {
if *result.get_unchecked(i) == 0 {
break;
}
len += 1;
}
result.set_len(len);
}
// There should be only ASCII characters in the result, but better be safe
// than sorry. If there happens to be anything else, return None.
String::from_utf8(result).ok()
}
|
{
// From fuzzy.h: "The buffer into which the fuzzy hash is stored has to be
// allocated to hold at least FUZZY_MAX_RESULT bytes."
Vec::with_capacity(raw::FUZZY_MAX_RESULT)
}
|
identifier_body
|
lib.rs
|
// ssdeep-rs: A Rust wrapper for ssdeep.
//
// Copyright (c) 2016 Petr Zemek <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! A Rust wrapper for [ssdeep by Jesse
//! Kornblum](https://ssdeep-project.github.io/ssdeep/), which is a C library
//! for computing [context triggered piecewise
//! hashes](http://dfrws.org/2006/proceedings/12-Kornblum.pdf) (CTPH). Also
//! called fuzzy hashes, CTPH can match inputs that have homologies. Such
//! inputs have sequences of identical bytes in the same order, although bytes
//! in between these sequences may be different in both content and length. In
//! contrast to standard hashing algorithms, CTPH can be used to identify files
//! that are highly similar but not identical.
//!
//! Usage
//! -----
//!
//! To compute the fuzzy hash of a given buffer, use
//! [`hash()`](fn.hash.html):
//!
//! ```
//! extern crate ssdeep;
//!
//! let h = ssdeep::hash(b"Hello there!").unwrap();
//! assert_eq!(h, "3:aNRn:aNRn");
//! ```
//!
//! If you want to obtain the fuzzy hash of a file, you can use
//! [`hash_from_file()`](fn.hash_from_file.html):
//!
//! ```
//! let h = ssdeep::hash_from_file("tests/file.txt").unwrap();
//! ```
//!
//! To compare two fuzzy hashes, use [`compare()`](fn.compare.html), which
//! returns an integer between 0 (no match) and 100:
//!
//! ```
//! let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
//! let h2 = b"3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2Cx";
//! let score = ssdeep::compare(h1, h2).unwrap();
//! assert_eq!(score, 22);
//! ```
//!
//! Each of these functions returns an
//! [`Option`](https://doc.rust-lang.org/std/option/enum.Option.html), where
//! `None` is returned when the underlying C function fails.
extern crate libc;
extern crate libfuzzy_sys as raw;
use libc::c_char;
use libc::uint32_t;
use std::ffi::CString;
use std::path::Path;
/// Computes the match score between two fuzzy hashes.
///
/// Returns a value from 0 to 100 indicating the match score of the two hashes.
/// A match score of zero indicates that the hashes did not match. When an
/// error occurs, it returns `None`.
///
/// # Examples
///
/// When the hashes are identical, it returns 100:
///
/// ```
/// let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// let h2 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// assert_eq!(ssdeep::compare(h1, h2), Some(100));
/// ```
///
/// When the hashes are similar, it returns a positive integer:
///
/// ```
/// let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// let h2 = b"3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2Cx";
/// assert_eq!(ssdeep::compare(h1, h2), Some(22));
/// ```
///
/// When the hashes have no similarity at all, it returns zero:
///
/// ```
/// let h1 = b"3:u+N:u+N";
/// let h2 = b"3:OWIXTn:OWQ";
/// assert_eq!(ssdeep::compare(h1, h2), Some(0));
/// ```
///
/// When either of the hashes is invalid, it returns `None`:
///
/// ```
/// let h1 = b"XYZ";
/// let h2 = b"3:tc:u";
/// assert_eq!(ssdeep::compare(h1, h2), None);
/// ```
///
/// # Panics
///
/// If either of the hashes contain a null byte. Note that
/// [`hash()`](fn.hash.html) never returns a hash with a null byte, so this may
/// happen only if you handcrafted the hashes or obtained them from other
/// sources.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_compare()` function from the underlying C
/// library. The return value `-1` is translated into `None`.
pub fn compare(hash1: &[u8], hash2: &[u8]) -> Option<i8> {
let h1 = bytes_to_cstring(hash1);
let h2 = bytes_to_cstring(hash2);
let score = unsafe {
raw::fuzzy_compare(h1.as_bytes_with_nul().as_ptr() as *const c_char,
h2.as_bytes_with_nul().as_ptr() as *const c_char)
};
if score == -1 {
None
} else {
Some(score as i8)
}
}
/// Computes the fuzzy hash of a buffer.
///
/// Returns the fuzzy hash of the given buffer. When an error occurs, it
/// returns `None`.
///
/// # Examples
///
/// ```
/// let h = ssdeep::hash(b"Hello there!").unwrap();
/// assert_eq!(h, "3:aNRn:aNRn");
/// ```
///
/// # Panics
///
/// If the size of the buffer is strictly greater than `2^32 - 1` bytes. The
/// reason for this is that the corresponding function from the underlying C
/// library accepts the length of the buffer as an unsigned 32b integer.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_hash_buf()` function from the underlying C
/// library. A non-zero return value is translated into `None`.
pub fn hash(buf: &[u8]) -> Option<String> {
assert!(buf.len() <= uint32_t::max_value() as usize);
let mut result = create_buffer_for_result();
let rc = unsafe {
raw::fuzzy_hash_buf(buf.as_ptr(),
buf.len() as uint32_t,
result.as_mut_ptr() as *mut c_char)
};
result_buffer_to_string(result, rc)
}
/// Computes the fuzzy hash of a file.
///
/// Returns the fuzzy hash of the given file. When an error occurs, it returns
/// `None`.
///
/// # Examples
///
/// ```
/// let h = ssdeep::hash_from_file("tests/file.txt").unwrap();
/// assert_eq!(h, "48:9MABzSwnjpDeSrLp8+nagE4f3ZMvcDT0MIhqy6Ic:9XMwnjdeSHS+n5ZfScX0MJ7");
/// ```
///
/// # Panics
///
/// If the path to the file cannot be converted into bytes or it contains a
/// null byte.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_hash_filename()` function from the
/// underlying C library. A non-zero return value is translated into `None`.
pub fn hash_from_file<P: AsRef<Path>>(file_path: P) -> Option<String> {
let mut result = create_buffer_for_result();
let fp = path_as_cstring(file_path);
let rc = unsafe {
raw::fuzzy_hash_filename(fp.as_bytes_with_nul().as_ptr() as *const c_char,
result.as_mut_ptr() as *mut c_char)
};
result_buffer_to_string(result, rc)
}
fn path_as_cstring<P: AsRef<Path>>(path: P) -> CString {
// We can unwrap() the result because if the path cannot be converted into
// a string, we panic, as documented in functions that call this function.
bytes_to_cstring(path.as_ref().to_str().unwrap().as_bytes())
}
fn bytes_to_cstring(s: &[u8]) -> CString {
// We can unwrap() the result because if there is a null byte, we panic, as
// documented in functions that call this function.
CString::new(s).unwrap()
}
fn create_buffer_for_result() -> Vec<u8> {
// From fuzzy.h: "The buffer into which the fuzzy hash is stored has to be
// allocated to hold at least FUZZY_MAX_RESULT bytes."
Vec::with_capacity(raw::FUZZY_MAX_RESULT)
}
fn result_buffer_to_string(mut result: Vec<u8>, rc: i32) -> Option<String> {
if rc!= 0
|
// Since the resulting vector that holds the fuzzy hash was populated in
// the underlying C library, we have to adjust its length because at this
// point, the vector thinks that its length is zero. We do this by finding
// the first null byte.
unsafe {
let mut len = 0;
for i in 0..raw::FUZZY_MAX_RESULT {
if *result.get_unchecked(i) == 0 {
break;
}
len += 1;
}
result.set_len(len);
}
// There should be only ASCII characters in the result, but better be safe
// than sorry. If there happens to be anything else, return None.
String::from_utf8(result).ok()
}
|
{
// The function from libfuzzy failed, so there is no result.
return None;
}
|
conditional_block
|
lib.rs
|
// ssdeep-rs: A Rust wrapper for ssdeep.
//
// Copyright (c) 2016 Petr Zemek <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! A Rust wrapper for [ssdeep by Jesse
//! Kornblum](https://ssdeep-project.github.io/ssdeep/), which is a C library
//! for computing [context triggered piecewise
//! hashes](http://dfrws.org/2006/proceedings/12-Kornblum.pdf) (CTPH). Also
//! called fuzzy hashes, CTPH can match inputs that have homologies. Such
//! inputs have sequences of identical bytes in the same order, although bytes
//! in between these sequences may be different in both content and length. In
//! contrast to standard hashing algorithms, CTPH can be used to identify files
//! that are highly similar but not identical.
//!
//! Usage
//! -----
//!
//! To compute the fuzzy hash of a given buffer, use
//! [`hash()`](fn.hash.html):
//!
//! ```
//! extern crate ssdeep;
//!
//! let h = ssdeep::hash(b"Hello there!").unwrap();
//! assert_eq!(h, "3:aNRn:aNRn");
//! ```
//!
//! If you want to obtain the fuzzy hash of a file, you can use
//! [`hash_from_file()`](fn.hash_from_file.html):
//!
//! ```
//! let h = ssdeep::hash_from_file("tests/file.txt").unwrap();
//! ```
//!
//! To compare two fuzzy hashes, use [`compare()`](fn.compare.html), which
//! returns an integer between 0 (no match) and 100:
//!
//! ```
//! let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
//! let h2 = b"3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2Cx";
//! let score = ssdeep::compare(h1, h2).unwrap();
//! assert_eq!(score, 22);
//! ```
//!
//! Each of these functions returns an
//! [`Option`](https://doc.rust-lang.org/std/option/enum.Option.html), where
//! `None` is returned when the underlying C function fails.
extern crate libc;
extern crate libfuzzy_sys as raw;
use libc::c_char;
use libc::uint32_t;
use std::ffi::CString;
use std::path::Path;
/// Computes the match score between two fuzzy hashes.
///
/// Returns a value from 0 to 100 indicating the match score of the two hashes.
/// A match score of zero indicates that the hashes did not match. When an
/// error occurs, it returns `None`.
///
/// # Examples
///
/// When the hashes are identical, it returns 100:
///
/// ```
/// let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// let h2 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// assert_eq!(ssdeep::compare(h1, h2), Some(100));
/// ```
///
/// When the hashes are similar, it returns a positive integer:
///
/// ```
/// let h1 = b"3:AXGBicFlgVNhBGcL6wCrFQEv:AXGHsNhxLsr2C";
/// let h2 = b"3:AXGBicFlIHBGcL6wCrFQEv:AXGH6xLsr2Cx";
/// assert_eq!(ssdeep::compare(h1, h2), Some(22));
/// ```
///
/// When the hashes have no similarity at all, it returns zero:
///
/// ```
/// let h1 = b"3:u+N:u+N";
/// let h2 = b"3:OWIXTn:OWQ";
/// assert_eq!(ssdeep::compare(h1, h2), Some(0));
/// ```
///
/// When either of the hashes is invalid, it returns `None`:
///
/// ```
/// let h1 = b"XYZ";
/// let h2 = b"3:tc:u";
/// assert_eq!(ssdeep::compare(h1, h2), None);
/// ```
///
/// # Panics
///
/// If either of the hashes contain a null byte. Note that
/// [`hash()`](fn.hash.html) never returns a hash with a null byte, so this may
/// happen only if you handcrafted the hashes or obtained them from other
/// sources.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_compare()` function from the underlying C
/// library. The return value `-1` is translated into `None`.
pub fn compare(hash1: &[u8], hash2: &[u8]) -> Option<i8> {
let h1 = bytes_to_cstring(hash1);
let h2 = bytes_to_cstring(hash2);
let score = unsafe {
raw::fuzzy_compare(h1.as_bytes_with_nul().as_ptr() as *const c_char,
h2.as_bytes_with_nul().as_ptr() as *const c_char)
};
if score == -1 {
None
} else {
Some(score as i8)
}
}
/// Computes the fuzzy hash of a buffer.
///
/// Returns the fuzzy hash of the given buffer. When an error occurs, it
/// returns `None`.
///
/// # Examples
///
/// ```
/// let h = ssdeep::hash(b"Hello there!").unwrap();
/// assert_eq!(h, "3:aNRn:aNRn");
/// ```
///
/// # Panics
///
/// If the size of the buffer is strictly greater than `2^32 - 1` bytes. The
/// reason for this is that the corresponding function from the underlying C
/// library accepts the length of the buffer as an unsigned 32b integer.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_hash_buf()` function from the underlying C
/// library. A non-zero return value is translated into `None`.
pub fn
|
(buf: &[u8]) -> Option<String> {
assert!(buf.len() <= uint32_t::max_value() as usize);
let mut result = create_buffer_for_result();
let rc = unsafe {
raw::fuzzy_hash_buf(buf.as_ptr(),
buf.len() as uint32_t,
result.as_mut_ptr() as *mut c_char)
};
result_buffer_to_string(result, rc)
}
/// Computes the fuzzy hash of a file.
///
/// Returns the fuzzy hash of the given file. When an error occurs, it returns
/// `None`.
///
/// # Examples
///
/// ```
/// let h = ssdeep::hash_from_file("tests/file.txt").unwrap();
/// assert_eq!(h, "48:9MABzSwnjpDeSrLp8+nagE4f3ZMvcDT0MIhqy6Ic:9XMwnjdeSHS+n5ZfScX0MJ7");
/// ```
///
/// # Panics
///
/// If the path to the file cannot be converted into bytes or it contains a
/// null byte.
///
/// # Implementation details
///
/// Internally, it calls the `fuzzy_hash_filename()` function from the
/// underlying C library. A non-zero return value is translated into `None`.
pub fn hash_from_file<P: AsRef<Path>>(file_path: P) -> Option<String> {
let mut result = create_buffer_for_result();
let fp = path_as_cstring(file_path);
let rc = unsafe {
raw::fuzzy_hash_filename(fp.as_bytes_with_nul().as_ptr() as *const c_char,
result.as_mut_ptr() as *mut c_char)
};
result_buffer_to_string(result, rc)
}
fn path_as_cstring<P: AsRef<Path>>(path: P) -> CString {
// We can unwrap() the result because if the path cannot be converted into
// a string, we panic, as documented in functions that call this function.
bytes_to_cstring(path.as_ref().to_str().unwrap().as_bytes())
}
fn bytes_to_cstring(s: &[u8]) -> CString {
// We can unwrap() the result because if there is a null byte, we panic, as
// documented in functions that call this function.
CString::new(s).unwrap()
}
fn create_buffer_for_result() -> Vec<u8> {
// From fuzzy.h: "The buffer into which the fuzzy hash is stored has to be
// allocated to hold at least FUZZY_MAX_RESULT bytes."
Vec::with_capacity(raw::FUZZY_MAX_RESULT)
}
fn result_buffer_to_string(mut result: Vec<u8>, rc: i32) -> Option<String> {
if rc!= 0 {
// The function from libfuzzy failed, so there is no result.
return None;
}
// Since the resulting vector that holds the fuzzy hash was populated in
// the underlying C library, we have to adjust its length because at this
// point, the vector thinks that its length is zero. We do this by finding
// the first null byte.
unsafe {
let mut len = 0;
for i in 0..raw::FUZZY_MAX_RESULT {
if *result.get_unchecked(i) == 0 {
break;
}
len += 1;
}
result.set_len(len);
}
// There should be only ASCII characters in the result, but better be safe
// than sorry. If there happens to be anything else, return None.
String::from_utf8(result).ok()
}
|
hash
|
identifier_name
|
mod.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Ethereum protocol module.
//!
//! Contains all Ethereum network specific stuff, such as denominations and
//! consensus specifications.
/// Export the ethash module.
pub mod ethash;
/// Export the denominations module.
pub mod denominations;
pub use self::ethash::{Ethash};
pub use self::denominations::*;
use super::spec::*;
fn load(b: &[u8]) -> Spec {
Spec::load(b).expect("chain spec is invalid")
}
/// Create a new Olympic chain spec.
pub fn new_olympic() -> Spec { load(include_bytes!("../../res/ethereum/olympic.json")) }
/// Create a new Frontier mainnet chain spec.
pub fn new_frontier() -> Spec { load(include_bytes!("../../res/ethereum/frontier.json")) }
/// Create a new Frontier mainnet chain spec without the DAO hardfork.
|
pub fn new_expanse() -> Spec { load(include_bytes!("../../res/ethereum/expanse.json")) }
/// Create a new Frontier chain spec as though it never changes to Homestead.
pub fn new_frontier_test() -> Spec { load(include_bytes!("../../res/ethereum/frontier_test.json")) }
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec { load(include_bytes!("../../res/ethereum/homestead_test.json")) }
/// Create a new Homestead-EIP150 chain spec as though it never changed from Homestead/Frontier.
pub fn new_eip150_test() -> Spec { load(include_bytes!("../../res/ethereum/eip150_test.json")) }
/// Create a new Frontier/Homestead/DAO chain spec with transition points at #5 and #8.
pub fn new_transition_test() -> Spec { load(include_bytes!("../../res/ethereum/transition_test.json")) }
/// Create a new Frontier main net chain spec without genesis accounts.
pub fn new_mainnet_like() -> Spec { load(include_bytes!("../../res/ethereum/frontier_like_test.json")) }
/// Create a new Morden chain spec.
pub fn new_morden() -> Spec { load(include_bytes!("../../res/ethereum/morden.json")) }
#[cfg(test)]
mod tests {
use util::*;
use state::*;
use super::*;
use tests::helpers::*;
use views::BlockView;
#[test]
fn ensure_db_good() {
let spec = new_morden();
let engine = &spec.engine;
let genesis_header = spec.genesis_header();
let mut db_result = get_temp_state_db();
let mut db = db_result.take();
spec.ensure_db_good(&mut db).unwrap();
let s = State::from_existing(db, genesis_header.state_root().clone(), engine.account_start_nonce(), Default::default()).unwrap();
assert_eq!(s.balance(&"0000000000000000000000000000000000000001".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000002".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000003".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000004".into()), 1u64.into());
assert_eq!(s.balance(&"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c".into()), U256::from(1u64) << 200);
assert_eq!(s.balance(&"0000000000000000000000000000000000000000".into()), 0u64.into());
}
#[test]
fn morden() {
let morden = new_morden();
assert_eq!(morden.state_root(), "f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9".into());
let genesis = morden.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into());
let _ = morden.engine;
}
#[test]
fn frontier() {
let frontier = new_frontier();
assert_eq!(frontier.state_root(), "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544".into());
let genesis = frontier.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3".into());
let _ = frontier.engine;
}
}
|
pub fn new_classic() -> Spec { load(include_bytes!("../../res/ethereum/classic.json")) }
/// Create a new Frontier mainnet chain spec without the DAO hardfork.
|
random_line_split
|
mod.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Ethereum protocol module.
//!
//! Contains all Ethereum network specific stuff, such as denominations and
//! consensus specifications.
/// Export the ethash module.
pub mod ethash;
/// Export the denominations module.
pub mod denominations;
pub use self::ethash::{Ethash};
pub use self::denominations::*;
use super::spec::*;
fn load(b: &[u8]) -> Spec {
Spec::load(b).expect("chain spec is invalid")
}
/// Create a new Olympic chain spec.
pub fn new_olympic() -> Spec { load(include_bytes!("../../res/ethereum/olympic.json")) }
/// Create a new Frontier mainnet chain spec.
pub fn new_frontier() -> Spec { load(include_bytes!("../../res/ethereum/frontier.json")) }
/// Create a new Frontier mainnet chain spec without the DAO hardfork.
pub fn new_classic() -> Spec { load(include_bytes!("../../res/ethereum/classic.json")) }
/// Create a new Frontier mainnet chain spec without the DAO hardfork.
pub fn new_expanse() -> Spec { load(include_bytes!("../../res/ethereum/expanse.json")) }
/// Create a new Frontier chain spec as though it never changes to Homestead.
pub fn
|
() -> Spec { load(include_bytes!("../../res/ethereum/frontier_test.json")) }
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec { load(include_bytes!("../../res/ethereum/homestead_test.json")) }
/// Create a new Homestead-EIP150 chain spec as though it never changed from Homestead/Frontier.
pub fn new_eip150_test() -> Spec { load(include_bytes!("../../res/ethereum/eip150_test.json")) }
/// Create a new Frontier/Homestead/DAO chain spec with transition points at #5 and #8.
pub fn new_transition_test() -> Spec { load(include_bytes!("../../res/ethereum/transition_test.json")) }
/// Create a new Frontier main net chain spec without genesis accounts.
pub fn new_mainnet_like() -> Spec { load(include_bytes!("../../res/ethereum/frontier_like_test.json")) }
/// Create a new Morden chain spec.
pub fn new_morden() -> Spec { load(include_bytes!("../../res/ethereum/morden.json")) }
#[cfg(test)]
mod tests {
use util::*;
use state::*;
use super::*;
use tests::helpers::*;
use views::BlockView;
#[test]
fn ensure_db_good() {
let spec = new_morden();
let engine = &spec.engine;
let genesis_header = spec.genesis_header();
let mut db_result = get_temp_state_db();
let mut db = db_result.take();
spec.ensure_db_good(&mut db).unwrap();
let s = State::from_existing(db, genesis_header.state_root().clone(), engine.account_start_nonce(), Default::default()).unwrap();
assert_eq!(s.balance(&"0000000000000000000000000000000000000001".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000002".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000003".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000004".into()), 1u64.into());
assert_eq!(s.balance(&"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c".into()), U256::from(1u64) << 200);
assert_eq!(s.balance(&"0000000000000000000000000000000000000000".into()), 0u64.into());
}
#[test]
fn morden() {
let morden = new_morden();
assert_eq!(morden.state_root(), "f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9".into());
let genesis = morden.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into());
let _ = morden.engine;
}
#[test]
fn frontier() {
let frontier = new_frontier();
assert_eq!(frontier.state_root(), "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544".into());
let genesis = frontier.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3".into());
let _ = frontier.engine;
}
}
|
new_frontier_test
|
identifier_name
|
mod.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Ethereum protocol module.
//!
//! Contains all Ethereum network specific stuff, such as denominations and
//! consensus specifications.
/// Export the ethash module.
pub mod ethash;
/// Export the denominations module.
pub mod denominations;
pub use self::ethash::{Ethash};
pub use self::denominations::*;
use super::spec::*;
fn load(b: &[u8]) -> Spec {
Spec::load(b).expect("chain spec is invalid")
}
/// Create a new Olympic chain spec.
pub fn new_olympic() -> Spec { load(include_bytes!("../../res/ethereum/olympic.json")) }
/// Create a new Frontier mainnet chain spec.
pub fn new_frontier() -> Spec { load(include_bytes!("../../res/ethereum/frontier.json")) }
/// Create a new Frontier mainnet chain spec without the DAO hardfork.
pub fn new_classic() -> Spec { load(include_bytes!("../../res/ethereum/classic.json")) }
/// Create a new Frontier mainnet chain spec without the DAO hardfork.
pub fn new_expanse() -> Spec { load(include_bytes!("../../res/ethereum/expanse.json")) }
/// Create a new Frontier chain spec as though it never changes to Homestead.
pub fn new_frontier_test() -> Spec
|
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec { load(include_bytes!("../../res/ethereum/homestead_test.json")) }
/// Create a new Homestead-EIP150 chain spec as though it never changed from Homestead/Frontier.
pub fn new_eip150_test() -> Spec { load(include_bytes!("../../res/ethereum/eip150_test.json")) }
/// Create a new Frontier/Homestead/DAO chain spec with transition points at #5 and #8.
pub fn new_transition_test() -> Spec { load(include_bytes!("../../res/ethereum/transition_test.json")) }
/// Create a new Frontier main net chain spec without genesis accounts.
pub fn new_mainnet_like() -> Spec { load(include_bytes!("../../res/ethereum/frontier_like_test.json")) }
/// Create a new Morden chain spec.
pub fn new_morden() -> Spec { load(include_bytes!("../../res/ethereum/morden.json")) }
#[cfg(test)]
mod tests {
use util::*;
use state::*;
use super::*;
use tests::helpers::*;
use views::BlockView;
#[test]
fn ensure_db_good() {
let spec = new_morden();
let engine = &spec.engine;
let genesis_header = spec.genesis_header();
let mut db_result = get_temp_state_db();
let mut db = db_result.take();
spec.ensure_db_good(&mut db).unwrap();
let s = State::from_existing(db, genesis_header.state_root().clone(), engine.account_start_nonce(), Default::default()).unwrap();
assert_eq!(s.balance(&"0000000000000000000000000000000000000001".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000002".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000003".into()), 1u64.into());
assert_eq!(s.balance(&"0000000000000000000000000000000000000004".into()), 1u64.into());
assert_eq!(s.balance(&"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c".into()), U256::from(1u64) << 200);
assert_eq!(s.balance(&"0000000000000000000000000000000000000000".into()), 0u64.into());
}
#[test]
fn morden() {
let morden = new_morden();
assert_eq!(morden.state_root(), "f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9".into());
let genesis = morden.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into());
let _ = morden.engine;
}
#[test]
fn frontier() {
let frontier = new_frontier();
assert_eq!(frontier.state_root(), "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544".into());
let genesis = frontier.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3".into());
let _ = frontier.engine;
}
}
|
{ load(include_bytes!("../../res/ethereum/frontier_test.json")) }
|
identifier_body
|
display.rs
|
use mon_gen::monster::{Monster, MonsterAttack};
use mon_gen::battle::{Party, Battle, BattleError, PartyMember};
pub fn display(text: String, left: bool)
{
if left
{
println!("{:>80}", text);
}
else
{
println!("{}", text);
}
}
pub fn display_member(member: Option<PartyMember>, opponent: bool, active: bool)
{
if let Some(monster) = member
{
display_stats(monster.member, opponent, active, None);
}
else
{
display("---".to_string(), true);
display("---".to_string(), true);
println!("");
}
}
pub fn display_active(battle: &Battle, active: usize)
{
println!("");
for index in 0..battle.state().parties()[1].active_count()
{
display_member(battle.state().parties()[1].active_member_alive(index), true, false)
}
for index in 0..battle.state().parties()[0].active_count()
{
let active = active == index;
display_member(battle.state().parties()[0].active_member_alive(index), false, active)
}
println!("");
}
pub fn display_stats(monster: &Monster, opponent: bool, active: bool, index: Option<usize>)
{
let active_arrow = if active
|
else
{
""
};
let active_index = if let Some(num) = index
{
format!("{}", num)
}
else
{
String::new()
};
let form_name = if monster.species().species().forms.len() > 1
{
format!(" ({})", monster.species().species().form(monster.form() as usize))
}
else
{
String::new()
};
display(format!("{}{}{}{} Lv. {}", active_index, active_arrow, monster.nick(), form_name,
monster.level()), opponent);
display(format!("{}HP: {}/{}", active_arrow, monster.health(), monster.stat_health()),
opponent);
println!("");
}
pub fn display_attacks(attacks: &[MonsterAttack])
{
let mut alternate = true;
for (index, attack) in attacks.iter().enumerate()
{
alternate =!alternate;
display(format!("{}) {}", index + 1, attack.attack().name()), alternate);
display(format!(" {}", attack.attack().element.name()), alternate);
display(format!(" Limit: {}/{}", attack.limit_left(), attack.limit_max()), alternate);
}
println!("");
println!("{:>80}", format!("{}) {}", attacks.len() + 1, "Back"));
}
pub fn display_party(party: &Party, back: bool)
{
println!("Party members:");
println!("");
let mut alternate = true;
for (index, monster) in party.iter().enumerate()
{
alternate =!alternate;
display(format!("{}) {} Lv. {}", index + 1, monster.nick(), monster.level()),
alternate);
display(format!(" HP: {}/{}", monster.health(), monster.stat_health()),
alternate);
display(format!(" ATK: {}, DEF: {}", monster.stat_attack(),
monster.stat_defense()), alternate);
display(format!(" SPATK: {}, SPDEF: {}", monster.stat_spattack(),
monster.stat_spdefense()), alternate);
display(format!(" SPD: {}", monster.stat_speed()), alternate);
}
println!("");
if back
{
println!("{:>80}", format!("{}) {}", party.member_count() + 1, "Back"));
}
}
/// Returns a descriptive string of the given battle error.
pub fn display_error(err: BattleError)
{
let error_str = match err
{
BattleError::None =>
{
unreachable!();
}
BattleError::Rejected =>
{
unreachable!();
}
BattleError::AttackLimit =>
{
"Selected move has no PP left."
}
BattleError::AttackTarget =>
{
"Invalid target."
}
BattleError::SwitchActive =>
{
"Selected party member is already active."
}
BattleError::SwitchHealth =>
{
"Selected party member has no health."
}
BattleError::SwitchQueued =>
{
"Selected party member is already queued to switch in."
}
};
println!("Invalid selection: {}", error_str);
}
|
{
"-> "
}
|
conditional_block
|
display.rs
|
use mon_gen::monster::{Monster, MonsterAttack};
use mon_gen::battle::{Party, Battle, BattleError, PartyMember};
pub fn display(text: String, left: bool)
{
if left
{
println!("{:>80}", text);
}
else
{
println!("{}", text);
}
}
pub fn display_member(member: Option<PartyMember>, opponent: bool, active: bool)
{
if let Some(monster) = member
{
display_stats(monster.member, opponent, active, None);
}
else
{
display("---".to_string(), true);
display("---".to_string(), true);
println!("");
}
}
pub fn display_active(battle: &Battle, active: usize)
{
println!("");
for index in 0..battle.state().parties()[1].active_count()
{
display_member(battle.state().parties()[1].active_member_alive(index), true, false)
}
for index in 0..battle.state().parties()[0].active_count()
{
let active = active == index;
display_member(battle.state().parties()[0].active_member_alive(index), false, active)
}
println!("");
}
pub fn display_stats(monster: &Monster, opponent: bool, active: bool, index: Option<usize>)
{
let active_arrow = if active
{
"-> "
}
else
{
""
};
let active_index = if let Some(num) = index
{
format!("{}", num)
}
else
{
String::new()
};
let form_name = if monster.species().species().forms.len() > 1
{
format!(" ({})", monster.species().species().form(monster.form() as usize))
}
else
{
String::new()
};
display(format!("{}{}{}{} Lv. {}", active_index, active_arrow, monster.nick(), form_name,
monster.level()), opponent);
display(format!("{}HP: {}/{}", active_arrow, monster.health(), monster.stat_health()),
opponent);
println!("");
}
pub fn display_attacks(attacks: &[MonsterAttack])
{
let mut alternate = true;
for (index, attack) in attacks.iter().enumerate()
{
alternate =!alternate;
display(format!("{}) {}", index + 1, attack.attack().name()), alternate);
display(format!(" {}", attack.attack().element.name()), alternate);
display(format!(" Limit: {}/{}", attack.limit_left(), attack.limit_max()), alternate);
}
println!("");
println!("{:>80}", format!("{}) {}", attacks.len() + 1, "Back"));
}
pub fn display_party(party: &Party, back: bool)
{
println!("Party members:");
println!("");
let mut alternate = true;
for (index, monster) in party.iter().enumerate()
{
alternate =!alternate;
display(format!("{}) {} Lv. {}", index + 1, monster.nick(), monster.level()),
alternate);
display(format!(" HP: {}/{}", monster.health(), monster.stat_health()),
alternate);
display(format!(" ATK: {}, DEF: {}", monster.stat_attack(),
monster.stat_defense()), alternate);
display(format!(" SPATK: {}, SPDEF: {}", monster.stat_spattack(),
monster.stat_spdefense()), alternate);
display(format!(" SPD: {}", monster.stat_speed()), alternate);
}
println!("");
if back
{
println!("{:>80}", format!("{}) {}", party.member_count() + 1, "Back"));
}
}
/// Returns a descriptive string of the given battle error.
pub fn display_error(err: BattleError)
{
let error_str = match err
{
BattleError::None =>
{
unreachable!();
}
BattleError::Rejected =>
{
unreachable!();
}
BattleError::AttackLimit =>
{
"Selected move has no PP left."
}
BattleError::AttackTarget =>
{
"Invalid target."
}
BattleError::SwitchActive =>
{
"Selected party member is already active."
}
BattleError::SwitchHealth =>
{
"Selected party member has no health."
|
};
println!("Invalid selection: {}", error_str);
}
|
}
BattleError::SwitchQueued =>
{
"Selected party member is already queued to switch in."
}
|
random_line_split
|
display.rs
|
use mon_gen::monster::{Monster, MonsterAttack};
use mon_gen::battle::{Party, Battle, BattleError, PartyMember};
pub fn display(text: String, left: bool)
{
if left
{
println!("{:>80}", text);
}
else
{
println!("{}", text);
}
}
pub fn display_member(member: Option<PartyMember>, opponent: bool, active: bool)
{
if let Some(monster) = member
{
display_stats(monster.member, opponent, active, None);
}
else
{
display("---".to_string(), true);
display("---".to_string(), true);
println!("");
}
}
pub fn
|
(battle: &Battle, active: usize)
{
println!("");
for index in 0..battle.state().parties()[1].active_count()
{
display_member(battle.state().parties()[1].active_member_alive(index), true, false)
}
for index in 0..battle.state().parties()[0].active_count()
{
let active = active == index;
display_member(battle.state().parties()[0].active_member_alive(index), false, active)
}
println!("");
}
pub fn display_stats(monster: &Monster, opponent: bool, active: bool, index: Option<usize>)
{
let active_arrow = if active
{
"-> "
}
else
{
""
};
let active_index = if let Some(num) = index
{
format!("{}", num)
}
else
{
String::new()
};
let form_name = if monster.species().species().forms.len() > 1
{
format!(" ({})", monster.species().species().form(monster.form() as usize))
}
else
{
String::new()
};
display(format!("{}{}{}{} Lv. {}", active_index, active_arrow, monster.nick(), form_name,
monster.level()), opponent);
display(format!("{}HP: {}/{}", active_arrow, monster.health(), monster.stat_health()),
opponent);
println!("");
}
pub fn display_attacks(attacks: &[MonsterAttack])
{
let mut alternate = true;
for (index, attack) in attacks.iter().enumerate()
{
alternate =!alternate;
display(format!("{}) {}", index + 1, attack.attack().name()), alternate);
display(format!(" {}", attack.attack().element.name()), alternate);
display(format!(" Limit: {}/{}", attack.limit_left(), attack.limit_max()), alternate);
}
println!("");
println!("{:>80}", format!("{}) {}", attacks.len() + 1, "Back"));
}
pub fn display_party(party: &Party, back: bool)
{
println!("Party members:");
println!("");
let mut alternate = true;
for (index, monster) in party.iter().enumerate()
{
alternate =!alternate;
display(format!("{}) {} Lv. {}", index + 1, monster.nick(), monster.level()),
alternate);
display(format!(" HP: {}/{}", monster.health(), monster.stat_health()),
alternate);
display(format!(" ATK: {}, DEF: {}", monster.stat_attack(),
monster.stat_defense()), alternate);
display(format!(" SPATK: {}, SPDEF: {}", monster.stat_spattack(),
monster.stat_spdefense()), alternate);
display(format!(" SPD: {}", monster.stat_speed()), alternate);
}
println!("");
if back
{
println!("{:>80}", format!("{}) {}", party.member_count() + 1, "Back"));
}
}
/// Returns a descriptive string of the given battle error.
pub fn display_error(err: BattleError)
{
let error_str = match err
{
BattleError::None =>
{
unreachable!();
}
BattleError::Rejected =>
{
unreachable!();
}
BattleError::AttackLimit =>
{
"Selected move has no PP left."
}
BattleError::AttackTarget =>
{
"Invalid target."
}
BattleError::SwitchActive =>
{
"Selected party member is already active."
}
BattleError::SwitchHealth =>
{
"Selected party member has no health."
}
BattleError::SwitchQueued =>
{
"Selected party member is already queued to switch in."
}
};
println!("Invalid selection: {}", error_str);
}
|
display_active
|
identifier_name
|
display.rs
|
use mon_gen::monster::{Monster, MonsterAttack};
use mon_gen::battle::{Party, Battle, BattleError, PartyMember};
pub fn display(text: String, left: bool)
{
if left
{
println!("{:>80}", text);
}
else
{
println!("{}", text);
}
}
pub fn display_member(member: Option<PartyMember>, opponent: bool, active: bool)
{
if let Some(monster) = member
{
display_stats(monster.member, opponent, active, None);
}
else
{
display("---".to_string(), true);
display("---".to_string(), true);
println!("");
}
}
pub fn display_active(battle: &Battle, active: usize)
{
println!("");
for index in 0..battle.state().parties()[1].active_count()
{
display_member(battle.state().parties()[1].active_member_alive(index), true, false)
}
for index in 0..battle.state().parties()[0].active_count()
{
let active = active == index;
display_member(battle.state().parties()[0].active_member_alive(index), false, active)
}
println!("");
}
pub fn display_stats(monster: &Monster, opponent: bool, active: bool, index: Option<usize>)
{
let active_arrow = if active
{
"-> "
}
else
{
""
};
let active_index = if let Some(num) = index
{
format!("{}", num)
}
else
{
String::new()
};
let form_name = if monster.species().species().forms.len() > 1
{
format!(" ({})", monster.species().species().form(monster.form() as usize))
}
else
{
String::new()
};
display(format!("{}{}{}{} Lv. {}", active_index, active_arrow, monster.nick(), form_name,
monster.level()), opponent);
display(format!("{}HP: {}/{}", active_arrow, monster.health(), monster.stat_health()),
opponent);
println!("");
}
pub fn display_attacks(attacks: &[MonsterAttack])
|
pub fn display_party(party: &Party, back: bool)
{
println!("Party members:");
println!("");
let mut alternate = true;
for (index, monster) in party.iter().enumerate()
{
alternate =!alternate;
display(format!("{}) {} Lv. {}", index + 1, monster.nick(), monster.level()),
alternate);
display(format!(" HP: {}/{}", monster.health(), monster.stat_health()),
alternate);
display(format!(" ATK: {}, DEF: {}", monster.stat_attack(),
monster.stat_defense()), alternate);
display(format!(" SPATK: {}, SPDEF: {}", monster.stat_spattack(),
monster.stat_spdefense()), alternate);
display(format!(" SPD: {}", monster.stat_speed()), alternate);
}
println!("");
if back
{
println!("{:>80}", format!("{}) {}", party.member_count() + 1, "Back"));
}
}
/// Returns a descriptive string of the given battle error.
pub fn display_error(err: BattleError)
{
let error_str = match err
{
BattleError::None =>
{
unreachable!();
}
BattleError::Rejected =>
{
unreachable!();
}
BattleError::AttackLimit =>
{
"Selected move has no PP left."
}
BattleError::AttackTarget =>
{
"Invalid target."
}
BattleError::SwitchActive =>
{
"Selected party member is already active."
}
BattleError::SwitchHealth =>
{
"Selected party member has no health."
}
BattleError::SwitchQueued =>
{
"Selected party member is already queued to switch in."
}
};
println!("Invalid selection: {}", error_str);
}
|
{
let mut alternate = true;
for (index, attack) in attacks.iter().enumerate()
{
alternate = !alternate;
display(format!("{}) {}", index + 1, attack.attack().name()), alternate);
display(format!(" {}", attack.attack().element.name()), alternate);
display(format!(" Limit: {}/{}", attack.limit_left(), attack.limit_max()), alternate);
}
println!("");
println!("{:>80}", format!("{}) {}", attacks.len() + 1, "Back"));
}
|
identifier_body
|
associated-types-sugar-path.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.
// Test paths to associated types using the type-parameter-only sugar.
pub trait Foo {
type A;
fn boo(&self) -> Self::A;
}
impl Foo for int {
type A = uint;
fn boo(&self) -> uint {
5
}
}
// Using a type via a function.
pub fn bar<T: Foo>(a: T, x: T::A) -> T::A {
let _: T::A = a.boo();
x
}
// Using a type via an impl.
trait C {
fn f();
fn g(&self) { }
}
struct B<X>(X);
impl<T: Foo> C for B<T> {
fn f() {
let x: T::A = panic!();
}
}
pub fn
|
() {
let z: uint = bar(2, 4);
}
|
main
|
identifier_name
|
associated-types-sugar-path.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.
// Test paths to associated types using the type-parameter-only sugar.
|
}
impl Foo for int {
type A = uint;
fn boo(&self) -> uint {
5
}
}
// Using a type via a function.
pub fn bar<T: Foo>(a: T, x: T::A) -> T::A {
let _: T::A = a.boo();
x
}
// Using a type via an impl.
trait C {
fn f();
fn g(&self) { }
}
struct B<X>(X);
impl<T: Foo> C for B<T> {
fn f() {
let x: T::A = panic!();
}
}
pub fn main() {
let z: uint = bar(2, 4);
}
|
pub trait Foo {
type A;
fn boo(&self) -> Self::A;
|
random_line_split
|
navigatorinfo.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::str::DOMString;
use std::borrow::Cow;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}
pub fn ProductSub() -> DOMString {
DOMString::from("20100101")
}
pub fn Vendor() -> DOMString {
DOMString::from("")
}
pub fn VendorSub() -> DOMString {
DOMString::from("")
}
pub fn TaintEnabled() -> bool {
false
}
pub fn AppName() -> DOMString {
DOMString::from("Netscape") // Like Gecko/Webkit
}
|
pub fn AppCodeName() -> DOMString {
DOMString::from("Mozilla")
}
#[cfg(target_os = "windows")]
pub fn Platform() -> DOMString {
DOMString::from("Win32")
}
#[cfg(any(target_os = "android", target_os = "linux"))]
pub fn Platform() -> DOMString {
DOMString::from("Linux")
}
#[cfg(target_os = "macos")]
pub fn Platform() -> DOMString {
DOMString::from("Mac")
}
#[cfg(target_os = "ios")]
pub fn Platform() -> DOMString {
DOMString::from("iOS")
}
pub fn UserAgent(user_agent: Cow<'static, str>) -> DOMString {
DOMString::from(&*user_agent)
}
pub fn AppVersion() -> DOMString {
DOMString::from("4.0")
}
pub fn Language() -> DOMString {
DOMString::from("en-US")
}
|
random_line_split
|
|
navigatorinfo.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::str::DOMString;
use std::borrow::Cow;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}
pub fn ProductSub() -> DOMString {
DOMString::from("20100101")
}
pub fn Vendor() -> DOMString {
DOMString::from("")
}
pub fn VendorSub() -> DOMString {
DOMString::from("")
}
pub fn TaintEnabled() -> bool {
false
}
pub fn AppName() -> DOMString
|
pub fn AppCodeName() -> DOMString {
DOMString::from("Mozilla")
}
#[cfg(target_os = "windows")]
pub fn Platform() -> DOMString {
DOMString::from("Win32")
}
#[cfg(any(target_os = "android", target_os = "linux"))]
pub fn Platform() -> DOMString {
DOMString::from("Linux")
}
#[cfg(target_os = "macos")]
pub fn Platform() -> DOMString {
DOMString::from("Mac")
}
#[cfg(target_os = "ios")]
pub fn Platform() -> DOMString {
DOMString::from("iOS")
}
pub fn UserAgent(user_agent: Cow<'static, str>) -> DOMString {
DOMString::from(&*user_agent)
}
pub fn AppVersion() -> DOMString {
DOMString::from("4.0")
}
pub fn Language() -> DOMString {
DOMString::from("en-US")
}
|
{
DOMString::from("Netscape") // Like Gecko/Webkit
}
|
identifier_body
|
navigatorinfo.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::str::DOMString;
use std::borrow::Cow;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}
pub fn ProductSub() -> DOMString {
DOMString::from("20100101")
}
pub fn Vendor() -> DOMString {
DOMString::from("")
}
pub fn VendorSub() -> DOMString {
DOMString::from("")
}
pub fn TaintEnabled() -> bool {
false
}
pub fn AppName() -> DOMString {
DOMString::from("Netscape") // Like Gecko/Webkit
}
pub fn AppCodeName() -> DOMString {
DOMString::from("Mozilla")
}
#[cfg(target_os = "windows")]
pub fn Platform() -> DOMString {
DOMString::from("Win32")
}
#[cfg(any(target_os = "android", target_os = "linux"))]
pub fn Platform() -> DOMString {
DOMString::from("Linux")
}
#[cfg(target_os = "macos")]
pub fn
|
() -> DOMString {
DOMString::from("Mac")
}
#[cfg(target_os = "ios")]
pub fn Platform() -> DOMString {
DOMString::from("iOS")
}
pub fn UserAgent(user_agent: Cow<'static, str>) -> DOMString {
DOMString::from(&*user_agent)
}
pub fn AppVersion() -> DOMString {
DOMString::from("4.0")
}
pub fn Language() -> DOMString {
DOMString::from("en-US")
}
|
Platform
|
identifier_name
|
issue-14959.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.
//
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
use std::ops::Fn;
trait Response {}
trait Request {}
trait Ingot<R, S> {
fn enter(&mut self, _: &mut R, _: &mut S, a: &mut Alloy) -> Status;
}
#[allow(dead_code)]
struct HelloWorld;
struct SendFile<'a>;
struct Alloy;
enum Status {
Continue
}
impl Alloy {
fn find<T>(&self) -> Option<T> {
None
}
}
impl<'a, 'b> Fn<(&'b mut (Response+'b),)> for SendFile<'a> {
type Output = ();
extern "rust-call" fn call(&self, (_res,): (&'b mut (Response+'b),)) {}
}
impl<Rq: Request, Rs: Response> Ingot<Rq, Rs> for HelloWorld {
fn enter(&mut self, _req: &mut Rq, res: &mut Rs, alloy: &mut Alloy) -> Status {
let send_file = alloy.find::<SendFile>().unwrap();
send_file(res);
Status::Continue
}
}
fn main() {}
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
random_line_split
|
issue-14959.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.
#![feature(unboxed_closures)]
use std::ops::Fn;
trait Response {}
trait Request {}
trait Ingot<R, S> {
fn enter(&mut self, _: &mut R, _: &mut S, a: &mut Alloy) -> Status;
}
#[allow(dead_code)]
struct HelloWorld;
struct SendFile<'a>;
struct Alloy;
enum Status {
Continue
}
impl Alloy {
fn find<T>(&self) -> Option<T> {
None
}
}
impl<'a, 'b> Fn<(&'b mut (Response+'b),)> for SendFile<'a> {
type Output = ();
extern "rust-call" fn call(&self, (_res,): (&'b mut (Response+'b),)) {}
}
impl<Rq: Request, Rs: Response> Ingot<Rq, Rs> for HelloWorld {
fn enter(&mut self, _req: &mut Rq, res: &mut Rs, alloy: &mut Alloy) -> Status
|
}
fn main() {}
|
{
let send_file = alloy.find::<SendFile>().unwrap();
send_file(res);
Status::Continue
}
|
identifier_body
|
issue-14959.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.
#![feature(unboxed_closures)]
use std::ops::Fn;
trait Response {}
trait Request {}
trait Ingot<R, S> {
fn enter(&mut self, _: &mut R, _: &mut S, a: &mut Alloy) -> Status;
}
#[allow(dead_code)]
struct HelloWorld;
struct SendFile<'a>;
struct
|
;
enum Status {
Continue
}
impl Alloy {
fn find<T>(&self) -> Option<T> {
None
}
}
impl<'a, 'b> Fn<(&'b mut (Response+'b),)> for SendFile<'a> {
type Output = ();
extern "rust-call" fn call(&self, (_res,): (&'b mut (Response+'b),)) {}
}
impl<Rq: Request, Rs: Response> Ingot<Rq, Rs> for HelloWorld {
fn enter(&mut self, _req: &mut Rq, res: &mut Rs, alloy: &mut Alloy) -> Status {
let send_file = alloy.find::<SendFile>().unwrap();
send_file(res);
Status::Continue
}
}
fn main() {}
|
Alloy
|
identifier_name
|
errors.rs
|
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::error;
use std::fmt;
use vm::costs::{CostErrors, ExecutionCost};
use vm::diagnostic::{DiagnosableError, Diagnostic};
use vm::representations::PreSymbolicExpression;
use vm::types::{TupleTypeSignature, TypeSignature};
use vm::MAX_CALL_STACK_DEPTH;
pub type ParseResult<T> = Result<T, ParseError>;
#[derive(Debug, PartialEq)]
pub enum ParseErrors {
CostOverflow,
CostBalanceExceeded(ExecutionCost, ExecutionCost),
MemoryBalanceExceeded(u64, u64),
TooManyExpressions,
ExpressionStackDepthTooDeep,
FailedCapturingInput,
SeparatorExpected(String),
SeparatorExpectedAfterColon(String),
ProgramTooLarge,
IllegalVariableName(String),
IllegalContractName(String),
UnknownQuotedValue(String),
FailedParsingIntValue(String),
FailedParsingBuffer(String),
FailedParsingHexValue(String, String),
FailedParsingPrincipal(String),
FailedParsingField(String),
FailedParsingRemainder(String),
ClosingParenthesisUnexpected,
ClosingParenthesisExpected,
ClosingTupleLiteralUnexpected,
ClosingTupleLiteralExpected,
CircularReference(Vec<String>),
TupleColonExpected(usize),
TupleCommaExpected(usize),
TupleItemExpected(usize),
NameAlreadyUsed(String),
TraitReferenceNotAllowed,
ImportTraitBadSignature,
DefineTraitBadSignature,
ImplTraitBadSignature,
TraitReferenceUnknown(String),
CommaSeparatorUnexpected,
ColonSeparatorUnexpected,
InvalidCharactersDetected,
InvalidEscaping,
CostComputationFailed(String),
}
#[derive(Debug, PartialEq)]
pub struct ParseError {
pub err: ParseErrors,
pub pre_expressions: Option<Vec<PreSymbolicExpression>>,
pub diagnostic: Diagnostic,
}
impl ParseError {
pub fn new(err: ParseErrors) -> ParseError {
let diagnostic = Diagnostic::err(&err);
ParseError {
err,
pre_expressions: None,
diagnostic,
}
}
pub fn has_pre_expression(&self) -> bool {
self.pre_expressions.is_some()
}
pub fn set_pre_expression(&mut self, expr: &PreSymbolicExpression) {
self.diagnostic.spans = vec![expr.span.clone()];
self.pre_expressions.replace(vec![expr.clone()]);
}
pub fn set_pre_expressions(&mut self, exprs: Vec<PreSymbolicExpression>)
|
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.err {
_ => write!(f, "{:?}", self.err),
}?;
if let Some(ref e) = self.pre_expressions {
write!(f, "\nNear:\n{:?}", e)?;
}
Ok(())
}
}
impl error::Error for ParseError {
fn source(&self) -> Option<&(dyn error::Error +'static)> {
match self.err {
_ => None,
}
}
}
impl From<ParseErrors> for ParseError {
fn from(err: ParseErrors) -> Self {
ParseError::new(err)
}
}
impl From<CostErrors> for ParseError {
fn from(err: CostErrors) -> Self {
match err {
CostErrors::CostOverflow => ParseError::new(ParseErrors::CostOverflow),
CostErrors::CostBalanceExceeded(a, b) => {
ParseError::new(ParseErrors::CostBalanceExceeded(a, b))
}
CostErrors::MemoryBalanceExceeded(a, b) => {
ParseError::new(ParseErrors::MemoryBalanceExceeded(a, b))
}
CostErrors::CostComputationFailed(s) => {
ParseError::new(ParseErrors::CostComputationFailed(s))
}
CostErrors::CostContractLoadFailure => ParseError::new(
ParseErrors::CostComputationFailed("Failed to load cost contract".into()),
),
}
}
}
impl DiagnosableError for ParseErrors {
fn message(&self) -> String {
match &self {
ParseErrors::CostOverflow => format!("Used up cost budget during the parse"),
ParseErrors::CostBalanceExceeded(bal, used) => format!(
"Used up cost budget during the parse: {} balance, {} used",
bal, used
),
ParseErrors::MemoryBalanceExceeded(bal, used) => format!(
"Used up memory budget during the parse: {} balance, {} used",
bal, used
),
ParseErrors::TooManyExpressions => format!("Too many expressions"),
ParseErrors::FailedCapturingInput => format!("Failed to capture value from input"),
ParseErrors::SeparatorExpected(found) => {
format!("Expected whitespace or a close parens. Found: '{}'", found)
}
ParseErrors::SeparatorExpectedAfterColon(found) => {
format!("Whitespace expected after colon (:), Found: '{}'", found)
}
ParseErrors::ProgramTooLarge => format!("Program too large to parse"),
ParseErrors::IllegalContractName(contract_name) => {
format!("Illegal contract name: '{}'", contract_name)
}
ParseErrors::IllegalVariableName(var_name) => {
format!("Illegal variable name: '{}'", var_name)
}
ParseErrors::UnknownQuotedValue(value) => format!("Unknown 'quoted value '{}'", value),
ParseErrors::FailedParsingIntValue(value) => {
format!("Failed to parse int literal '{}'", value)
}
ParseErrors::FailedParsingHexValue(value, x) => {
format!("Invalid hex-string literal {}: {}", value, x)
}
ParseErrors::FailedParsingPrincipal(value) => {
format!("Invalid principal literal: {}", value)
}
ParseErrors::FailedParsingBuffer(value) => format!("Invalid buffer literal: {}", value),
ParseErrors::FailedParsingField(value) => format!("Invalid field literal: {}", value),
ParseErrors::FailedParsingRemainder(remainder) => {
format!("Failed to lex input remainder: '{}'", remainder)
}
ParseErrors::ClosingParenthesisUnexpected => {
format!("Tried to close list which isn't open.")
}
ParseErrors::ClosingParenthesisExpected => {
format!("List expressions (..) left opened.")
}
ParseErrors::ClosingTupleLiteralUnexpected => {
format!("Tried to close tuple literal which isn't open.")
}
ParseErrors::ClosingTupleLiteralExpected => {
format!("Tuple literal {{..}} left opened.")
}
ParseErrors::ColonSeparatorUnexpected => format!("Misplaced colon."),
ParseErrors::CommaSeparatorUnexpected => format!("Misplaced comma."),
ParseErrors::TupleColonExpected(i) => {
format!("Tuple literal construction expects a colon at index {}", i)
}
ParseErrors::TupleCommaExpected(i) => {
format!("Tuple literal construction expects a comma at index {}", i)
}
ParseErrors::TupleItemExpected(i) => format!(
"Tuple literal construction expects a key or value at index {}",
i
),
ParseErrors::CircularReference(function_names) => format!(
"detected interdependent functions ({})",
function_names.join(", ")
),
ParseErrors::NameAlreadyUsed(name) => {
format!("defining '{}' conflicts with previous value", name)
}
ParseErrors::ImportTraitBadSignature => {
format!("(use-trait...) expects a trait name and a trait identifier")
}
ParseErrors::DefineTraitBadSignature => {
format!("(define-trait...) expects a trait name and a trait definition")
}
ParseErrors::ImplTraitBadSignature => {
format!("(impl-trait...) expects a trait identifier")
}
ParseErrors::TraitReferenceNotAllowed => format!("trait references can not be stored"),
ParseErrors::TraitReferenceUnknown(trait_name) => {
format!("use of undeclared trait <{}>", trait_name)
}
ParseErrors::ExpressionStackDepthTooDeep => format!(
"AST has too deep of an expression nesting. The maximum stack depth is {}",
MAX_CALL_STACK_DEPTH
),
ParseErrors::InvalidCharactersDetected => format!("invalid characters detected"),
ParseErrors::InvalidEscaping => format!("invalid escaping detected in string"),
ParseErrors::CostComputationFailed(s) => format!("Cost computation failed: {}", s),
}
}
fn suggestion(&self) -> Option<String> {
match &self {
_ => None,
}
}
}
|
{
self.diagnostic.spans = exprs.iter().map(|e| e.span.clone()).collect();
self.pre_expressions.replace(exprs.clone().to_vec());
}
|
identifier_body
|
errors.rs
|
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::error;
use std::fmt;
use vm::costs::{CostErrors, ExecutionCost};
use vm::diagnostic::{DiagnosableError, Diagnostic};
use vm::representations::PreSymbolicExpression;
use vm::types::{TupleTypeSignature, TypeSignature};
use vm::MAX_CALL_STACK_DEPTH;
pub type ParseResult<T> = Result<T, ParseError>;
#[derive(Debug, PartialEq)]
pub enum ParseErrors {
CostOverflow,
CostBalanceExceeded(ExecutionCost, ExecutionCost),
MemoryBalanceExceeded(u64, u64),
TooManyExpressions,
ExpressionStackDepthTooDeep,
FailedCapturingInput,
SeparatorExpected(String),
SeparatorExpectedAfterColon(String),
ProgramTooLarge,
IllegalVariableName(String),
IllegalContractName(String),
UnknownQuotedValue(String),
FailedParsingIntValue(String),
FailedParsingBuffer(String),
FailedParsingHexValue(String, String),
FailedParsingPrincipal(String),
FailedParsingField(String),
FailedParsingRemainder(String),
ClosingParenthesisUnexpected,
ClosingParenthesisExpected,
ClosingTupleLiteralUnexpected,
ClosingTupleLiteralExpected,
CircularReference(Vec<String>),
TupleColonExpected(usize),
TupleCommaExpected(usize),
TupleItemExpected(usize),
NameAlreadyUsed(String),
TraitReferenceNotAllowed,
ImportTraitBadSignature,
DefineTraitBadSignature,
ImplTraitBadSignature,
TraitReferenceUnknown(String),
CommaSeparatorUnexpected,
ColonSeparatorUnexpected,
InvalidCharactersDetected,
InvalidEscaping,
CostComputationFailed(String),
}
#[derive(Debug, PartialEq)]
pub struct ParseError {
pub err: ParseErrors,
pub pre_expressions: Option<Vec<PreSymbolicExpression>>,
pub diagnostic: Diagnostic,
}
impl ParseError {
pub fn new(err: ParseErrors) -> ParseError {
let diagnostic = Diagnostic::err(&err);
ParseError {
err,
pre_expressions: None,
diagnostic,
}
}
pub fn has_pre_expression(&self) -> bool {
self.pre_expressions.is_some()
}
pub fn set_pre_expression(&mut self, expr: &PreSymbolicExpression) {
self.diagnostic.spans = vec![expr.span.clone()];
self.pre_expressions.replace(vec![expr.clone()]);
}
pub fn set_pre_expressions(&mut self, exprs: Vec<PreSymbolicExpression>) {
self.diagnostic.spans = exprs.iter().map(|e| e.span.clone()).collect();
self.pre_expressions.replace(exprs.clone().to_vec());
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.err {
_ => write!(f, "{:?}", self.err),
}?;
if let Some(ref e) = self.pre_expressions {
write!(f, "\nNear:\n{:?}", e)?;
}
Ok(())
}
}
impl error::Error for ParseError {
fn source(&self) -> Option<&(dyn error::Error +'static)> {
match self.err {
_ => None,
}
}
}
impl From<ParseErrors> for ParseError {
fn from(err: ParseErrors) -> Self {
ParseError::new(err)
}
}
impl From<CostErrors> for ParseError {
fn from(err: CostErrors) -> Self {
match err {
CostErrors::CostOverflow => ParseError::new(ParseErrors::CostOverflow),
CostErrors::CostBalanceExceeded(a, b) => {
ParseError::new(ParseErrors::CostBalanceExceeded(a, b))
}
CostErrors::MemoryBalanceExceeded(a, b) => {
ParseError::new(ParseErrors::MemoryBalanceExceeded(a, b))
}
CostErrors::CostComputationFailed(s) => {
ParseError::new(ParseErrors::CostComputationFailed(s))
}
CostErrors::CostContractLoadFailure => ParseError::new(
ParseErrors::CostComputationFailed("Failed to load cost contract".into()),
),
}
}
}
impl DiagnosableError for ParseErrors {
fn message(&self) -> String {
match &self {
ParseErrors::CostOverflow => format!("Used up cost budget during the parse"),
ParseErrors::CostBalanceExceeded(bal, used) => format!(
"Used up cost budget during the parse: {} balance, {} used",
bal, used
),
ParseErrors::MemoryBalanceExceeded(bal, used) => format!(
"Used up memory budget during the parse: {} balance, {} used",
bal, used
),
ParseErrors::TooManyExpressions => format!("Too many expressions"),
ParseErrors::FailedCapturingInput => format!("Failed to capture value from input"),
ParseErrors::SeparatorExpected(found) => {
format!("Expected whitespace or a close parens. Found: '{}'", found)
}
ParseErrors::SeparatorExpectedAfterColon(found) =>
|
ParseErrors::ProgramTooLarge => format!("Program too large to parse"),
ParseErrors::IllegalContractName(contract_name) => {
format!("Illegal contract name: '{}'", contract_name)
}
ParseErrors::IllegalVariableName(var_name) => {
format!("Illegal variable name: '{}'", var_name)
}
ParseErrors::UnknownQuotedValue(value) => format!("Unknown 'quoted value '{}'", value),
ParseErrors::FailedParsingIntValue(value) => {
format!("Failed to parse int literal '{}'", value)
}
ParseErrors::FailedParsingHexValue(value, x) => {
format!("Invalid hex-string literal {}: {}", value, x)
}
ParseErrors::FailedParsingPrincipal(value) => {
format!("Invalid principal literal: {}", value)
}
ParseErrors::FailedParsingBuffer(value) => format!("Invalid buffer literal: {}", value),
ParseErrors::FailedParsingField(value) => format!("Invalid field literal: {}", value),
ParseErrors::FailedParsingRemainder(remainder) => {
format!("Failed to lex input remainder: '{}'", remainder)
}
ParseErrors::ClosingParenthesisUnexpected => {
format!("Tried to close list which isn't open.")
}
ParseErrors::ClosingParenthesisExpected => {
format!("List expressions (..) left opened.")
}
ParseErrors::ClosingTupleLiteralUnexpected => {
format!("Tried to close tuple literal which isn't open.")
}
ParseErrors::ClosingTupleLiteralExpected => {
format!("Tuple literal {{..}} left opened.")
}
ParseErrors::ColonSeparatorUnexpected => format!("Misplaced colon."),
ParseErrors::CommaSeparatorUnexpected => format!("Misplaced comma."),
ParseErrors::TupleColonExpected(i) => {
format!("Tuple literal construction expects a colon at index {}", i)
}
ParseErrors::TupleCommaExpected(i) => {
format!("Tuple literal construction expects a comma at index {}", i)
}
ParseErrors::TupleItemExpected(i) => format!(
"Tuple literal construction expects a key or value at index {}",
i
),
ParseErrors::CircularReference(function_names) => format!(
"detected interdependent functions ({})",
function_names.join(", ")
),
ParseErrors::NameAlreadyUsed(name) => {
format!("defining '{}' conflicts with previous value", name)
}
ParseErrors::ImportTraitBadSignature => {
format!("(use-trait...) expects a trait name and a trait identifier")
}
ParseErrors::DefineTraitBadSignature => {
format!("(define-trait...) expects a trait name and a trait definition")
}
ParseErrors::ImplTraitBadSignature => {
format!("(impl-trait...) expects a trait identifier")
}
ParseErrors::TraitReferenceNotAllowed => format!("trait references can not be stored"),
ParseErrors::TraitReferenceUnknown(trait_name) => {
format!("use of undeclared trait <{}>", trait_name)
}
ParseErrors::ExpressionStackDepthTooDeep => format!(
"AST has too deep of an expression nesting. The maximum stack depth is {}",
MAX_CALL_STACK_DEPTH
),
ParseErrors::InvalidCharactersDetected => format!("invalid characters detected"),
ParseErrors::InvalidEscaping => format!("invalid escaping detected in string"),
ParseErrors::CostComputationFailed(s) => format!("Cost computation failed: {}", s),
}
}
fn suggestion(&self) -> Option<String> {
match &self {
_ => None,
}
}
}
|
{
format!("Whitespace expected after colon (:), Found: '{}'", found)
}
|
conditional_block
|
errors.rs
|
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::error;
use std::fmt;
use vm::costs::{CostErrors, ExecutionCost};
use vm::diagnostic::{DiagnosableError, Diagnostic};
use vm::representations::PreSymbolicExpression;
use vm::types::{TupleTypeSignature, TypeSignature};
use vm::MAX_CALL_STACK_DEPTH;
pub type ParseResult<T> = Result<T, ParseError>;
#[derive(Debug, PartialEq)]
pub enum ParseErrors {
CostOverflow,
CostBalanceExceeded(ExecutionCost, ExecutionCost),
MemoryBalanceExceeded(u64, u64),
TooManyExpressions,
ExpressionStackDepthTooDeep,
FailedCapturingInput,
SeparatorExpected(String),
SeparatorExpectedAfterColon(String),
ProgramTooLarge,
IllegalVariableName(String),
IllegalContractName(String),
UnknownQuotedValue(String),
FailedParsingIntValue(String),
FailedParsingBuffer(String),
FailedParsingHexValue(String, String),
FailedParsingPrincipal(String),
FailedParsingField(String),
FailedParsingRemainder(String),
ClosingParenthesisUnexpected,
ClosingParenthesisExpected,
ClosingTupleLiteralUnexpected,
ClosingTupleLiteralExpected,
CircularReference(Vec<String>),
TupleColonExpected(usize),
TupleCommaExpected(usize),
TupleItemExpected(usize),
NameAlreadyUsed(String),
TraitReferenceNotAllowed,
ImportTraitBadSignature,
DefineTraitBadSignature,
ImplTraitBadSignature,
TraitReferenceUnknown(String),
CommaSeparatorUnexpected,
ColonSeparatorUnexpected,
InvalidCharactersDetected,
InvalidEscaping,
CostComputationFailed(String),
}
#[derive(Debug, PartialEq)]
pub struct ParseError {
pub err: ParseErrors,
pub pre_expressions: Option<Vec<PreSymbolicExpression>>,
pub diagnostic: Diagnostic,
}
impl ParseError {
pub fn
|
(err: ParseErrors) -> ParseError {
let diagnostic = Diagnostic::err(&err);
ParseError {
err,
pre_expressions: None,
diagnostic,
}
}
pub fn has_pre_expression(&self) -> bool {
self.pre_expressions.is_some()
}
pub fn set_pre_expression(&mut self, expr: &PreSymbolicExpression) {
self.diagnostic.spans = vec![expr.span.clone()];
self.pre_expressions.replace(vec![expr.clone()]);
}
pub fn set_pre_expressions(&mut self, exprs: Vec<PreSymbolicExpression>) {
self.diagnostic.spans = exprs.iter().map(|e| e.span.clone()).collect();
self.pre_expressions.replace(exprs.clone().to_vec());
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.err {
_ => write!(f, "{:?}", self.err),
}?;
if let Some(ref e) = self.pre_expressions {
write!(f, "\nNear:\n{:?}", e)?;
}
Ok(())
}
}
impl error::Error for ParseError {
fn source(&self) -> Option<&(dyn error::Error +'static)> {
match self.err {
_ => None,
}
}
}
impl From<ParseErrors> for ParseError {
fn from(err: ParseErrors) -> Self {
ParseError::new(err)
}
}
impl From<CostErrors> for ParseError {
fn from(err: CostErrors) -> Self {
match err {
CostErrors::CostOverflow => ParseError::new(ParseErrors::CostOverflow),
CostErrors::CostBalanceExceeded(a, b) => {
ParseError::new(ParseErrors::CostBalanceExceeded(a, b))
}
CostErrors::MemoryBalanceExceeded(a, b) => {
ParseError::new(ParseErrors::MemoryBalanceExceeded(a, b))
}
CostErrors::CostComputationFailed(s) => {
ParseError::new(ParseErrors::CostComputationFailed(s))
}
CostErrors::CostContractLoadFailure => ParseError::new(
ParseErrors::CostComputationFailed("Failed to load cost contract".into()),
),
}
}
}
impl DiagnosableError for ParseErrors {
fn message(&self) -> String {
match &self {
ParseErrors::CostOverflow => format!("Used up cost budget during the parse"),
ParseErrors::CostBalanceExceeded(bal, used) => format!(
"Used up cost budget during the parse: {} balance, {} used",
bal, used
),
ParseErrors::MemoryBalanceExceeded(bal, used) => format!(
"Used up memory budget during the parse: {} balance, {} used",
bal, used
),
ParseErrors::TooManyExpressions => format!("Too many expressions"),
ParseErrors::FailedCapturingInput => format!("Failed to capture value from input"),
ParseErrors::SeparatorExpected(found) => {
format!("Expected whitespace or a close parens. Found: '{}'", found)
}
ParseErrors::SeparatorExpectedAfterColon(found) => {
format!("Whitespace expected after colon (:), Found: '{}'", found)
}
ParseErrors::ProgramTooLarge => format!("Program too large to parse"),
ParseErrors::IllegalContractName(contract_name) => {
format!("Illegal contract name: '{}'", contract_name)
}
ParseErrors::IllegalVariableName(var_name) => {
format!("Illegal variable name: '{}'", var_name)
}
ParseErrors::UnknownQuotedValue(value) => format!("Unknown 'quoted value '{}'", value),
ParseErrors::FailedParsingIntValue(value) => {
format!("Failed to parse int literal '{}'", value)
}
ParseErrors::FailedParsingHexValue(value, x) => {
format!("Invalid hex-string literal {}: {}", value, x)
}
ParseErrors::FailedParsingPrincipal(value) => {
format!("Invalid principal literal: {}", value)
}
ParseErrors::FailedParsingBuffer(value) => format!("Invalid buffer literal: {}", value),
ParseErrors::FailedParsingField(value) => format!("Invalid field literal: {}", value),
ParseErrors::FailedParsingRemainder(remainder) => {
format!("Failed to lex input remainder: '{}'", remainder)
}
ParseErrors::ClosingParenthesisUnexpected => {
format!("Tried to close list which isn't open.")
}
ParseErrors::ClosingParenthesisExpected => {
format!("List expressions (..) left opened.")
}
ParseErrors::ClosingTupleLiteralUnexpected => {
format!("Tried to close tuple literal which isn't open.")
}
ParseErrors::ClosingTupleLiteralExpected => {
format!("Tuple literal {{..}} left opened.")
}
ParseErrors::ColonSeparatorUnexpected => format!("Misplaced colon."),
ParseErrors::CommaSeparatorUnexpected => format!("Misplaced comma."),
ParseErrors::TupleColonExpected(i) => {
format!("Tuple literal construction expects a colon at index {}", i)
}
ParseErrors::TupleCommaExpected(i) => {
format!("Tuple literal construction expects a comma at index {}", i)
}
ParseErrors::TupleItemExpected(i) => format!(
"Tuple literal construction expects a key or value at index {}",
i
),
ParseErrors::CircularReference(function_names) => format!(
"detected interdependent functions ({})",
function_names.join(", ")
),
ParseErrors::NameAlreadyUsed(name) => {
format!("defining '{}' conflicts with previous value", name)
}
ParseErrors::ImportTraitBadSignature => {
format!("(use-trait...) expects a trait name and a trait identifier")
}
ParseErrors::DefineTraitBadSignature => {
format!("(define-trait...) expects a trait name and a trait definition")
}
ParseErrors::ImplTraitBadSignature => {
format!("(impl-trait...) expects a trait identifier")
}
ParseErrors::TraitReferenceNotAllowed => format!("trait references can not be stored"),
ParseErrors::TraitReferenceUnknown(trait_name) => {
format!("use of undeclared trait <{}>", trait_name)
}
ParseErrors::ExpressionStackDepthTooDeep => format!(
"AST has too deep of an expression nesting. The maximum stack depth is {}",
MAX_CALL_STACK_DEPTH
),
ParseErrors::InvalidCharactersDetected => format!("invalid characters detected"),
ParseErrors::InvalidEscaping => format!("invalid escaping detected in string"),
ParseErrors::CostComputationFailed(s) => format!("Cost computation failed: {}", s),
}
}
fn suggestion(&self) -> Option<String> {
match &self {
_ => None,
}
}
}
|
new
|
identifier_name
|
errors.rs
|
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::error;
use std::fmt;
use vm::costs::{CostErrors, ExecutionCost};
use vm::diagnostic::{DiagnosableError, Diagnostic};
use vm::representations::PreSymbolicExpression;
use vm::types::{TupleTypeSignature, TypeSignature};
use vm::MAX_CALL_STACK_DEPTH;
pub type ParseResult<T> = Result<T, ParseError>;
#[derive(Debug, PartialEq)]
pub enum ParseErrors {
CostOverflow,
CostBalanceExceeded(ExecutionCost, ExecutionCost),
MemoryBalanceExceeded(u64, u64),
TooManyExpressions,
ExpressionStackDepthTooDeep,
FailedCapturingInput,
SeparatorExpected(String),
SeparatorExpectedAfterColon(String),
ProgramTooLarge,
IllegalVariableName(String),
IllegalContractName(String),
UnknownQuotedValue(String),
FailedParsingIntValue(String),
FailedParsingBuffer(String),
FailedParsingHexValue(String, String),
FailedParsingPrincipal(String),
FailedParsingField(String),
FailedParsingRemainder(String),
ClosingParenthesisUnexpected,
ClosingParenthesisExpected,
ClosingTupleLiteralUnexpected,
ClosingTupleLiteralExpected,
CircularReference(Vec<String>),
TupleColonExpected(usize),
TupleCommaExpected(usize),
TupleItemExpected(usize),
NameAlreadyUsed(String),
TraitReferenceNotAllowed,
ImportTraitBadSignature,
DefineTraitBadSignature,
ImplTraitBadSignature,
TraitReferenceUnknown(String),
CommaSeparatorUnexpected,
ColonSeparatorUnexpected,
InvalidCharactersDetected,
InvalidEscaping,
CostComputationFailed(String),
}
#[derive(Debug, PartialEq)]
pub struct ParseError {
pub err: ParseErrors,
pub pre_expressions: Option<Vec<PreSymbolicExpression>>,
pub diagnostic: Diagnostic,
}
impl ParseError {
pub fn new(err: ParseErrors) -> ParseError {
let diagnostic = Diagnostic::err(&err);
ParseError {
err,
pre_expressions: None,
diagnostic,
}
}
pub fn has_pre_expression(&self) -> bool {
self.pre_expressions.is_some()
}
pub fn set_pre_expression(&mut self, expr: &PreSymbolicExpression) {
self.diagnostic.spans = vec![expr.span.clone()];
self.pre_expressions.replace(vec![expr.clone()]);
}
pub fn set_pre_expressions(&mut self, exprs: Vec<PreSymbolicExpression>) {
self.diagnostic.spans = exprs.iter().map(|e| e.span.clone()).collect();
self.pre_expressions.replace(exprs.clone().to_vec());
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.err {
_ => write!(f, "{:?}", self.err),
}?;
if let Some(ref e) = self.pre_expressions {
write!(f, "\nNear:\n{:?}", e)?;
}
Ok(())
}
}
impl error::Error for ParseError {
fn source(&self) -> Option<&(dyn error::Error +'static)> {
match self.err {
_ => None,
}
}
}
impl From<ParseErrors> for ParseError {
fn from(err: ParseErrors) -> Self {
ParseError::new(err)
}
}
impl From<CostErrors> for ParseError {
fn from(err: CostErrors) -> Self {
match err {
CostErrors::CostOverflow => ParseError::new(ParseErrors::CostOverflow),
CostErrors::CostBalanceExceeded(a, b) => {
ParseError::new(ParseErrors::CostBalanceExceeded(a, b))
}
CostErrors::MemoryBalanceExceeded(a, b) => {
ParseError::new(ParseErrors::MemoryBalanceExceeded(a, b))
}
CostErrors::CostComputationFailed(s) => {
ParseError::new(ParseErrors::CostComputationFailed(s))
}
CostErrors::CostContractLoadFailure => ParseError::new(
ParseErrors::CostComputationFailed("Failed to load cost contract".into()),
),
}
}
}
impl DiagnosableError for ParseErrors {
fn message(&self) -> String {
match &self {
ParseErrors::CostOverflow => format!("Used up cost budget during the parse"),
ParseErrors::CostBalanceExceeded(bal, used) => format!(
"Used up cost budget during the parse: {} balance, {} used",
bal, used
),
ParseErrors::MemoryBalanceExceeded(bal, used) => format!(
"Used up memory budget during the parse: {} balance, {} used",
bal, used
),
ParseErrors::TooManyExpressions => format!("Too many expressions"),
ParseErrors::FailedCapturingInput => format!("Failed to capture value from input"),
ParseErrors::SeparatorExpected(found) => {
format!("Expected whitespace or a close parens. Found: '{}'", found)
}
ParseErrors::SeparatorExpectedAfterColon(found) => {
format!("Whitespace expected after colon (:), Found: '{}'", found)
}
ParseErrors::ProgramTooLarge => format!("Program too large to parse"),
ParseErrors::IllegalContractName(contract_name) => {
format!("Illegal contract name: '{}'", contract_name)
}
ParseErrors::IllegalVariableName(var_name) => {
format!("Illegal variable name: '{}'", var_name)
}
ParseErrors::UnknownQuotedValue(value) => format!("Unknown 'quoted value '{}'", value),
ParseErrors::FailedParsingIntValue(value) => {
format!("Failed to parse int literal '{}'", value)
}
ParseErrors::FailedParsingHexValue(value, x) => {
format!("Invalid hex-string literal {}: {}", value, x)
}
ParseErrors::FailedParsingPrincipal(value) => {
format!("Invalid principal literal: {}", value)
}
ParseErrors::FailedParsingBuffer(value) => format!("Invalid buffer literal: {}", value),
ParseErrors::FailedParsingField(value) => format!("Invalid field literal: {}", value),
ParseErrors::FailedParsingRemainder(remainder) => {
format!("Failed to lex input remainder: '{}'", remainder)
}
ParseErrors::ClosingParenthesisUnexpected => {
format!("Tried to close list which isn't open.")
}
ParseErrors::ClosingParenthesisExpected => {
format!("List expressions (..) left opened.")
}
ParseErrors::ClosingTupleLiteralUnexpected => {
|
ParseErrors::ClosingTupleLiteralExpected => {
format!("Tuple literal {{..}} left opened.")
}
ParseErrors::ColonSeparatorUnexpected => format!("Misplaced colon."),
ParseErrors::CommaSeparatorUnexpected => format!("Misplaced comma."),
ParseErrors::TupleColonExpected(i) => {
format!("Tuple literal construction expects a colon at index {}", i)
}
ParseErrors::TupleCommaExpected(i) => {
format!("Tuple literal construction expects a comma at index {}", i)
}
ParseErrors::TupleItemExpected(i) => format!(
"Tuple literal construction expects a key or value at index {}",
i
),
ParseErrors::CircularReference(function_names) => format!(
"detected interdependent functions ({})",
function_names.join(", ")
),
ParseErrors::NameAlreadyUsed(name) => {
format!("defining '{}' conflicts with previous value", name)
}
ParseErrors::ImportTraitBadSignature => {
format!("(use-trait...) expects a trait name and a trait identifier")
}
ParseErrors::DefineTraitBadSignature => {
format!("(define-trait...) expects a trait name and a trait definition")
}
ParseErrors::ImplTraitBadSignature => {
format!("(impl-trait...) expects a trait identifier")
}
ParseErrors::TraitReferenceNotAllowed => format!("trait references can not be stored"),
ParseErrors::TraitReferenceUnknown(trait_name) => {
format!("use of undeclared trait <{}>", trait_name)
}
ParseErrors::ExpressionStackDepthTooDeep => format!(
"AST has too deep of an expression nesting. The maximum stack depth is {}",
MAX_CALL_STACK_DEPTH
),
ParseErrors::InvalidCharactersDetected => format!("invalid characters detected"),
ParseErrors::InvalidEscaping => format!("invalid escaping detected in string"),
ParseErrors::CostComputationFailed(s) => format!("Cost computation failed: {}", s),
}
}
fn suggestion(&self) -> Option<String> {
match &self {
_ => None,
}
}
}
|
format!("Tried to close tuple literal which isn't open.")
}
|
random_line_split
|
mod.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Utilities for random number generation
//!
//! The key functions are `random()` and `Rng::gen()`. These are polymorphic
//! and so can be used to generate any type that implements `Rand`. Type inference
//! means that often a simple call to `rand::random()` or `rng.gen()` will
//! suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
//!
//! See the `distributions` submodule for sampling random numbers from
//! distributions like normal and exponential.
//!
//! # Thread-local RNG
//!
//! There is built-in support for a RNG associated with each thread stored
//! in thread-local storage. This RNG can be accessed via `thread_rng`, or
//! used implicitly via `random`. This RNG is normally randomly seeded
//! from an operating-system source of randomness, e.g. `/dev/urandom` on
//! Unix systems, and will automatically reseed itself from this source
//! after generating 32 KiB of random data.
//!
//! # Cryptographic security
//!
//! An application that requires an entropy source for cryptographic purposes
//! must use `OsRng`, which reads randomness from the source that the operating
//! system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on Windows).
//! The other random number generators provided by this module are not suitable
//! for such purposes.
//!
//! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
//! This module uses `/dev/urandom` for the following reasons:
//!
//! - On Linux, `/dev/random` may block if entropy pool is empty; `/dev/urandom` will not block.
//! This does not mean that `/dev/random` provides better output than
//! `/dev/urandom`; the kernel internally runs a cryptographically secure pseudorandom
//! number generator (CSPRNG) based on entropy pool for random number generation,
//! so the "quality" of `/dev/random` is not better than `/dev/urandom` in most cases.
//! However, this means that `/dev/urandom` can yield somewhat predictable randomness
//! if the entropy pool is very small, such as immediately after first booting.
//! Linux 3.17 added the `getrandom(2)` system call which solves the issue: it blocks if entropy
//! pool is not initialized yet, but it does not block once initialized.
//! `OsRng` tries to use `getrandom(2)` if available, and use `/dev/urandom` fallback if not.
//! If an application does not have `getrandom` and likely to be run soon after first booting,
//! or on a system with very few entropy sources, one should consider using `/dev/random` via
//! `ReaderRng`.
//! - On some systems (e.g. FreeBSD, OpenBSD and Mac OS X) there is no difference
//! between the two sources. (Also note that, on some systems e.g. FreeBSD, both `/dev/random`
//! and `/dev/urandom` may block once if the CSPRNG has not seeded yet.)
#![unstable(feature = "rand")]
use prelude::v1::*;
use cell::RefCell;
use io;
use mem;
use rc::Rc;
#[cfg(target_pointer_width = "32")]
use core_rand::IsaacRng as IsaacWordRng;
#[cfg(target_pointer_width = "64")]
use core_rand::Isaac64Rng as IsaacWordRng;
pub use core_rand::{Rand, Rng, SeedableRng};
pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng};
pub use core_rand::reseeding;
pub use rand::os::OsRng;
pub mod os;
pub mod reader;
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[derive(Copy, Clone)]
pub struct StdRng {
rng: IsaacWordRng,
}
impl StdRng {
/// Create a randomly seeded instance of `StdRng`.
///
/// This is a very expensive operation as it has to read
/// randomness from the operating system and use this in an
/// expensive seeding operation. If one is only generating a small
/// number of random numbers, or doesn't need the utmost speed for
/// generating each number, `thread_rng` and/or `random` may be more
/// appropriate.
///
/// Reading the randomness from the OS may fail, and any error is
/// propagated via the `io::Result` return value.
pub fn new() -> io::Result<StdRng> {
OsRng::new().map(|mut r| StdRng { rng: r.gen() })
}
}
impl Rng for StdRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.rng.next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.rng.next_u64()
}
}
impl<'a> SeedableRng<&'a [usize]> for StdRng {
fn reseed(&mut self, seed: &'a [usize]) {
// the internal RNG can just be seeded from the above
// randomness.
self.rng.reseed(unsafe {mem::transmute(seed)})
}
fn from_seed(seed: &'a [usize]) -> StdRng {
StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
}
}
/// Controls how the thread-local RNG is reseeded.
struct ThreadRngReseeder;
impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
fn reseed(&mut self, rng: &mut StdRng) {
*rng = match StdRng::new() {
Ok(r) => r,
Err(e) => panic!("could not reseed thread_rng: {}", e)
}
}
}
const THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
/// The thread-local RNG.
#[derive(Clone)]
pub struct ThreadRng {
rng: Rc<RefCell<ThreadRngInner>>,
}
/// Retrieve the lazily-initialized thread-local random number
/// generator, seeded by the system. Intended to be used in method
/// chaining style, e.g. `thread_rng().gen::<isize>()`.
///
/// The RNG provided will reseed itself from the operating system
/// after generating a certain amount of randomness.
///
/// The internal RNG used is platform and architecture dependent, even
/// if the operating system random number generator is rigged to give
/// the same sequence always. If absolute consistency is required,
/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
pub fn thread_rng() -> ThreadRng {
// used to make space in TLS for a random number generator
thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
let r = match StdRng::new() {
Ok(r) => r,
Err(e) => panic!("could not initialize thread_rng: {}", e)
};
let rng = reseeding::ReseedingRng::new(r,
THREAD_RNG_RESEED_THRESHOLD,
ThreadRngReseeder);
Rc::new(RefCell::new(rng))
});
ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
}
impl Rng for ThreadRng {
fn
|
(&mut self) -> u32 {
self.rng.borrow_mut().next_u32()
}
fn next_u64(&mut self) -> u64 {
self.rng.borrow_mut().next_u64()
}
#[inline]
fn fill_bytes(&mut self, bytes: &mut [u8]) {
self.rng.borrow_mut().fill_bytes(bytes)
}
}
|
next_u32
|
identifier_name
|
mod.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Utilities for random number generation
//!
//! The key functions are `random()` and `Rng::gen()`. These are polymorphic
//! and so can be used to generate any type that implements `Rand`. Type inference
//! means that often a simple call to `rand::random()` or `rng.gen()` will
//! suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
//!
//! See the `distributions` submodule for sampling random numbers from
//! distributions like normal and exponential.
//!
//! # Thread-local RNG
//!
//! There is built-in support for a RNG associated with each thread stored
//! in thread-local storage. This RNG can be accessed via `thread_rng`, or
//! used implicitly via `random`. This RNG is normally randomly seeded
//! from an operating-system source of randomness, e.g. `/dev/urandom` on
//! Unix systems, and will automatically reseed itself from this source
//! after generating 32 KiB of random data.
//!
//! # Cryptographic security
//!
//! An application that requires an entropy source for cryptographic purposes
//! must use `OsRng`, which reads randomness from the source that the operating
//! system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on Windows).
//! The other random number generators provided by this module are not suitable
//! for such purposes.
//!
//! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
//! This module uses `/dev/urandom` for the following reasons:
//!
//! - On Linux, `/dev/random` may block if entropy pool is empty; `/dev/urandom` will not block.
//! This does not mean that `/dev/random` provides better output than
//! `/dev/urandom`; the kernel internally runs a cryptographically secure pseudorandom
//! number generator (CSPRNG) based on entropy pool for random number generation,
//! so the "quality" of `/dev/random` is not better than `/dev/urandom` in most cases.
//! However, this means that `/dev/urandom` can yield somewhat predictable randomness
//! if the entropy pool is very small, such as immediately after first booting.
//! Linux 3.17 added the `getrandom(2)` system call which solves the issue: it blocks if entropy
//! pool is not initialized yet, but it does not block once initialized.
//! `OsRng` tries to use `getrandom(2)` if available, and use `/dev/urandom` fallback if not.
//! If an application does not have `getrandom` and likely to be run soon after first booting,
//! or on a system with very few entropy sources, one should consider using `/dev/random` via
//! `ReaderRng`.
//! - On some systems (e.g. FreeBSD, OpenBSD and Mac OS X) there is no difference
//! between the two sources. (Also note that, on some systems e.g. FreeBSD, both `/dev/random`
//! and `/dev/urandom` may block once if the CSPRNG has not seeded yet.)
#![unstable(feature = "rand")]
use prelude::v1::*;
use cell::RefCell;
use io;
use mem;
use rc::Rc;
#[cfg(target_pointer_width = "32")]
use core_rand::IsaacRng as IsaacWordRng;
#[cfg(target_pointer_width = "64")]
use core_rand::Isaac64Rng as IsaacWordRng;
pub use core_rand::{Rand, Rng, SeedableRng};
pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng};
pub use core_rand::reseeding;
pub use rand::os::OsRng;
pub mod os;
pub mod reader;
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[derive(Copy, Clone)]
pub struct StdRng {
rng: IsaacWordRng,
}
impl StdRng {
/// Create a randomly seeded instance of `StdRng`.
///
/// This is a very expensive operation as it has to read
/// randomness from the operating system and use this in an
/// expensive seeding operation. If one is only generating a small
/// number of random numbers, or doesn't need the utmost speed for
/// generating each number, `thread_rng` and/or `random` may be more
/// appropriate.
///
/// Reading the randomness from the OS may fail, and any error is
/// propagated via the `io::Result` return value.
pub fn new() -> io::Result<StdRng> {
OsRng::new().map(|mut r| StdRng { rng: r.gen() })
}
}
impl Rng for StdRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.rng.next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.rng.next_u64()
}
}
impl<'a> SeedableRng<&'a [usize]> for StdRng {
fn reseed(&mut self, seed: &'a [usize]) {
// the internal RNG can just be seeded from the above
// randomness.
self.rng.reseed(unsafe {mem::transmute(seed)})
}
fn from_seed(seed: &'a [usize]) -> StdRng {
StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
}
}
/// Controls how the thread-local RNG is reseeded.
struct ThreadRngReseeder;
impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
fn reseed(&mut self, rng: &mut StdRng) {
*rng = match StdRng::new() {
Ok(r) => r,
Err(e) => panic!("could not reseed thread_rng: {}", e)
}
}
}
const THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
/// The thread-local RNG.
#[derive(Clone)]
pub struct ThreadRng {
rng: Rc<RefCell<ThreadRngInner>>,
}
/// Retrieve the lazily-initialized thread-local random number
/// generator, seeded by the system. Intended to be used in method
/// chaining style, e.g. `thread_rng().gen::<isize>()`.
///
/// The RNG provided will reseed itself from the operating system
/// after generating a certain amount of randomness.
///
/// The internal RNG used is platform and architecture dependent, even
/// if the operating system random number generator is rigged to give
/// the same sequence always. If absolute consistency is required,
/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
pub fn thread_rng() -> ThreadRng {
// used to make space in TLS for a random number generator
thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
let r = match StdRng::new() {
Ok(r) => r,
Err(e) => panic!("could not initialize thread_rng: {}", e)
};
let rng = reseeding::ReseedingRng::new(r,
THREAD_RNG_RESEED_THRESHOLD,
ThreadRngReseeder);
Rc::new(RefCell::new(rng))
});
ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
}
impl Rng for ThreadRng {
fn next_u32(&mut self) -> u32 {
self.rng.borrow_mut().next_u32()
}
fn next_u64(&mut self) -> u64 {
self.rng.borrow_mut().next_u64()
}
#[inline]
fn fill_bytes(&mut self, bytes: &mut [u8])
|
}
|
{
self.rng.borrow_mut().fill_bytes(bytes)
}
|
identifier_body
|
mod.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Utilities for random number generation
//!
//! The key functions are `random()` and `Rng::gen()`. These are polymorphic
//! and so can be used to generate any type that implements `Rand`. Type inference
//! means that often a simple call to `rand::random()` or `rng.gen()` will
//! suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
//!
//! See the `distributions` submodule for sampling random numbers from
//! distributions like normal and exponential.
//!
|
//! There is built-in support for a RNG associated with each thread stored
//! in thread-local storage. This RNG can be accessed via `thread_rng`, or
//! used implicitly via `random`. This RNG is normally randomly seeded
//! from an operating-system source of randomness, e.g. `/dev/urandom` on
//! Unix systems, and will automatically reseed itself from this source
//! after generating 32 KiB of random data.
//!
//! # Cryptographic security
//!
//! An application that requires an entropy source for cryptographic purposes
//! must use `OsRng`, which reads randomness from the source that the operating
//! system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on Windows).
//! The other random number generators provided by this module are not suitable
//! for such purposes.
//!
//! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
//! This module uses `/dev/urandom` for the following reasons:
//!
//! - On Linux, `/dev/random` may block if entropy pool is empty; `/dev/urandom` will not block.
//! This does not mean that `/dev/random` provides better output than
//! `/dev/urandom`; the kernel internally runs a cryptographically secure pseudorandom
//! number generator (CSPRNG) based on entropy pool for random number generation,
//! so the "quality" of `/dev/random` is not better than `/dev/urandom` in most cases.
//! However, this means that `/dev/urandom` can yield somewhat predictable randomness
//! if the entropy pool is very small, such as immediately after first booting.
//! Linux 3.17 added the `getrandom(2)` system call which solves the issue: it blocks if entropy
//! pool is not initialized yet, but it does not block once initialized.
//! `OsRng` tries to use `getrandom(2)` if available, and use `/dev/urandom` fallback if not.
//! If an application does not have `getrandom` and likely to be run soon after first booting,
//! or on a system with very few entropy sources, one should consider using `/dev/random` via
//! `ReaderRng`.
//! - On some systems (e.g. FreeBSD, OpenBSD and Mac OS X) there is no difference
//! between the two sources. (Also note that, on some systems e.g. FreeBSD, both `/dev/random`
//! and `/dev/urandom` may block once if the CSPRNG has not seeded yet.)
#![unstable(feature = "rand")]
use prelude::v1::*;
use cell::RefCell;
use io;
use mem;
use rc::Rc;
#[cfg(target_pointer_width = "32")]
use core_rand::IsaacRng as IsaacWordRng;
#[cfg(target_pointer_width = "64")]
use core_rand::Isaac64Rng as IsaacWordRng;
pub use core_rand::{Rand, Rng, SeedableRng};
pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng};
pub use core_rand::reseeding;
pub use rand::os::OsRng;
pub mod os;
pub mod reader;
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[derive(Copy, Clone)]
pub struct StdRng {
rng: IsaacWordRng,
}
impl StdRng {
/// Create a randomly seeded instance of `StdRng`.
///
/// This is a very expensive operation as it has to read
/// randomness from the operating system and use this in an
/// expensive seeding operation. If one is only generating a small
/// number of random numbers, or doesn't need the utmost speed for
/// generating each number, `thread_rng` and/or `random` may be more
/// appropriate.
///
/// Reading the randomness from the OS may fail, and any error is
/// propagated via the `io::Result` return value.
pub fn new() -> io::Result<StdRng> {
OsRng::new().map(|mut r| StdRng { rng: r.gen() })
}
}
impl Rng for StdRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.rng.next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.rng.next_u64()
}
}
impl<'a> SeedableRng<&'a [usize]> for StdRng {
fn reseed(&mut self, seed: &'a [usize]) {
// the internal RNG can just be seeded from the above
// randomness.
self.rng.reseed(unsafe {mem::transmute(seed)})
}
fn from_seed(seed: &'a [usize]) -> StdRng {
StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
}
}
/// Controls how the thread-local RNG is reseeded.
struct ThreadRngReseeder;
impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
fn reseed(&mut self, rng: &mut StdRng) {
*rng = match StdRng::new() {
Ok(r) => r,
Err(e) => panic!("could not reseed thread_rng: {}", e)
}
}
}
const THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
/// The thread-local RNG.
#[derive(Clone)]
pub struct ThreadRng {
rng: Rc<RefCell<ThreadRngInner>>,
}
/// Retrieve the lazily-initialized thread-local random number
/// generator, seeded by the system. Intended to be used in method
/// chaining style, e.g. `thread_rng().gen::<isize>()`.
///
/// The RNG provided will reseed itself from the operating system
/// after generating a certain amount of randomness.
///
/// The internal RNG used is platform and architecture dependent, even
/// if the operating system random number generator is rigged to give
/// the same sequence always. If absolute consistency is required,
/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
pub fn thread_rng() -> ThreadRng {
// used to make space in TLS for a random number generator
thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
let r = match StdRng::new() {
Ok(r) => r,
Err(e) => panic!("could not initialize thread_rng: {}", e)
};
let rng = reseeding::ReseedingRng::new(r,
THREAD_RNG_RESEED_THRESHOLD,
ThreadRngReseeder);
Rc::new(RefCell::new(rng))
});
ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
}
impl Rng for ThreadRng {
fn next_u32(&mut self) -> u32 {
self.rng.borrow_mut().next_u32()
}
fn next_u64(&mut self) -> u64 {
self.rng.borrow_mut().next_u64()
}
#[inline]
fn fill_bytes(&mut self, bytes: &mut [u8]) {
self.rng.borrow_mut().fill_bytes(bytes)
}
}
|
//! # Thread-local RNG
//!
|
random_line_split
|
const-vecs-and-slices.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.
extern crate debug;
static x : [int,..4] = [1,2,3,4];
static y : &'static [int] = &[1,2,3,4];
pub fn main() {
println!("{:?}", x[1]);
println!("{:?}", y[1]);
assert_eq!(x[1], 2);
assert_eq!(x[3], 4);
assert_eq!(x[3], y[3]);
|
}
|
random_line_split
|
|
const-vecs-and-slices.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.
extern crate debug;
static x : [int,..4] = [1,2,3,4];
static y : &'static [int] = &[1,2,3,4];
pub fn
|
() {
println!("{:?}", x[1]);
println!("{:?}", y[1]);
assert_eq!(x[1], 2);
assert_eq!(x[3], 4);
assert_eq!(x[3], y[3]);
}
|
main
|
identifier_name
|
const-vecs-and-slices.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.
extern crate debug;
static x : [int,..4] = [1,2,3,4];
static y : &'static [int] = &[1,2,3,4];
pub fn main()
|
{
println!("{:?}", x[1]);
println!("{:?}", y[1]);
assert_eq!(x[1], 2);
assert_eq!(x[3], 4);
assert_eq!(x[3], y[3]);
}
|
identifier_body
|
|
stage0-clone-contravariant-lifetime.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.
// A zero-dependency test that covers some basic traits, default
// methods, etc. When mucking about with basic type system stuff I
// often encounter problems in the iterator trait, so it's useful to
// have hanging around. -nmatsakis
// error-pattern: requires `start` lang_item
#![no_std]
#![feature(lang_items)]
#[lang = "sized"]
pub trait Sized for Sized? {
// Empty.
}
pub mod std {
pub mod clone {
pub trait Clone {
fn clone(&self) -> Self;
}
}
}
pub struct ContravariantLifetime<'a>;
impl <'a> ::std::clone::Clone for ContravariantLifetime<'a> {
#[inline]
fn clone(&self) -> ContravariantLifetime<'a> {
match *self { ContravariantLifetime => ContravariantLifetime, }
}
}
fn main()
|
{ }
|
identifier_body
|
|
stage0-clone-contravariant-lifetime.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.
// A zero-dependency test that covers some basic traits, default
// methods, etc. When mucking about with basic type system stuff I
// often encounter problems in the iterator trait, so it's useful to
// have hanging around. -nmatsakis
// error-pattern: requires `start` lang_item
#![no_std]
#![feature(lang_items)]
#[lang = "sized"]
pub trait Sized for Sized? {
// Empty.
}
pub mod std {
pub mod clone {
pub trait Clone {
fn clone(&self) -> Self;
}
}
}
pub struct ContravariantLifetime<'a>;
impl <'a> ::std::clone::Clone for ContravariantLifetime<'a> {
#[inline]
fn clone(&self) -> ContravariantLifetime<'a> {
match *self { ContravariantLifetime => ContravariantLifetime, }
}
}
fn main() { }
|
random_line_split
|
|
stage0-clone-contravariant-lifetime.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.
// A zero-dependency test that covers some basic traits, default
// methods, etc. When mucking about with basic type system stuff I
// often encounter problems in the iterator trait, so it's useful to
// have hanging around. -nmatsakis
// error-pattern: requires `start` lang_item
#![no_std]
#![feature(lang_items)]
#[lang = "sized"]
pub trait Sized for Sized? {
// Empty.
}
pub mod std {
pub mod clone {
pub trait Clone {
fn clone(&self) -> Self;
}
}
}
pub struct
|
<'a>;
impl <'a> ::std::clone::Clone for ContravariantLifetime<'a> {
#[inline]
fn clone(&self) -> ContravariantLifetime<'a> {
match *self { ContravariantLifetime => ContravariantLifetime, }
}
}
fn main() { }
|
ContravariantLifetime
|
identifier_name
|
migrations.rs
|
use failure::format_err;
use log::info;
use rusqlite::{Connection, Transaction};
use crate::db::migrations_code;
use crate::errors::*;
const CREATE_VERSIONS: &str = r#"
create table __version ( current_version integer primary key )
"#;
pub trait Migration {
fn run(&self, tx: &Transaction) -> Result<()>;
}
struct SQLMigration {
sql: &'static str,
}
impl Migration for SQLMigration {
fn run(&self, tx: &Transaction) -> Result<()> {
tx.execute_batch(self.sql).map_err(|e| {
format_err!(
"Error running migration: \n---\n{}\n---\n. Error: {}",
self.sql,
e
)
})
}
}
fn sql(s: &'static str) -> Box<dyn Migration> {
Box::new(SQLMigration { sql: s })
}
fn all_migrations() -> Vec<Box<dyn Migration>> {
vec![
sql(r#"
create table users (
id integer not null,
github_name varchar not null,
slack_name varchar not null,
UNIQUE( github_name ),
PRIMARY KEY( id )
);
create table repos (
id integer not null,
repo varchar not null,
channel varchar not null,
force_push_notify tinyint not null,
force_push_reapply_statuses varchar not null,
branches varchar not null,
jira_projects varchar not null,
jira_versions_enabled tinyint not null,
version_script varchar not null,
release_branch_prefix varchar not null,
UNIQUE( repo, branches ),
PRIMARY KEY( id )
);
"#),
sql(r#"alter table users add column mute_direct_messages tinyint not null default 0"#),
sql(r#"alter table repos add column next_branch_suffix varchar not null default ''"#),
sql(r#"
create table repos_jiras (
repo_id integer not null,
jira varchar not null,
channel varchar not null,
version_script varchar not null,
release_branch_regex varchar not null,
PRIMARY KEY( repo_id, jira )
);
"#),
Box::new(migrations_code::MigrationReposJiras {}),
sql(r#"
create table repos_new (
id integer not null,
repo varchar not null,
channel varchar not null,
force_push_notify tinyint not null,
release_branch_prefix varchar not null,
UNIQUE( repo ),
PRIMARY KEY( id )
);
insert into repos_new
select id, repo, channel, force_push_notify, release_branch_prefix
from repos;
drop table repos;
alter table repos_new rename to repos;
"#),
]
}
fn current_version(conn: &Connection) -> Result<Option<i32>> {
let mut version: Option<i32> = None;
conn.query_row("SELECT current_version from __version", [], |row| {
version = row.get(0).ok();
Ok(())
})
.map_err(|_| format_err!("Could not get current version"))?;
Ok(version)
}
pub fn migrate(conn: &mut Connection) -> Result<()> {
let version: Option<i32> = match current_version(conn) {
Ok(v) => v,
Err(_) => {
// versions table probably doesn't exist.
conn.execute(CREATE_VERSIONS, [])
.map_err(|e| format_err!("Error creating versions table: {}", e))?;
None
}
};
info!("Current schema version: {:?}", version);
let migrations = all_migrations();
let mut next_version = version.map(|v| v + 1).unwrap_or(0);
while next_version < migrations.len() as i32 {
info!("Migrating to schema version: {:}", next_version);
let tx = conn.transaction()?;
let next_version_unsigned: usize = next_version as usize;
migrations[next_version_unsigned].run(&tx)?;
if next_version == 0 {
|
} else {
tx.execute(
"UPDATE __version set current_version =?1",
&[&next_version],
)
}
.map_err(|e| format_err!("Error updating version: {}", e))?;
tx.commit()?;
next_version += 1;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempdir::TempDir;
#[test]
fn test_migration_versions() {
let temp_dir = TempDir::new("users.rs").unwrap();
let db_file = temp_dir.path().join("db.sqlite3");
let mut conn = Connection::open(&db_file).expect("create temp database");
migrate(&mut conn).unwrap();
assert_eq!(
Some((all_migrations().len() as i32) - 1),
current_version(&conn).unwrap()
);
}
#[test]
fn test_multiple_migration() {
let temp_dir = TempDir::new("users.rs").unwrap();
let db_file = temp_dir.path().join("db.sqlite3");
let mut conn = Connection::open(&db_file).expect("create temp database");
// migration #1
migrate(&mut conn).unwrap();
// migration #2
if let Err(e) = migrate(&mut conn) {
panic!("Failed: expected second migration to be a noop: {}", e);
}
}
}
|
tx.execute("INSERT INTO __version VALUES (?1)", &[&next_version])
|
random_line_split
|
migrations.rs
|
use failure::format_err;
use log::info;
use rusqlite::{Connection, Transaction};
use crate::db::migrations_code;
use crate::errors::*;
const CREATE_VERSIONS: &str = r#"
create table __version ( current_version integer primary key )
"#;
pub trait Migration {
fn run(&self, tx: &Transaction) -> Result<()>;
}
struct SQLMigration {
sql: &'static str,
}
impl Migration for SQLMigration {
fn run(&self, tx: &Transaction) -> Result<()> {
tx.execute_batch(self.sql).map_err(|e| {
format_err!(
"Error running migration: \n---\n{}\n---\n. Error: {}",
self.sql,
e
)
})
}
}
fn sql(s: &'static str) -> Box<dyn Migration> {
Box::new(SQLMigration { sql: s })
}
fn all_migrations() -> Vec<Box<dyn Migration>> {
vec![
sql(r#"
create table users (
id integer not null,
github_name varchar not null,
slack_name varchar not null,
UNIQUE( github_name ),
PRIMARY KEY( id )
);
create table repos (
id integer not null,
repo varchar not null,
channel varchar not null,
force_push_notify tinyint not null,
force_push_reapply_statuses varchar not null,
branches varchar not null,
jira_projects varchar not null,
jira_versions_enabled tinyint not null,
version_script varchar not null,
release_branch_prefix varchar not null,
UNIQUE( repo, branches ),
PRIMARY KEY( id )
);
"#),
sql(r#"alter table users add column mute_direct_messages tinyint not null default 0"#),
sql(r#"alter table repos add column next_branch_suffix varchar not null default ''"#),
sql(r#"
create table repos_jiras (
repo_id integer not null,
jira varchar not null,
channel varchar not null,
version_script varchar not null,
release_branch_regex varchar not null,
PRIMARY KEY( repo_id, jira )
);
"#),
Box::new(migrations_code::MigrationReposJiras {}),
sql(r#"
create table repos_new (
id integer not null,
repo varchar not null,
channel varchar not null,
force_push_notify tinyint not null,
release_branch_prefix varchar not null,
UNIQUE( repo ),
PRIMARY KEY( id )
);
insert into repos_new
select id, repo, channel, force_push_notify, release_branch_prefix
from repos;
drop table repos;
alter table repos_new rename to repos;
"#),
]
}
fn current_version(conn: &Connection) -> Result<Option<i32>> {
let mut version: Option<i32> = None;
conn.query_row("SELECT current_version from __version", [], |row| {
version = row.get(0).ok();
Ok(())
})
.map_err(|_| format_err!("Could not get current version"))?;
Ok(version)
}
pub fn migrate(conn: &mut Connection) -> Result<()> {
let version: Option<i32> = match current_version(conn) {
Ok(v) => v,
Err(_) => {
// versions table probably doesn't exist.
conn.execute(CREATE_VERSIONS, [])
.map_err(|e| format_err!("Error creating versions table: {}", e))?;
None
}
};
info!("Current schema version: {:?}", version);
let migrations = all_migrations();
let mut next_version = version.map(|v| v + 1).unwrap_or(0);
while next_version < migrations.len() as i32 {
info!("Migrating to schema version: {:}", next_version);
let tx = conn.transaction()?;
let next_version_unsigned: usize = next_version as usize;
migrations[next_version_unsigned].run(&tx)?;
if next_version == 0 {
tx.execute("INSERT INTO __version VALUES (?1)", &[&next_version])
} else {
tx.execute(
"UPDATE __version set current_version =?1",
&[&next_version],
)
}
.map_err(|e| format_err!("Error updating version: {}", e))?;
tx.commit()?;
next_version += 1;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempdir::TempDir;
#[test]
fn
|
() {
let temp_dir = TempDir::new("users.rs").unwrap();
let db_file = temp_dir.path().join("db.sqlite3");
let mut conn = Connection::open(&db_file).expect("create temp database");
migrate(&mut conn).unwrap();
assert_eq!(
Some((all_migrations().len() as i32) - 1),
current_version(&conn).unwrap()
);
}
#[test]
fn test_multiple_migration() {
let temp_dir = TempDir::new("users.rs").unwrap();
let db_file = temp_dir.path().join("db.sqlite3");
let mut conn = Connection::open(&db_file).expect("create temp database");
// migration #1
migrate(&mut conn).unwrap();
// migration #2
if let Err(e) = migrate(&mut conn) {
panic!("Failed: expected second migration to be a noop: {}", e);
}
}
}
|
test_migration_versions
|
identifier_name
|
migrations.rs
|
use failure::format_err;
use log::info;
use rusqlite::{Connection, Transaction};
use crate::db::migrations_code;
use crate::errors::*;
const CREATE_VERSIONS: &str = r#"
create table __version ( current_version integer primary key )
"#;
pub trait Migration {
fn run(&self, tx: &Transaction) -> Result<()>;
}
struct SQLMigration {
sql: &'static str,
}
impl Migration for SQLMigration {
fn run(&self, tx: &Transaction) -> Result<()> {
tx.execute_batch(self.sql).map_err(|e| {
format_err!(
"Error running migration: \n---\n{}\n---\n. Error: {}",
self.sql,
e
)
})
}
}
fn sql(s: &'static str) -> Box<dyn Migration> {
Box::new(SQLMigration { sql: s })
}
fn all_migrations() -> Vec<Box<dyn Migration>> {
vec![
sql(r#"
create table users (
id integer not null,
github_name varchar not null,
slack_name varchar not null,
UNIQUE( github_name ),
PRIMARY KEY( id )
);
create table repos (
id integer not null,
repo varchar not null,
channel varchar not null,
force_push_notify tinyint not null,
force_push_reapply_statuses varchar not null,
branches varchar not null,
jira_projects varchar not null,
jira_versions_enabled tinyint not null,
version_script varchar not null,
release_branch_prefix varchar not null,
UNIQUE( repo, branches ),
PRIMARY KEY( id )
);
"#),
sql(r#"alter table users add column mute_direct_messages tinyint not null default 0"#),
sql(r#"alter table repos add column next_branch_suffix varchar not null default ''"#),
sql(r#"
create table repos_jiras (
repo_id integer not null,
jira varchar not null,
channel varchar not null,
version_script varchar not null,
release_branch_regex varchar not null,
PRIMARY KEY( repo_id, jira )
);
"#),
Box::new(migrations_code::MigrationReposJiras {}),
sql(r#"
create table repos_new (
id integer not null,
repo varchar not null,
channel varchar not null,
force_push_notify tinyint not null,
release_branch_prefix varchar not null,
UNIQUE( repo ),
PRIMARY KEY( id )
);
insert into repos_new
select id, repo, channel, force_push_notify, release_branch_prefix
from repos;
drop table repos;
alter table repos_new rename to repos;
"#),
]
}
fn current_version(conn: &Connection) -> Result<Option<i32>> {
let mut version: Option<i32> = None;
conn.query_row("SELECT current_version from __version", [], |row| {
version = row.get(0).ok();
Ok(())
})
.map_err(|_| format_err!("Could not get current version"))?;
Ok(version)
}
pub fn migrate(conn: &mut Connection) -> Result<()> {
let version: Option<i32> = match current_version(conn) {
Ok(v) => v,
Err(_) => {
// versions table probably doesn't exist.
conn.execute(CREATE_VERSIONS, [])
.map_err(|e| format_err!("Error creating versions table: {}", e))?;
None
}
};
info!("Current schema version: {:?}", version);
let migrations = all_migrations();
let mut next_version = version.map(|v| v + 1).unwrap_or(0);
while next_version < migrations.len() as i32 {
info!("Migrating to schema version: {:}", next_version);
let tx = conn.transaction()?;
let next_version_unsigned: usize = next_version as usize;
migrations[next_version_unsigned].run(&tx)?;
if next_version == 0 {
tx.execute("INSERT INTO __version VALUES (?1)", &[&next_version])
} else {
tx.execute(
"UPDATE __version set current_version =?1",
&[&next_version],
)
}
.map_err(|e| format_err!("Error updating version: {}", e))?;
tx.commit()?;
next_version += 1;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempdir::TempDir;
#[test]
fn test_migration_versions() {
let temp_dir = TempDir::new("users.rs").unwrap();
let db_file = temp_dir.path().join("db.sqlite3");
let mut conn = Connection::open(&db_file).expect("create temp database");
migrate(&mut conn).unwrap();
assert_eq!(
Some((all_migrations().len() as i32) - 1),
current_version(&conn).unwrap()
);
}
#[test]
fn test_multiple_migration() {
let temp_dir = TempDir::new("users.rs").unwrap();
let db_file = temp_dir.path().join("db.sqlite3");
let mut conn = Connection::open(&db_file).expect("create temp database");
// migration #1
migrate(&mut conn).unwrap();
// migration #2
if let Err(e) = migrate(&mut conn)
|
}
}
|
{
panic!("Failed: expected second migration to be a noop: {}", e);
}
|
conditional_block
|
migrations.rs
|
use failure::format_err;
use log::info;
use rusqlite::{Connection, Transaction};
use crate::db::migrations_code;
use crate::errors::*;
const CREATE_VERSIONS: &str = r#"
create table __version ( current_version integer primary key )
"#;
pub trait Migration {
fn run(&self, tx: &Transaction) -> Result<()>;
}
struct SQLMigration {
sql: &'static str,
}
impl Migration for SQLMigration {
fn run(&self, tx: &Transaction) -> Result<()> {
tx.execute_batch(self.sql).map_err(|e| {
format_err!(
"Error running migration: \n---\n{}\n---\n. Error: {}",
self.sql,
e
)
})
}
}
fn sql(s: &'static str) -> Box<dyn Migration> {
Box::new(SQLMigration { sql: s })
}
fn all_migrations() -> Vec<Box<dyn Migration>> {
vec![
sql(r#"
create table users (
id integer not null,
github_name varchar not null,
slack_name varchar not null,
UNIQUE( github_name ),
PRIMARY KEY( id )
);
create table repos (
id integer not null,
repo varchar not null,
channel varchar not null,
force_push_notify tinyint not null,
force_push_reapply_statuses varchar not null,
branches varchar not null,
jira_projects varchar not null,
jira_versions_enabled tinyint not null,
version_script varchar not null,
release_branch_prefix varchar not null,
UNIQUE( repo, branches ),
PRIMARY KEY( id )
);
"#),
sql(r#"alter table users add column mute_direct_messages tinyint not null default 0"#),
sql(r#"alter table repos add column next_branch_suffix varchar not null default ''"#),
sql(r#"
create table repos_jiras (
repo_id integer not null,
jira varchar not null,
channel varchar not null,
version_script varchar not null,
release_branch_regex varchar not null,
PRIMARY KEY( repo_id, jira )
);
"#),
Box::new(migrations_code::MigrationReposJiras {}),
sql(r#"
create table repos_new (
id integer not null,
repo varchar not null,
channel varchar not null,
force_push_notify tinyint not null,
release_branch_prefix varchar not null,
UNIQUE( repo ),
PRIMARY KEY( id )
);
insert into repos_new
select id, repo, channel, force_push_notify, release_branch_prefix
from repos;
drop table repos;
alter table repos_new rename to repos;
"#),
]
}
fn current_version(conn: &Connection) -> Result<Option<i32>> {
let mut version: Option<i32> = None;
conn.query_row("SELECT current_version from __version", [], |row| {
version = row.get(0).ok();
Ok(())
})
.map_err(|_| format_err!("Could not get current version"))?;
Ok(version)
}
pub fn migrate(conn: &mut Connection) -> Result<()> {
let version: Option<i32> = match current_version(conn) {
Ok(v) => v,
Err(_) => {
// versions table probably doesn't exist.
conn.execute(CREATE_VERSIONS, [])
.map_err(|e| format_err!("Error creating versions table: {}", e))?;
None
}
};
info!("Current schema version: {:?}", version);
let migrations = all_migrations();
let mut next_version = version.map(|v| v + 1).unwrap_or(0);
while next_version < migrations.len() as i32 {
info!("Migrating to schema version: {:}", next_version);
let tx = conn.transaction()?;
let next_version_unsigned: usize = next_version as usize;
migrations[next_version_unsigned].run(&tx)?;
if next_version == 0 {
tx.execute("INSERT INTO __version VALUES (?1)", &[&next_version])
} else {
tx.execute(
"UPDATE __version set current_version =?1",
&[&next_version],
)
}
.map_err(|e| format_err!("Error updating version: {}", e))?;
tx.commit()?;
next_version += 1;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempdir::TempDir;
#[test]
fn test_migration_versions() {
let temp_dir = TempDir::new("users.rs").unwrap();
let db_file = temp_dir.path().join("db.sqlite3");
let mut conn = Connection::open(&db_file).expect("create temp database");
migrate(&mut conn).unwrap();
assert_eq!(
Some((all_migrations().len() as i32) - 1),
current_version(&conn).unwrap()
);
}
#[test]
fn test_multiple_migration()
|
}
|
{
let temp_dir = TempDir::new("users.rs").unwrap();
let db_file = temp_dir.path().join("db.sqlite3");
let mut conn = Connection::open(&db_file).expect("create temp database");
// migration #1
migrate(&mut conn).unwrap();
// migration #2
if let Err(e) = migrate(&mut conn) {
panic!("Failed: expected second migration to be a noop: {}", e);
}
}
|
identifier_body
|
role.rs
|
use super::ArgumentConvert;
use crate::{model::prelude::*, prelude::*};
/// Error that can be returned from [`Role::convert`].
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum RoleParseError {
/// When the operation was invoked outside a guild.
NotInGuild,
/// When the guild's roles were not found in cache.
NotInCache,
/// The provided channel string failed to parse, or the parsed result cannot be found in the
/// cache.
NotFoundOrMalformed,
}
impl std::error::Error for RoleParseError {}
impl std::fmt::Display for RoleParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotInGuild => f.write_str("Must invoke this operation in a guild"),
Self::NotInCache => f.write_str("Guild's roles were not found in cache"),
Self::NotFoundOrMalformed => f.write_str("Role not found or unknown format"),
}
}
}
/// Look up a [`Role`] by a string case-insensitively.
///
/// Requires the cache feature to be enabled.
///
/// The lookup strategy is as follows (in order):
/// 1. Lookup by ID
/// 2. [Lookup by mention](`crate::utils::parse_role`).
/// 3. Lookup by name (case-insensitive)
#[cfg(feature = "cache")]
#[async_trait::async_trait]
impl ArgumentConvert for Role {
type Err = RoleParseError;
async fn convert(
ctx: &Context,
guild_id: Option<GuildId>,
_channel_id: Option<ChannelId>,
s: &str,
) -> Result<Self, Self::Err>
|
}
|
{
let roles = ctx
.cache
.guild_roles(guild_id.ok_or(RoleParseError::NotInGuild)?)
.await
.ok_or(RoleParseError::NotInCache)?;
if let Some(role_id) = s.parse::<u64>().ok().or_else(|| crate::utils::parse_role(s)) {
if let Some(role) = roles.get(&RoleId(role_id)) {
return Ok(role.clone());
}
}
if let Some(role) = roles.values().find(|role| role.name.eq_ignore_ascii_case(s)) {
return Ok(role.clone());
}
Err(RoleParseError::NotFoundOrMalformed)
}
|
identifier_body
|
role.rs
|
use super::ArgumentConvert;
use crate::{model::prelude::*, prelude::*};
/// Error that can be returned from [`Role::convert`].
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum RoleParseError {
/// When the operation was invoked outside a guild.
NotInGuild,
/// When the guild's roles were not found in cache.
NotInCache,
/// The provided channel string failed to parse, or the parsed result cannot be found in the
/// cache.
NotFoundOrMalformed,
}
impl std::error::Error for RoleParseError {}
impl std::fmt::Display for RoleParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotInGuild => f.write_str("Must invoke this operation in a guild"),
Self::NotInCache => f.write_str("Guild's roles were not found in cache"),
Self::NotFoundOrMalformed => f.write_str("Role not found or unknown format"),
}
}
}
/// Look up a [`Role`] by a string case-insensitively.
///
/// Requires the cache feature to be enabled.
///
/// The lookup strategy is as follows (in order):
/// 1. Lookup by ID
/// 2. [Lookup by mention](`crate::utils::parse_role`).
/// 3. Lookup by name (case-insensitive)
#[cfg(feature = "cache")]
#[async_trait::async_trait]
impl ArgumentConvert for Role {
type Err = RoleParseError;
async fn convert(
ctx: &Context,
guild_id: Option<GuildId>,
_channel_id: Option<ChannelId>,
s: &str,
) -> Result<Self, Self::Err> {
let roles = ctx
.cache
.guild_roles(guild_id.ok_or(RoleParseError::NotInGuild)?)
.await
.ok_or(RoleParseError::NotInCache)?;
if let Some(role_id) = s.parse::<u64>().ok().or_else(|| crate::utils::parse_role(s)) {
if let Some(role) = roles.get(&RoleId(role_id)) {
return Ok(role.clone());
}
}
if let Some(role) = roles.values().find(|role| role.name.eq_ignore_ascii_case(s))
|
Err(RoleParseError::NotFoundOrMalformed)
}
}
|
{
return Ok(role.clone());
}
|
conditional_block
|
role.rs
|
use super::ArgumentConvert;
use crate::{model::prelude::*, prelude::*};
/// Error that can be returned from [`Role::convert`].
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum RoleParseError {
/// When the operation was invoked outside a guild.
NotInGuild,
/// When the guild's roles were not found in cache.
NotInCache,
/// The provided channel string failed to parse, or the parsed result cannot be found in the
/// cache.
NotFoundOrMalformed,
}
impl std::error::Error for RoleParseError {}
impl std::fmt::Display for RoleParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotInGuild => f.write_str("Must invoke this operation in a guild"),
Self::NotInCache => f.write_str("Guild's roles were not found in cache"),
Self::NotFoundOrMalformed => f.write_str("Role not found or unknown format"),
}
}
}
/// Look up a [`Role`] by a string case-insensitively.
///
/// Requires the cache feature to be enabled.
///
/// The lookup strategy is as follows (in order):
/// 1. Lookup by ID
/// 2. [Lookup by mention](`crate::utils::parse_role`).
/// 3. Lookup by name (case-insensitive)
#[cfg(feature = "cache")]
#[async_trait::async_trait]
impl ArgumentConvert for Role {
type Err = RoleParseError;
async fn
|
(
ctx: &Context,
guild_id: Option<GuildId>,
_channel_id: Option<ChannelId>,
s: &str,
) -> Result<Self, Self::Err> {
let roles = ctx
.cache
.guild_roles(guild_id.ok_or(RoleParseError::NotInGuild)?)
.await
.ok_or(RoleParseError::NotInCache)?;
if let Some(role_id) = s.parse::<u64>().ok().or_else(|| crate::utils::parse_role(s)) {
if let Some(role) = roles.get(&RoleId(role_id)) {
return Ok(role.clone());
}
}
if let Some(role) = roles.values().find(|role| role.name.eq_ignore_ascii_case(s)) {
return Ok(role.clone());
}
Err(RoleParseError::NotFoundOrMalformed)
}
}
|
convert
|
identifier_name
|
role.rs
|
use super::ArgumentConvert;
use crate::{model::prelude::*, prelude::*};
/// Error that can be returned from [`Role::convert`].
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum RoleParseError {
/// When the operation was invoked outside a guild.
NotInGuild,
/// When the guild's roles were not found in cache.
NotInCache,
/// The provided channel string failed to parse, or the parsed result cannot be found in the
/// cache.
NotFoundOrMalformed,
}
impl std::error::Error for RoleParseError {}
impl std::fmt::Display for RoleParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotInGuild => f.write_str("Must invoke this operation in a guild"),
Self::NotInCache => f.write_str("Guild's roles were not found in cache"),
Self::NotFoundOrMalformed => f.write_str("Role not found or unknown format"),
}
}
}
/// Look up a [`Role`] by a string case-insensitively.
///
/// Requires the cache feature to be enabled.
///
/// The lookup strategy is as follows (in order):
/// 1. Lookup by ID
/// 2. [Lookup by mention](`crate::utils::parse_role`).
/// 3. Lookup by name (case-insensitive)
#[cfg(feature = "cache")]
#[async_trait::async_trait]
impl ArgumentConvert for Role {
|
type Err = RoleParseError;
async fn convert(
ctx: &Context,
guild_id: Option<GuildId>,
_channel_id: Option<ChannelId>,
s: &str,
) -> Result<Self, Self::Err> {
let roles = ctx
.cache
.guild_roles(guild_id.ok_or(RoleParseError::NotInGuild)?)
.await
.ok_or(RoleParseError::NotInCache)?;
if let Some(role_id) = s.parse::<u64>().ok().or_else(|| crate::utils::parse_role(s)) {
if let Some(role) = roles.get(&RoleId(role_id)) {
return Ok(role.clone());
}
}
if let Some(role) = roles.values().find(|role| role.name.eq_ignore_ascii_case(s)) {
return Ok(role.clone());
}
Err(RoleParseError::NotFoundOrMalformed)
}
}
|
random_line_split
|
|
private.rs
|
// This file was borrowed from https://github.com/nikomatsakis/rayon/blob/master/src/private.rs
// and is subject to the license and copyright from that project.
//! The public parts of this private module are used to create traits
//! that cannot be implemented outside of our own crate. This way we
//! can feel free to extend those traits without worrying about it
//! being a breaking change for other implementations.
/// If this type is pub but not publicly reachable, third parties
/// can't name it and can't implement traits using it.
pub struct
|
;
macro_rules! private_decl {
() => {
/// This trait is private; this method exists to make it
/// impossible to implement outside the crate.
#[doc(hidden)]
fn __rayon_private__(&self) -> ::private::PrivateMarker;
}
}
macro_rules! private_impl {
() => {
fn __rayon_private__(&self) -> ::private::PrivateMarker {
::private::PrivateMarker
}
}
}
|
PrivateMarker
|
identifier_name
|
private.rs
|
// This file was borrowed from https://github.com/nikomatsakis/rayon/blob/master/src/private.rs
// and is subject to the license and copyright from that project.
//! The public parts of this private module are used to create traits
//! that cannot be implemented outside of our own crate. This way we
//! can feel free to extend those traits without worrying about it
//! being a breaking change for other implementations.
/// If this type is pub but not publicly reachable, third parties
/// can't name it and can't implement traits using it.
pub struct PrivateMarker;
macro_rules! private_decl {
() => {
/// This trait is private; this method exists to make it
|
}
}
macro_rules! private_impl {
() => {
fn __rayon_private__(&self) -> ::private::PrivateMarker {
::private::PrivateMarker
}
}
}
|
/// impossible to implement outside the crate.
#[doc(hidden)]
fn __rayon_private__(&self) -> ::private::PrivateMarker;
|
random_line_split
|
macros.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.
/// Entry point of thread panic, for details, see std::macros
#[macro_export]
macro_rules! panic {
() => (
panic!("explicit panic")
);
($msg:expr) => ({
static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
::core::panicking::panic(&_MSG_FILE_LINE)
});
($fmt:expr, $($arg:tt)*) => ({
// The leading _'s are to avoid dead code warnings if this is
// used inside a dead function. Just `#[allow(dead_code)]` is
// insufficient, since the user may have
// `#[forbid(dead_code)]` and which cannot be overridden.
static _FILE_LINE: (&'static str, u32) = (file!(), line!());
::core::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
});
}
/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// assert!(true);
///
/// fn some_computation() -> bool { true } // a very simple function
///
/// assert!(some_computation());
///
/// // assert with a custom message
/// let x = true;
/// assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert {
($cond:expr) => (
if!$cond {
panic!(concat!("assertion failed: ", stringify!($cond)))
}
);
($cond:expr, $($arg:tt)+) => (
if!$cond {
panic!($($arg)+)
}
);
}
/// Asserts that two expressions are equal to each other.
///
/// On panic, this macro will print the values of the expressions with their
/// debug representations.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// assert_eq!(a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert_eq {
($left:expr, $right:expr) => ({
match (&($left), &($right)) {
(left_val, right_val) => {
if!(*left_val == *right_val) {
panic!("assertion failed: `(left == right)` \
(left: `{:?}`, right: `{:?}`)", *left_val, *right_val)
}
}
}
})
}
/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Unlike `assert!`, `debug_assert!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// debug_assert!(true);
///
/// fn some_expensive_computation() -> bool { true } // a very simple function
/// debug_assert!(some_expensive_computation());
///
/// // assert with a custom message
/// let x = true;
/// debug_assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert {
($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
}
/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
/// On panic, this macro will print the values of the expressions.
///
/// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert_eq!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// debug_assert_eq!(a, b);
/// ```
#[macro_export]
macro_rules! debug_assert_eq {
($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
}
/// Short circuiting evaluation on Err
///
/// `libstd` contains a more general `try!` macro that uses `From<E>`.
#[macro_export]
macro_rules! try {
|
match $e {
Ok(e) => e,
Err(e) => return Err(e),
}
})
}
/// Use the `format!` syntax to write data into a buffer of type `&mut Write`.
/// See `std::fmt` for more information.
///
/// # Examples
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::io::Write;
///
/// let mut w = Vec::new();
/// write!(&mut w, "test");
/// write!(&mut w, "formatted {}", "arguments");
/// ```
#[macro_export]
macro_rules! write {
($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
}
/// Equivalent to the `write!` macro, except that a newline is appended after
/// the message is written.
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! writeln {
($dst:expr, $fmt:expr) => (
write!($dst, concat!($fmt, "\n"))
);
($dst:expr, $fmt:expr, $($arg:tt)*) => (
write!($dst, concat!($fmt, "\n"), $($arg)*)
);
}
/// A utility macro for indicating unreachable code.
///
/// This is useful any time that the compiler can't determine that some code is unreachable. For
/// example:
///
/// * Match arms with guard conditions.
/// * Loops that dynamically terminate.
/// * Iterators that dynamically terminate.
///
/// # Panics
///
/// This will always panic.
///
/// # Examples
///
/// Match arms:
///
/// ```
/// fn foo(x: Option<i32>) {
/// match x {
/// Some(n) if n >= 0 => println!("Some(Non-negative)"),
/// Some(n) if n < 0 => println!("Some(Negative)"),
/// Some(_) => unreachable!(), // compile error if commented out
/// None => println!("None")
/// }
/// }
/// ```
///
/// Iterators:
///
/// ```
/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
/// for i in 0.. {
/// if 3*i < i { panic!("u32 overflow"); }
/// if x < 3*i { return i-1; }
/// }
/// unreachable!();
/// }
/// ```
#[macro_export]
#[unstable(feature = "core",
reason = "relationship with panic is unclear")]
macro_rules! unreachable {
() => ({
panic!("internal error: entered unreachable code")
});
($msg:expr) => ({
unreachable!("{}", $msg)
});
($fmt:expr, $($arg:tt)*) => ({
panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
});
}
/// A standardised placeholder for marking unfinished code. It panics with the
/// message `"not yet implemented"` when executed.
#[macro_export]
#[unstable(feature = "core",
reason = "relationship with panic is unclear")]
macro_rules! unimplemented {
() => (panic!("not yet implemented"))
}
|
($e:expr) => ({
use $crate::result::Result::{Ok, Err};
|
random_line_split
|
main.rs
|
extern crate dotenv;
extern crate ctrlc;
extern crate chrono;
extern crate chrono_tz;
extern crate url;
extern crate linkify;
#[macro_use]
extern crate html5ever;
extern crate reqwest;
#[macro_use]
extern crate slog;
extern crate slog_async;
extern crate slog_envlogger;
extern crate slog_scope;
extern crate slog_stdlog;
extern crate slog_term;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate serenity;
#[macro_use]
extern crate error_chain;
mod preview;
mod bot;
mod hacker_news;
mod util;
mod errors {
error_chain! {
foreign_links {
Serenity(::serenity::Error);
Reqwest(::reqwest::Error);
}
links {
HackerNews(::hacker_news::Error, ::hacker_news::ErrorKind);
}
}
}
use std::env;
use slog::Drain;
use bot::Bot;
fn main() {
dotenv::dotenv().ok();
let decorator = slog_term::TermDecorator::new().stderr().build();
let formatter = slog_term::CompactFormat::new(decorator).build().fuse();
let logger = slog_envlogger::new(formatter);
let drain = slog_async::Async::default(logger);
let root_logger = slog::Logger::root(
drain.fuse(),
o!(
"version" => env!("CARGO_PKG_VERSION"),
// NOTE
// Uncomment this to get SLOC location
// "place" => slog::FnValue(move |info| {
// format!("{}:{}", info.file(), info.line())
// })
),
);
let _global_logger_guard =
slog_stdlog::init().expect("Couldn't initialize global slog-stdlog logger.");
slog_scope::scope(&root_logger, || {
// Create client.
let token = env::var("DISCORD_TOKEN").expect("token");
let mut bot = Bot::new(root_logger.new(o!("scope" => "Bot")));
bot.push_previewer(hacker_news::HackerNews);
let mut client = bot::new_client(&token, bot);
// Listen for signal.
let closer = client.close_handle();
let ctrlc_logger = root_logger.clone();
ctrlc::set_handler(move || {
info!(ctrlc_logger, "Received termination signal. Terminating.");
closer.close();
}).expect("Error setting handler.");
// Start client.
if let Err(e) = client.start_autosharded() {
match e {
serenity::Error::Client(serenity::client::ClientError::Shutdown) =>
|
_ => error!(root_logger, "Problem with starting the client."; "error" => e.to_string()),
}
}
});
}
|
{
info!(root_logger, "Shutting down.")
}
|
conditional_block
|
main.rs
|
extern crate dotenv;
extern crate ctrlc;
extern crate chrono;
extern crate chrono_tz;
extern crate url;
extern crate linkify;
#[macro_use]
extern crate html5ever;
extern crate reqwest;
#[macro_use]
extern crate slog;
extern crate slog_async;
extern crate slog_envlogger;
extern crate slog_scope;
extern crate slog_stdlog;
extern crate slog_term;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate serenity;
#[macro_use]
extern crate error_chain;
mod preview;
mod bot;
mod hacker_news;
mod util;
mod errors {
error_chain! {
foreign_links {
Serenity(::serenity::Error);
Reqwest(::reqwest::Error);
}
links {
HackerNews(::hacker_news::Error, ::hacker_news::ErrorKind);
}
}
}
use std::env;
use slog::Drain;
use bot::Bot;
fn
|
() {
dotenv::dotenv().ok();
let decorator = slog_term::TermDecorator::new().stderr().build();
let formatter = slog_term::CompactFormat::new(decorator).build().fuse();
let logger = slog_envlogger::new(formatter);
let drain = slog_async::Async::default(logger);
let root_logger = slog::Logger::root(
drain.fuse(),
o!(
"version" => env!("CARGO_PKG_VERSION"),
// NOTE
// Uncomment this to get SLOC location
// "place" => slog::FnValue(move |info| {
// format!("{}:{}", info.file(), info.line())
// })
),
);
let _global_logger_guard =
slog_stdlog::init().expect("Couldn't initialize global slog-stdlog logger.");
slog_scope::scope(&root_logger, || {
// Create client.
let token = env::var("DISCORD_TOKEN").expect("token");
let mut bot = Bot::new(root_logger.new(o!("scope" => "Bot")));
bot.push_previewer(hacker_news::HackerNews);
let mut client = bot::new_client(&token, bot);
// Listen for signal.
let closer = client.close_handle();
let ctrlc_logger = root_logger.clone();
ctrlc::set_handler(move || {
info!(ctrlc_logger, "Received termination signal. Terminating.");
closer.close();
}).expect("Error setting handler.");
// Start client.
if let Err(e) = client.start_autosharded() {
match e {
serenity::Error::Client(serenity::client::ClientError::Shutdown) => {
info!(root_logger, "Shutting down.")
}
_ => error!(root_logger, "Problem with starting the client."; "error" => e.to_string()),
}
}
});
}
|
main
|
identifier_name
|
main.rs
|
extern crate dotenv;
extern crate ctrlc;
extern crate chrono;
extern crate chrono_tz;
extern crate url;
extern crate linkify;
#[macro_use]
extern crate html5ever;
extern crate reqwest;
#[macro_use]
extern crate slog;
extern crate slog_async;
extern crate slog_envlogger;
extern crate slog_scope;
extern crate slog_stdlog;
extern crate slog_term;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate serenity;
#[macro_use]
extern crate error_chain;
mod preview;
mod bot;
mod hacker_news;
mod util;
mod errors {
error_chain! {
foreign_links {
Serenity(::serenity::Error);
Reqwest(::reqwest::Error);
}
links {
HackerNews(::hacker_news::Error, ::hacker_news::ErrorKind);
}
}
}
use std::env;
use slog::Drain;
use bot::Bot;
fn main() {
dotenv::dotenv().ok();
let decorator = slog_term::TermDecorator::new().stderr().build();
let formatter = slog_term::CompactFormat::new(decorator).build().fuse();
let logger = slog_envlogger::new(formatter);
let drain = slog_async::Async::default(logger);
let root_logger = slog::Logger::root(
drain.fuse(),
o!(
"version" => env!("CARGO_PKG_VERSION"),
// NOTE
// Uncomment this to get SLOC location
// "place" => slog::FnValue(move |info| {
// format!("{}:{}", info.file(), info.line())
// })
),
);
let _global_logger_guard =
slog_stdlog::init().expect("Couldn't initialize global slog-stdlog logger.");
slog_scope::scope(&root_logger, || {
// Create client.
let token = env::var("DISCORD_TOKEN").expect("token");
let mut bot = Bot::new(root_logger.new(o!("scope" => "Bot")));
bot.push_previewer(hacker_news::HackerNews);
let mut client = bot::new_client(&token, bot);
// Listen for signal.
let closer = client.close_handle();
let ctrlc_logger = root_logger.clone();
ctrlc::set_handler(move || {
info!(ctrlc_logger, "Received termination signal. Terminating.");
closer.close();
}).expect("Error setting handler.");
|
serenity::Error::Client(serenity::client::ClientError::Shutdown) => {
info!(root_logger, "Shutting down.")
}
_ => error!(root_logger, "Problem with starting the client."; "error" => e.to_string()),
}
}
});
}
|
// Start client.
if let Err(e) = client.start_autosharded() {
match e {
|
random_line_split
|
main.rs
|
extern crate dotenv;
extern crate ctrlc;
extern crate chrono;
extern crate chrono_tz;
extern crate url;
extern crate linkify;
#[macro_use]
extern crate html5ever;
extern crate reqwest;
#[macro_use]
extern crate slog;
extern crate slog_async;
extern crate slog_envlogger;
extern crate slog_scope;
extern crate slog_stdlog;
extern crate slog_term;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate serenity;
#[macro_use]
extern crate error_chain;
mod preview;
mod bot;
mod hacker_news;
mod util;
mod errors {
error_chain! {
foreign_links {
Serenity(::serenity::Error);
Reqwest(::reqwest::Error);
}
links {
HackerNews(::hacker_news::Error, ::hacker_news::ErrorKind);
}
}
}
use std::env;
use slog::Drain;
use bot::Bot;
fn main()
|
let _global_logger_guard =
slog_stdlog::init().expect("Couldn't initialize global slog-stdlog logger.");
slog_scope::scope(&root_logger, || {
// Create client.
let token = env::var("DISCORD_TOKEN").expect("token");
let mut bot = Bot::new(root_logger.new(o!("scope" => "Bot")));
bot.push_previewer(hacker_news::HackerNews);
let mut client = bot::new_client(&token, bot);
// Listen for signal.
let closer = client.close_handle();
let ctrlc_logger = root_logger.clone();
ctrlc::set_handler(move || {
info!(ctrlc_logger, "Received termination signal. Terminating.");
closer.close();
}).expect("Error setting handler.");
// Start client.
if let Err(e) = client.start_autosharded() {
match e {
serenity::Error::Client(serenity::client::ClientError::Shutdown) => {
info!(root_logger, "Shutting down.")
}
_ => error!(root_logger, "Problem with starting the client."; "error" => e.to_string()),
}
}
});
}
|
{
dotenv::dotenv().ok();
let decorator = slog_term::TermDecorator::new().stderr().build();
let formatter = slog_term::CompactFormat::new(decorator).build().fuse();
let logger = slog_envlogger::new(formatter);
let drain = slog_async::Async::default(logger);
let root_logger = slog::Logger::root(
drain.fuse(),
o!(
"version" => env!("CARGO_PKG_VERSION"),
// NOTE
// Uncomment this to get SLOC location
// "place" => slog::FnValue(move |info| {
// format!("{}:{}", info.file(), info.line())
// })
),
);
|
identifier_body
|
day_4.rs
|
use std::iter::Peekable;
use std::str::Chars;
#[derive(PartialEq)]
enum SymbolGroup {
AlphaNumeric,
WhiteSpace,
Else
}
pub struct Lexer<'a> {
iter: Peekable<Chars<'a>>
}
impl <'a> Lexer<'a> {
pub fn new(line: &'a str) -> Lexer {
Lexer { iter: line.chars().peekable() }
}
pub fn next_lexem(&mut self) -> Option<String> {
let mut value = vec![];
let expected = self.define_symbol_group();
if expected == SymbolGroup::Else {
return None;
}
loop {
let actual = self.define_symbol_group();
let symbol = self.peek_next_symbol();
if expected == actual {
self.iter.next();
value.push(symbol.unwrap());
}
else {
break;
}
}
Some(value.iter().cloned().collect::<String>())
}
fn define_symbol_group(&mut self) -> SymbolGroup {
match self.peek_next_symbol() {
Some('a'...'z') | Some('A'...'Z') |
Some('_') | Some('0'...'9') => SymbolGroup::AlphaNumeric,
Some(' ') => SymbolGroup::WhiteSpace,
Some(_) | None => SymbolGroup::Else,
}
}
fn
|
(&mut self) -> Option<char> {
self.iter.peek().cloned()
}
}
|
peek_next_symbol
|
identifier_name
|
day_4.rs
|
use std::iter::Peekable;
use std::str::Chars;
#[derive(PartialEq)]
enum SymbolGroup {
AlphaNumeric,
WhiteSpace,
Else
}
pub struct Lexer<'a> {
iter: Peekable<Chars<'a>>
}
impl <'a> Lexer<'a> {
|
pub fn next_lexem(&mut self) -> Option<String> {
let mut value = vec![];
let expected = self.define_symbol_group();
if expected == SymbolGroup::Else {
return None;
}
loop {
let actual = self.define_symbol_group();
let symbol = self.peek_next_symbol();
if expected == actual {
self.iter.next();
value.push(symbol.unwrap());
}
else {
break;
}
}
Some(value.iter().cloned().collect::<String>())
}
fn define_symbol_group(&mut self) -> SymbolGroup {
match self.peek_next_symbol() {
Some('a'...'z') | Some('A'...'Z') |
Some('_') | Some('0'...'9') => SymbolGroup::AlphaNumeric,
Some(' ') => SymbolGroup::WhiteSpace,
Some(_) | None => SymbolGroup::Else,
}
}
fn peek_next_symbol(&mut self) -> Option<char> {
self.iter.peek().cloned()
}
}
|
pub fn new(line: &'a str) -> Lexer {
Lexer { iter: line.chars().peekable() }
}
|
random_line_split
|
day_4.rs
|
use std::iter::Peekable;
use std::str::Chars;
#[derive(PartialEq)]
enum SymbolGroup {
AlphaNumeric,
WhiteSpace,
Else
}
pub struct Lexer<'a> {
iter: Peekable<Chars<'a>>
}
impl <'a> Lexer<'a> {
pub fn new(line: &'a str) -> Lexer {
Lexer { iter: line.chars().peekable() }
}
pub fn next_lexem(&mut self) -> Option<String> {
let mut value = vec![];
let expected = self.define_symbol_group();
if expected == SymbolGroup::Else {
return None;
}
loop {
let actual = self.define_symbol_group();
let symbol = self.peek_next_symbol();
if expected == actual {
self.iter.next();
value.push(symbol.unwrap());
}
else {
break;
}
}
Some(value.iter().cloned().collect::<String>())
}
fn define_symbol_group(&mut self) -> SymbolGroup
|
fn peek_next_symbol(&mut self) -> Option<char> {
self.iter.peek().cloned()
}
}
|
{
match self.peek_next_symbol() {
Some('a' ...'z') | Some('A'...'Z') |
Some('_') | Some('0'...'9') => SymbolGroup::AlphaNumeric,
Some(' ') => SymbolGroup::WhiteSpace,
Some(_) | None => SymbolGroup::Else,
}
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.