Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add Automorphic number in Rust | // In mathematics an automorphic number (sometimes referred to as a circular number)
// is a number whose square "ends" in the same digits as the number itself.
fn list_automorphic_numbers(start: i32, end: i32) {
(start..end)
.filter(|&n| is_automorphic(n as i128))
.for_each(|n| println!("{}\t=>\t{}", n, n.pow(2)))
}
fn is_automorphic(n: i128) -> bool {
let n_str = n.to_string();
let sq_str = n.pow(2).to_string();
n_str == sq_str[(sq_str.len() - n_str.len())..]
}
fn main() {
list_automorphic_numbers(1, 10000)
}
#[test]
fn simple_test() {
assert!(is_automorphic(5));
assert!(is_automorphic(6));
assert!(is_automorphic(76));
assert!(is_automorphic(376));
assert!(is_automorphic(890625));
}
| |
Add test against possible undefined behavior | #![cfg(feature = "std")]
extern crate rand;
extern crate libc;
use rand::{FromEntropy, SmallRng};
use rand::distributions::{Distribution, Bernoulli};
#[link_name = "m"]
extern "C" {
fn nextafter(x: f64, y: f64) -> f64;
}
/// This test should make sure that we don't accidentally have undefined
/// behavior for large propabilties due to
/// https://github.com/rust-lang/rust/issues/10184.
#[test]
fn large_probability() {
let p = unsafe { nextafter(1., 0.) };
assert!(p < 1.);
let d = Bernoulli::new(p);
let mut rng = SmallRng::from_entropy();
for _ in 0..10 {
assert!(d.sample(&mut rng));
}
}
| |
Add solution to problem 53 | #![feature(core)]
#[macro_use] extern crate libeuler;
use std::collections::HashMap;
use std::iter::range_inclusive;
/// There are exactly ten ways of selecting three from five, 12345:
///
/// 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
///
/// In combinatorics, we use the notation, 5C3 = 10.
///
/// In general,
/// nCr = n! / (r!(n−r)!)
///
/// where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
///
/// It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
///
/// How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than
/// one-million?
fn main() {
solutions! {
inputs: (min_val: i64 = 1_000_000)
sol naive {
let mut mem = HashMap::new();
range_inclusive(1, 100).map(|n| {
range_inclusive(0, n).map(|r| {
match ncr(&mut mem, n, r) {
Num::TooBig => 1,
Num::N(a) if a > min_val => 1,
_ => 0
}
}).sum::<i64>()
}).sum::<i64>()
}
}
}
#[derive(Debug, Copy, Clone)]
enum Num {
TooBig,
N(i64)
}
fn ncr(memo: &mut HashMap<(i64, i64), Num>, n: i64, r: i64) -> Num {
use Num::*;
if memo.contains_key(&(n, r)) {
return memo[&(n, r)];
}
let proto_ret = match (n, r) {
(_, 0) => N(1),
(n, r) if n == r => N(1),
(n, r) => match (ncr(memo, n-1, r-1), ncr(memo, n-1, r)) {
(TooBig, _) => TooBig,
(_, TooBig) => TooBig,
(N(a), N(b)) => N(a + b)
}
};
let ret = match proto_ret {
N(a) if a > 1_000_000_000 => TooBig,
a => a
};
memo.insert((n,r), ret);
ret
}
| |
Add test of impl formatting | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(optin_builtin_traits)]
pub trait AnOibit {}
impl AnOibit for .. {}
pub struct Foo<T> { field: T }
// @has impl_parts/struct.Foo.html '//*[@class="impl"]//code' \
// "impl<T: Clone> !AnOibit for Foo<T> where T: Sync"
// @has impl_parts/trait.AnOibit.html '//*[@class="item-list"]//code' \
// "impl<T: Clone> !AnOibit for Foo<T> where T: Sync"
impl<T: Clone> !AnOibit for Foo<T> where T: Sync {}
| |
Add rust code for clock case | #[derive(Debug, PartialEq)]
pub struct Clock {
hour: i32,
minute: i32,
}
impl Clock {
#[inline]
fn normalize(hour: i32, minute: i32) -> (i32, i32) {
const HOURS: i32 = 24;
const MINUTES: i32 = 60;
let mut c = 0;
let mut m = minute % MINUTES;
if m < 0 {
m += 60;
c = -1;
}
let mut h = (c + minute / MINUTES + hour) % HOURS;
if h < 0 {
h += 24;
}
(h, m)
}
pub fn new(hour: i32, minute: i32) -> Clock {
let (h, m) = Clock::normalize(hour, minute);
Clock { hour: h, minute: m }
}
pub fn add_minutes(&self, minutes: i32) -> Clock {
let (h, m) = Clock::normalize(self.hour, self.minute + minutes);
Clock { hour: h, minute: m }
}
}
impl ToString for Clock {
fn to_string(&self) -> String {
format!("{:02}:{:02}", self.hour, self.minute)
}
}
| |
Test case for new `derive(PartialOrd)` expansion. | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue 15523: derive(PartialOrd) should use the provided
// discriminant values for the derived ordering.
#[derive(PartialEq, PartialOrd)]
enum E1 {
Pos2 = 2,
Neg1 = -1,
Pos1 = 1,
}
#[derive(PartialEq, PartialOrd)]
#[repr(u8)]
enum E2 {
Pos2 = 2,
PosMax = !0 as u8,
Pos1 = 1,
}
#[derive(PartialEq, PartialOrd)]
#[repr(i8)]
enum E3 {
Pos2 = 2,
Neg1 = -1_i8,
Pos1 = 1,
}
fn main() {
assert!(E1::Pos2 > E1::Pos1);
assert!(E1::Pos1 > E1::Neg1);
assert!(E1::Pos2 > E1::Neg1);
assert!(E2::Pos2 > E2::Pos1);
assert!(E2::Pos1 < E2::PosMax);
assert!(E2::Pos2 < E2::PosMax);
assert!(E3::Pos2 > E3::Pos1);
assert!(E3::Pos1 > E3::Neg1);
assert!(E3::Pos2 > E3::Neg1);
}
| |
Add rust code for rna-transcription | #[derive(Debug, PartialEq)]
pub struct RibonucleicAcid(String);
impl RibonucleicAcid {
pub fn new(serial: &str) -> RibonucleicAcid {
RibonucleicAcid(serial.to_string())
}
}
#[derive(Debug, PartialEq)]
pub struct DeoxyribonucleicAcid(String);
impl DeoxyribonucleicAcid {
pub fn new(serial: &str) -> DeoxyribonucleicAcid {
DeoxyribonucleicAcid(serial.to_string())
}
pub fn to_rna(&self) -> Result<RibonucleicAcid, String> {
let rna = self.0
.chars()
.filter_map(|c| match c {
'A' => Some('U'),
'C' => Some('G'),
'G' => Some('C'),
'T' => Some('A'),
_ => None,
})
.collect::<String>();
if rna.len() != self.0.len() {
return Err("Invalid DNA serial".to_string());
}
Ok(RibonucleicAcid(rna))
}
}
| |
Test that all structs are actually empty | extern crate llvm_safe;
use std::mem;
use llvm_safe::llvm::{BasicBlock, Label, Builder, PositionedBuilder, Constant, Context, Function, FunctionLabel, Module, Phi, Target, TargetMachine, Type, Value};
#[test]
fn test_all_empty() {
assert_eq!(mem::size_of::<BasicBlock<'static, 'static, 'static>>(), 0);
assert_eq!(mem::size_of::<Label<'static>>(), 0);
assert_eq!(mem::size_of::<Builder<'static, 'static>>(), 0);
assert_eq!(mem::size_of::<PositionedBuilder<'static, 'static, 'static, 'static, 'static>>(), 0);
assert_eq!(mem::size_of::<Constant<'static>>(), 0);
assert_eq!(mem::size_of::<Context<'static>>(), 0);
assert_eq!(mem::size_of::<Function<'static, 'static>>(), 0);
assert_eq!(mem::size_of::<FunctionLabel<'static, 'static>>(), 0);
assert_eq!(mem::size_of::<Module<'static, 'static, 'static>>(), 0);
assert_eq!(mem::size_of::<Phi<'static, 'static, 'static>>(), 0);
assert_eq!(mem::size_of::<Target>(), 0);
assert_eq!(mem::size_of::<TargetMachine>(), 0);
assert_eq!(mem::size_of::<Type<'static>>(), 0);
assert_eq!(mem::size_of::<Value<'static, 'static, 'static>>(), 0);
assert_eq!(mem::align_of::<BasicBlock<'static, 'static, 'static>>(), 1);
assert_eq!(mem::align_of::<Label<'static>>(), 1);
assert_eq!(mem::align_of::<Builder<'static, 'static>>(), 1);
assert_eq!(mem::align_of::<PositionedBuilder<'static, 'static, 'static, 'static, 'static>>(), 1);
assert_eq!(mem::align_of::<Constant<'static>>(), 1);
assert_eq!(mem::align_of::<Context<'static>>(), 1);
assert_eq!(mem::align_of::<Function<'static, 'static>>(), 1);
assert_eq!(mem::align_of::<FunctionLabel<'static, 'static>>(), 1);
assert_eq!(mem::align_of::<Module<'static, 'static, 'static>>(), 1);
assert_eq!(mem::align_of::<Phi<'static, 'static, 'static>>(), 1);
assert_eq!(mem::align_of::<Target>(), 1);
assert_eq!(mem::align_of::<TargetMachine>(), 1);
assert_eq!(mem::align_of::<Type<'static>>(), 1);
assert_eq!(mem::align_of::<Value<'static, 'static, 'static>>(), 1);
}
| |
Add test for sidebar link generation | // 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.
#![crate_name = "foo"]
// @has foo/struct.SomeStruct.html '//*[@class="sidebar-links"]/a[@href="#method.some_fn-1"]' \
// "some_fn"
pub struct SomeStruct<T> { _inner: T }
impl SomeStruct<()> {
pub fn some_fn(&self) {}
}
impl SomeStruct<usize> {
pub fn some_fn(&self) {}
}
| |
Fix botched error message in compile-fail test | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct yes0<'self> {
x: &uint, //~ ERROR Illegal anonymous lifetime: anonymous lifetimes are not permitted here
}
struct yes1<'self> {
x: &'self uint,
}
struct yes2<'self> {
x: &'foo uint, //~ ERROR Illegal lifetime 'foo: this lifetime must be declared
}
fn main() {}
| // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct yes0<'self> {
x: &uint, //~ ERROR Illegal anonymous lifetime: anonymous lifetimes are not permitted here
}
struct yes1<'self> {
x: &'self uint,
}
struct yes2<'self> {
x: &'foo uint, //~ ERROR Illegal lifetime 'foo: only 'self is allowed
}
fn main() {}
|
Add example for embedded named R function call. | extern crate libc;
extern crate libr;
use libc::c_int;
use std::ptr;
use std::env;
use std::ffi::{CStr, CString};
use libr::ffi::internals::*;
use libr::ffi::embedded::{self, Rf_endEmbeddedR, Rf_initEmbeddedR};
unsafe fn source(path: *const ::libc::c_char) {
let mut e: SEXP = Rf_lang2(Rf_install(CString::new("source").unwrap().into_raw()),
Rf_mkString(path));
Rf_protect(e);
R_tryEval(e, R_GlobalEnv, ptr::null_mut::<libc::c_int>());
Rf_unprotect(1);
}
fn main() {
if let Err(_) = env::var("R_HOME") {
panic!("Rembedded test need R_HOME be setted");
}
let mut s = Box::new(vec![CString::new("R").unwrap().into_raw(),
CString::new("--quiet").unwrap().into_raw(),
CString::new("--no-save").unwrap().into_raw()]);
unsafe {
embedded::Rf_initEmbeddedR(s.len() as i32, s.as_mut_ptr());
source(CString::new("foo.R").unwrap().into_raw());
embedded::Rf_endEmbeddedR(0);
}
}
| |
Test that associated types are not required as type parameters | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {
type T;
}
// should be able to use a trait with an associated type without specifying it as an argument
trait Bar<F: Foo> {
fn bar(foo: &F);
}
pub fn main() {
}
| |
Use an array to label all commands and add `ptr_write` command | use std::{io, fs};
macro_rules! readln {
() => {
{
let mut line = String::new();
match io::stdin().read_line(&mut line) {
Ok(n) => Some(line.trim().to_string()),
Err(e) => None
}
}
};
}
fn console_title(title: &str){
}
#[no_mangle]
pub fn main() {
console_title("Test");
println!("Type help for a command list");
while let Some(line) = readln!() {
let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect();
if let Some(command) = args.get(0) {
println!("# {}", line);
match &command[..]
{
"panic" => panic!("Test panic"),
"ls" => {
// TODO: when libredox is completed
//fs::read_dir("/").unwrap().map(|dir| println!("{}", dir));
}
_ => println!("Commands: panic"),
}
}
}
}
| #![feature(alloc)]
#![feature(core)]
extern crate alloc;
extern crate core;
use alloc::boxed::Box;
use std::{io, fs, rand};
use core::ptr;
macro_rules! readln {
() => {
{
let mut line = String::new();
match io::stdin().read_line(&mut line) {
Ok(n) => Some(line.trim().to_string()),
Err(e) => None
}
}
};
}
fn console_title(title: &str){
}
#[no_mangle]
pub fn main() {
console_title("Test");
println!("Type help for a command list");
while let Some(line) = readln!() {
let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect();
if let Some(command) = args.get(0) {
println!("# {}", line);
let console_commands = ["panic", "ls", "ptr_write"];
match &command[..]
{
command if command == console_commands[0] => panic!("Test panic"),
command if command == console_commands[1] => {
// TODO: import std::fs functions into libredox
//fs::read_dir("/").unwrap().map(|dir| println!("{}", dir));
}
command if command == console_commands[2] => {
let a_ptr = rand() as *mut u8;
// TODO: import Box::{from_raw, to_raw} methods in libredox
//let mut a_box = Box::new(rand() as u8);
unsafe {
ptr::write(a_ptr, rand() as u8);
//ptr::write(a_box.to_raw(), rand() as u8);
}
}
_ => println!("Commands: {}", console_commands.join(" ")),
}
}
}
}
|
Create an example for recursive Levenshtein | extern crate code;
use code::levenshtein;
fn main() {
let u = "kangaroo";
let v = "koala";
let distance = levenshtein::recursive(u, v);
println!("distance between \"{}\" and \"{}\" is {}", u, v, distance);
}
| |
Add a test to check that marshalled references cannot escape | extern crate embed_lang;
use embed_lang::new_vm;
use embed_lang::vm::vm::Value;
use embed_lang::vm::api::{VMType, Getable};
use embed_lang::vm::gc::Traverseable;
use std::cell::Cell;
struct Test<'vm>(Cell<&'vm str>);
impl<'vm> Traverseable for Test<'vm> { }
impl<'vm> VMType for Test<'vm> {
type Type = Test<'static>;
}
fn f<'vm>(test: &'vm Test<'vm>, s: &'vm str) {
test.0.set(s);
}
fn main() {
let vm = new_vm();
vm.define_global("f", f as fn (_, _));
//~^ Error `vm` does not live long enough
}
| |
Create a example PPM program | extern crate scratchapixel;
use std::fs::File;
use scratchapixel::ppm::rgb::RGB;
use scratchapixel::ppm::format::PPM;
fn main() {
let white = RGB { r: 255, g: 255, b: 255 };
let black = RGB { r: 0, g: 0, b: 0 };
let red = RGB { r: 255, g: 0, b: 0 };
let mut image: PPM = PPM::new(64, 64);
for y in 0..64 {
let parity_y = (y / 8) % 2;
for x in 0..64 {
let parity_x = (x / 8) % 2;
let color = match (parity_y + parity_x) % 2 {
0 => black,
1 => white,
_ => red
};
image.set_pixel(x, y, color);
}
}
match File::create("resources/example.use_ppm.ppm") {
Ok(file) => {
match image.write_file(file) {
Ok(_) => println!("wrote file"),
Err(_) => println!("could not write file")
}
}
Err(_) => println!("could not create file")
}
}
| |
Add another test for ! | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(never_type)]
trait StringifyType {
fn stringify_type() -> &'static str;
}
impl StringifyType for ! {
fn stringify_type() -> &'static str {
"!"
}
}
fn maybe_stringify<T: StringifyType>(opt: Option<T>) -> &'static str {
match opt {
Some(_) => T::stringify_type(),
None => "none",
}
}
fn main() {
println!("! is {}", <!>::stringify_type());
println!("None is {}", maybe_stringify(None::<!>));
}
| |
Add a regression test for FromIterator of OscArray | extern crate rosc;
use rosc::{OscArray, OscType};
#[test]
fn test_osc_array_from_iter() {
use std::iter::FromIterator;
let iter = (0..3).map(|i| OscType::Int(i));
let osc_arr = OscArray::from_iter(iter);
assert_eq!(
osc_arr,
OscArray {
content: vec![OscType::Int(0), OscType::Int(1), OscType::Int(2)]
}
);
}
| |
Add 7 segment display example | #![no_std]
extern crate tock;
const DATA_PIN: u32 = 0;
const CLOCK_PIN: u32 = 1;
const LATCH_PIN: u32 = 2;
const SPEED: u32 = 2;
use tock::{led, timer};
fn push_one_bit(value: bool) {
if value {
led::on(DATA_PIN)
} else {
led::off(DATA_PIN)
}
led::on(CLOCK_PIN);
timer::delay_ms(SPEED);
led::off(CLOCK_PIN);
timer::delay_ms(SPEED);
}
fn push_bits(values: &[bool]) {
for i in values {
push_one_bit(*i);
}
display();
timer::delay_ms(200);
}
fn display() {
led::on(LATCH_PIN);
timer::delay_ms(SPEED);
led::off(LATCH_PIN);
}
fn number_to_bits(n: u8) -> [bool; 8] {
match n {
1 => [true, true, true, false, true, false, true, true],
2 => [false, true, false, false, true, true, false, false],
3 => [false, true, false, false, true, false, false, true],
4 => [false, false, true, false, true, false, true, true],
5 => [false, false, false, true, true, false, false, true],
6 => [false, false, false, true, true, false, false, false],
7 => [true, true, false, false, true, false, true, true],
8 => [false, false, false, false, true, false, false, false],
9 => [false, false, false, false, true, false, false, true],
0 => [true, false, false, false, true, false, false, false],
_ => [true, true, true, true, false, true, true, true],
}
}
fn main() {
let mut i = 0;
loop {
i = (i + 1) % 11;
push_bits(&number_to_bits(i));
}
}
| |
Add a regression test for the const eval type resolution | // Copyright 2017 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.
trait Nat {
const VALUE: usize;
}
struct Zero;
struct Succ<N>(N);
impl Nat for Zero {
const VALUE: usize = 0;
}
impl<N: Nat> Nat for Succ<N> {
const VALUE: usize = N::VALUE + 1;
}
fn main() {
let x: [i32; <Succ<Succ<Succ<Succ<Zero>>>>>::VALUE] = [1, 2, 3, 4];
}
| |
Add the AST (missing file). | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub type Program = Vec<Item>;
pub enum Item {
Statement(Stmt),
Fn(Function)
}
pub type Block = Vec<Stmt>;
pub struct JavaTy {
pub name: String,
pub generics: Vec<JavaTy>
}
pub struct Function {
pub name: String,
pub params: Vec<String>,
pub body: Block
}
pub enum Stmt {
Par(Vec<Block>),
Space(Vec<Block>),
Let(LetDecl),
LetInStore(LetInStoreDecl),
When(EntailmentRel, Block),
Pause,
Trap(String, Block),
Exit(String),
Loop(Block),
FnCall(String, Vec<String>),
Tell(Var, Expr)
}
pub struct LetDecl {
pub transient: bool,
pub var: String,
pub var_ty: Option<JavaTy>,
pub spacetime: Spacetime,
pub expr: Expr
}
pub struct LetInStoreDecl {
pub location: String,
pub loc_ty: Option<JavaTy>,
pub store: String,
pub expr: Expr
}
pub struct EntailmentRel {
pub left: StreamVar,
pub right: Expr
}
pub struct Var {
pub name: String,
pub args: Vec<Var>
}
pub struct StreamVar {
pub name: String,
pub past: usize,
pub args: Vec<StreamVar>
}
pub enum Spacetime {
SingleSpace,
SingleTime,
WorldLine,
Location(String)
}
pub enum Expr {
JavaNew(JavaTy, Vec<Expr>),
JavaObjectCall(String, Vec<JavaCall>),
Number(u64),
StringLiteral(String),
Variable(StreamVar)
}
pub struct JavaCall {
pub property: String, // can be an attribute or a method.
pub args: Vec<Expr>
}
| |
Implement a trait that get an HTTP response given an URL and headers | use hyper::client::Client;
use hyper::client::response::Response;
use hyper::error::Error;
use hyper::header::Headers;
use hyper::method::Method;
/// Trait that represents some methods to send a specific request
pub trait GetResponse {
/// Given a specific URL, get the response from the target server
fn get_http_response(url: &str) -> Result<Response, Error>;
/// Given a specific URL and an header, get the response from the target server
fn get_http_response_using_headers(url: &str, header: Headers) -> Result<Response, Error>;
}
impl GetResponse for Client {
fn get_http_response(url: &str) -> Result<Response, Error> {
Client::new().request(Method::Get, url).send()
}
fn get_http_response_using_headers(url: &str,
custom_header: Headers)
-> Result<Response, Error> {
Client::new().request(Method::Get, url).headers(custom_header).send()
}
} | |
Add example for merge requests |
extern crate gitlab_api as gitlab;
use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
use gitlab::GitLab;
use gitlab::merge_requests;
fn main() {
env_logger::init().unwrap();
info!("starting up");
let hostname = match env::var("GITLAB_HOSTNAME") {
Ok(val) => val,
Err(_) => {
let default = String::from("gitlab.com");
println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.",
default);
default
}
};
let token = match env::var("GITLAB_TOKEN") {
Ok(val) => val,
Err(_) => {
panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \
http://{}/profile/account",
hostname);
}
};
let gl = GitLab::new_https(&hostname, &token);
let merge_request = gl.merge_request(merge_requests::single::Listing::new(142, 418)).unwrap();
println!("merge_request: {:?}", merge_request);
let merge_requests = gl.merge_requests(merge_requests::Listing::new(142)).unwrap();
println!("merge_requests: {:?}", merge_requests);
}
| |
Add tests for null pointer opt. | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::gc::Gc;
use std::mem::size_of;
trait Trait {}
fn main() {
// Closures - || / proc()
assert_eq!(size_of::<proc()>(), size_of::<Option<proc()>>());
assert_eq!(size_of::<||>(), size_of::<Option<||>>());
// Functions
assert_eq!(size_of::<fn(int)>(), size_of::<Option<fn(int)>>());
assert_eq!(size_of::<extern "C" fn(int)>(), size_of::<Option<extern "C" fn(int)>>());
// Slices - &str / &[T] / &mut [T]
assert_eq!(size_of::<&str>(), size_of::<Option<&str>>());
assert_eq!(size_of::<&[int]>(), size_of::<Option<&[int]>>());
assert_eq!(size_of::<&mut [int]>(), size_of::<Option<&mut [int]>>());
// Traits - Box<Trait> / &Trait / &mut Trait
assert_eq!(size_of::<Box<Trait>>(), size_of::<Option<Box<Trait>>>());
assert_eq!(size_of::<&Trait>(), size_of::<Option<&Trait>>());
assert_eq!(size_of::<&mut Trait>(), size_of::<Option<&mut Trait>>());
// Pointers - Box<T> / Gc<T>
assert_eq!(size_of::<Box<int>>(), size_of::<Option<Box<int>>>());
assert_eq!(size_of::<Gc<int>>(), size_of::<Option<Gc<int>>>());
}
| |
Update i686-linux-android features to match android ABI. | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::Target;
pub fn target() -> Target {
let mut base = super::android_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = 64;
Target {
llvm_target: "i686-linux-android".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "android".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
options: base,
}
}
| // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::Target;
pub fn target() -> Target {
let mut base = super::android_base::opts();
base.max_atomic_width = 64;
// http://developer.android.com/ndk/guides/abis.html#x86
base.cpu = "pentiumpro".to_string();
base.features = "+mmx,+sse,+sse2,+sse3,+ssse3".to_string();
Target {
llvm_target: "i686-linux-android".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "android".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
options: base,
}
}
|
Add a test for vstore, which already works | // 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.
enum E { V1(int), V0 }
const C: &static/[E] = &[V0, V1(0xDEADBEE), V0];
fn main() {
match C[1] {
V1(n) => assert(n == 0xDEADBEE),
_ => die!()
}
match C[2] {
V0 => (),
_ => die!()
}
}
| |
Add a test case for linearize_ty_params() and shapes | // xfail-test
// Tests that shapes respect linearize_ty_params().
tag option<T> {
none;
some(T);
}
type smallintmap<T> = @{mutable v: [mutable option<T>]};
fn mk<@T>() -> smallintmap<T> {
let v: [mutable option<T>] = [mutable];
ret @{mutable v: v};
}
fn f<@T,@U>() {
let sim = mk::<U>();
log_err sim;
}
fn main() {
f::<int,int>();
}
| |
Add example for storing file feature | extern crate fruently;
use std::env;
use fruently::fluent::Fluent;
use fruently::retry_conf::RetryConf;
use std::collections::HashMap;
use fruently::forwardable::MsgpackForwardable;
fn main() {
let home = env::home_dir().unwrap();
let file = home.join("buffer");
let conf = RetryConf::new().store_file(file.clone()).max(5).multiplier(2_f64);
let mut obj: HashMap<String, String> = HashMap::new();
obj.insert("name".to_string(), "fruently".to_string());
let fruently = Fluent::new_with_conf("noexistent.local:24224", "test", conf);
match fruently.post(&obj) {
Err(e) => println!("{:?}", e),
Ok(_) => {
assert!(file.exists());
return
},
}
}
| |
Add an xfailed test for bogus vector addition of typarams | // xfail-test
// expected error: mismatched kinds
resource r(i: @mutable int) {
*i = *i + 1;
}
fn f<@T>(i: [T], j: [T]) {
// Shouldn't be able to do this copy of j
let k = i + j;
}
fn main() {
let i1 = @mutable 0;
let i2 = @mutable 1;
let r1 <- [~r(i1)];
let r2 <- [~r(i2)];
f(r1, r2);
log_err *i1;
log_err *i2;
} | |
Fix a stack to use the new .to_c_str() api | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::str;
mod libc {
#[abi = "cdecl"]
#[nolink]
extern {
pub fn atol(x: *u8) -> int;
pub fn atoll(x: *u8) -> i64;
}
}
fn atol(s: ~str) -> int {
s.as_imm_buf(|x, _len| unsafe { libc::atol(x) })
}
fn atoll(s: ~str) -> i64 {
s.as_imm_buf(|x, _len| unsafe { libc::atoll(x) })
}
pub fn main() {
unsafe {
assert_eq!(atol(~"1024") * 10, atol(~"10240"));
assert!((atoll(~"11111111111111111") * 10i64)
== atoll(~"111111111111111110"));
}
}
| // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::str;
mod libc {
#[abi = "cdecl"]
#[nolink]
extern {
pub fn atol(x: *u8) -> int;
pub fn atoll(x: *u8) -> i64;
}
}
fn atol(s: ~str) -> int {
s.to_c_str().with_ref(|x| unsafe { libc::atol(x as *u8) })
}
fn atoll(s: ~str) -> i64 {
s.to_c_str().with_ref(|x| unsafe { libc::atoll(x as *u8) })
}
pub fn main() {
unsafe {
assert_eq!(atol(~"1024") * 10, atol(~"10240"));
assert!((atoll(~"11111111111111111") * 10i64)
== atoll(~"111111111111111110"));
}
}
|
Add inline const macro test | // run-pass
#![allow(incomplete_features)]
#![feature(inline_const)]
macro_rules! do_const_block{
($val:block) => { const $val }
}
fn main() {
let s = do_const_block!({ 22 });
assert_eq!(s, 22);
}
| |
Add example to load and print bundle | use kbdgen::{Load, ProjectBundle};
use snafu::ErrorCompat;
fn main() {
let path = std::env::args()
.nth(1)
.expect("Pass path to `.kbdgen` bundle as argument");
match ProjectBundle::load(&path) {
Ok(bundle) => eprintln!("{:#?}", bundle),
Err(e) => {
eprintln!("An error occurred: {}", e);
if let Some(backtrace) = ErrorCompat::backtrace(&e) {
println!("{}", backtrace);
}
}
}
}
| |
Update error message and un-xfail test | // xfail-test
// error-pattern:unresolved import: m::f
use x = m::f;
mod m {
#[legacy_exports];
}
fn main() {
}
| use x = m::f; //~ ERROR failed to resolve import
mod m {
#[legacy_exports];
}
fn main() {
}
|
Add missing example for testing the drop/ memory leakage | extern crate libmodbus_sys as raw;
extern crate libmodbus_rs;
use libmodbus_rs::modbus::{Modbus};
fn main() {
// 1. Parameter Serial Interface `/dev/ttyUSB0`
let device: String = std::env::args().nth(1).unwrap();
// 2. Parameter SlaveID
let slave_id: i32 = std::env::args().nth(2).unwrap().parse().unwrap();
let mut modbus = Modbus::new_rtu(&device, 9600, 'N', 8, 1);
let _ = modbus.set_slave(slave_id);
let _ = modbus.set_debug(true);
match modbus.connect() {
Err(_) => { modbus.free(); }
Ok(_) => {}
}
}
| |
Add failing test for globals to subcommands | extern crate clap;
extern crate regex;
include!("../clap-test.rs");
use clap::{App, Arg, SubCommand, ErrorKind, AppSettings};
static VISIBLE_ALIAS_HELP: &'static str = "clap-test 2.6
USAGE:
clap-test [SUBCOMMAND]
FLAGS:
-h, --help Prints help information
-V, --version Prints version information
SUBCOMMANDS:
help Prints this message or the help of the given subcommand(s)
test Some help [aliases: dongle, done]";
static INVISIBLE_ALIAS_HELP: &'static str = "clap-test 2.6
USAGE:
clap-test [SUBCOMMAND]
FLAGS:
-h, --help Prints help information
-V, --version Prints version information
SUBCOMMANDS:
help Prints this message or the help of the given subcommand(s)
test Some help";
#[cfg(feature = "suggestions")]
static DYM: &'static str = "error: The subcommand 'subcm' wasn't recognized
\tDid you mean 'subcmd'?
If you believe you received this message in error, try re-running with 'clap-test -- subcm'
USAGE:
clap-test [FLAGS] [OPTIONS] [ARGS] [SUBCOMMAND]
For more information try --help";
#[cfg(feature = "suggestions")]
static DYM2: &'static str = "error: Found argument '--subcm' which wasn't expected, or isn't valid in this context
\tDid you mean to put '--subcmdarg' after the subcommand 'subcmd'?
USAGE:
clap-test [FLAGS] [OPTIONS] [ARGS] [SUBCOMMAND]
For more information try --help";
#[test]
fn subcommand_can_access_global_arg_if_setting_is_on() {
let global_arg = Arg::with_name("GLOBAL_ARG")
.long("global-arg")
.help(
"Specifies something needed by the subcommands",
)
.global(true)
.takes_value(true);
let double_sub_command = SubCommand::with_name("outer")
.subcommand(SubCommand::with_name("run"));
let matches = App::new("globals")
.setting(AppSettings::PropagateGlobalValuesDown)
.arg(global_arg)
.subcommand(double_sub_command)
.get_matches_from(
vec!["globals", "outer", "--global-arg", "some_value"]
);
let sub_match = matches.subcommand_matches("outer").expect("could not access subcommand");
assert_eq!(sub_match.value_of("global-arg").expect("subcommand could not access global arg"),
"some_value", "subcommand did not have expected value for global arg");
} | |
Add a test for BTreeMap lifetime bound to see if it compiles | // check-pass
use std::collections::{BTreeMap, HashMap};
trait Map
where
for<'a> &'a Self: IntoIterator<Item = (&'a Self::Key, &'a Self::Value)>,
{
type Key;
type Value;
}
impl<K, V> Map for HashMap<K, V> {
type Key = K;
type Value = V;
}
impl<K, V> Map for BTreeMap<K, V> {
type Key = K;
type Value = V;
}
fn main() {}
| |
Add ignored test for associated types in const impl | // ignore-test
// FIXME: This test should fail since, within a const impl of `Foo`, the bound on `Foo::Bar` should
// require a const impl of `Add` for the associated type.
#![allow(incomplete_features)]
#![feature(const_trait_impl)]
#![feature(const_fn)]
struct NonConstAdd(i32);
impl std::ops::Add for NonConstAdd {
type Output = Self;
fn add(self, rhs: Self) -> Self {
NonConstAdd(self.0 + rhs.0)
}
}
trait Foo {
type Bar: std::ops::Add;
}
impl const Foo for NonConstAdd {
type Bar = NonConstAdd;
}
fn main() {}
| |
Add hello world server example | extern crate clap;
extern crate fibers;
extern crate futures;
extern crate miasht;
use fibers::{Executor, ThreadPoolExecutor};
use futures::{Future, BoxFuture};
use miasht::{Server, Status};
use miasht::builtin::servers::{SimpleHttpServer, RawConnection};
use miasht::builtin::headers::ContentLength;
use miasht::builtin::FutureExt;
fn main() {
let mut executor = ThreadPoolExecutor::new().unwrap();
let addr = "0.0.0.0:3000".parse().unwrap();
let server = SimpleHttpServer::new((), echo);
let server = server.start(addr, executor.handle());
let monitor = executor.spawn_monitor(server.join());
let result = executor.run_fiber(monitor).unwrap();
println!("HTTP Server shutdown: {:?}", result);
}
fn echo(_: (), connection: RawConnection) -> BoxFuture<(), ()> {
connection.read_request()
.and_then(|request| {
let bytes = b"Hello, World";
let connection = request.finish();
let mut response = connection.build_response(Status::Ok);
response.add_header(&ContentLength(bytes.len() as u64));
response.finish().write_all_bytes(bytes).then(|_| Ok(()))
})
.map_err(|e| {
println!("Error: {:?}", e);
()
})
.boxed()
}
| |
Add example showing incorrect handling of gamma | //! Demonstrates the current incorrect handling of gamma for RGB images
extern crate image;
extern crate imageproc;
use image::{ImageBuffer, Rgb};
use imageproc::pixelops::interpolate;
fn main() {
let red = Rgb([255, 0, 0]);
let green = Rgb([0, 255, 0]);
// We'll create an 800 pixel wide gradient image.
let left_weight = |x| x as f32 / 800.0;
let naive_blend = |x| {
interpolate(red, green, left_weight(x))
};
let mut naive_image = ImageBuffer::new(800, 400);
for y in 0..naive_image.height() {
for x in 0..naive_image.width() {
naive_image.put_pixel(x, y, naive_blend(x));
}
}
naive_image.save("naive_blend.png").unwrap();
let gamma = 2.2f32;
let gamma_inv = 1.0 / gamma;
let gamma_blend_channel = |l, r, w| {
let l = (l as f32).powf(gamma);
let r = (r as f32).powf(gamma);
let s: f32 = l * w + r * (1.0 - w);
s.powf(gamma_inv) as u8
};
let gamma_blend = |x| {
let w = left_weight(x);
Rgb([
gamma_blend_channel(red[0], green[0], w),
gamma_blend_channel(red[1], green[1], w),
gamma_blend_channel(red[2], green[2], w)
])
};
let mut gamma_image = ImageBuffer::new(800, 400);
for y in 0..gamma_image.height() {
for x in 0..gamma_image.width() {
gamma_image.put_pixel(x, y, gamma_blend(x));
}
}
gamma_image.save("gamma_blend.png").unwrap();
}
| |
Add compile-fail test of DST rvalues resulting from overloaded index | // 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 that overloaded index expressions with DST result types
// can't be used as rvalues
use std::ops::Index;
use std::fmt::Show;
struct S;
impl Index<uint, str> for S {
fn index<'a>(&'a self, _: &uint) -> &'a str {
"hello"
}
}
struct T;
impl Index<uint, Show + 'static> for T {
fn index<'a>(&'a self, idx: &uint) -> &'a Show + 'static {
static x: uint = 42;
&x
}
}
fn main() {
S[0];
//~^ ERROR E0161
T[0];
//~^ ERROR cannot move out of dereference
//~^^ ERROR E0161
}
| |
Add a test for mutable references to unique boxes as function arguments | fn f(&i: ~int) {
i = ~200;
}
fn main() {
let i = ~100;
f(i);
assert *i == 200;
} | |
Add another discriminant-size-related test, this time with fields. | // 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.
#[feature(macro_rules)];
use std::mem::size_of;
macro_rules! check {
($t:ty, $sz:expr, $($e:expr, $s:expr),*) => {{
assert_eq!(size_of::<$t>(), $sz);
$({
static S: $t = $e;
let v: $t = $e;
assert_eq!(S, v);
assert_eq!(format!("{:?}", v), ~$s);
assert_eq!(format!("{:?}", S), ~$s);
});*
}}
}
pub fn main() {
check!(Option<u8>, 2,
None, "None",
Some(129u8), "Some(129u8)");
check!(Option<i16>, 4,
None, "None",
Some(-20000i16), "Some(-20000i16)");
check!(Either<u8, i8>, 2,
Left(132u8), "Left(132u8)",
Right(-32i8), "Right(-32i8)");
check!(Either<u8, i16>, 4,
Left(132u8), "Left(132u8)",
Right(-20000i16), "Right(-20000i16)");
}
| |
Add test that runs every nannou example listed in the Cargo.toml | // A simple little script that attempts to run every example listed within the `Cargo.toml`.
//
// This will fail if any of the examples `panic!`.
#[test]
#[ignore]
fn test_run_all_examples() {
// Read the nannou cargo manifest to a `toml::Value`.
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let manifest_path = std::path::Path::new(manifest_dir).join("Cargo").with_extension("toml");
let bytes = std::fs::read(&manifest_path).unwrap();
let toml: toml::Value = toml::from_slice(&bytes).unwrap();
// Find the `examples` table within the `toml::Value` to find all example names.
let examples = toml["example"].as_array().expect("failed to retrieve example array");
for example in examples {
let name = example["name"].as_str().expect("failed to retrieve example name");
// For each example, invoke a cargo sub-process to run the example.
let mut child = std::process::Command::new("cargo")
.arg("run")
.arg("--example")
.arg(&name)
.spawn()
.expect("failed to spawn `cargo run --example` process");
// Allow each example to run for 3 secs each.
std::thread::sleep(std::time::Duration::from_secs(3));
// Kill the example and retrieve any output.
child.kill().ok();
let output = child.wait_with_output().expect("failed to wait for child process");
// If the example wrote to `stderr` it must have failed.
if !output.stderr.is_empty() {
panic!("example {} wrote to stderr: {:?}", name, output);
}
}
}
| |
Add example for exec command | extern crate shiplift;
use shiplift::{Docker, ExecContainerOptions};
use std::env;
fn main() {
let docker = Docker::new();
let options = ExecContainerOptions::builder().cmd(vec!["ls"]).build();
if let Some(id) = env::args().nth(1) {
let container = docker.containers()
.get(&id)
.exec(&options)
.unwrap();
println!("{:?}", container);
}
}
| |
Add utils from my 30 days of code project | use std::io::BufRead;
use std::iter::FromIterator;
pub fn get_line<T>(mut input: T)
-> String
where T: BufRead
{
let mut buffer = String::new();
input.read_line(&mut buffer).unwrap();
buffer
}
pub fn parse_single_number(input: String)
-> i32
{
input.trim().parse::<i32>().unwrap()
}
#[allow(dead_code)]
pub fn get_single_number<T>(input: T)
-> i32
where T: BufRead
{
parse_single_number(get_line(input))
}
#[allow(dead_code)]
pub fn get_numbers(line: String)
-> Vec<i32>
{
Vec::from_iter(
line.split_whitespace()
.map(|x| x.parse::<i32>().unwrap())
)
}
| |
Add a related test case | // check-pass
// compile-flags: -Zsave-analysis
// Check that this doesn't ICE when processing associated const in formal
// argument and return type of functions defined inside function/method scope.
pub trait Trait {
type Assoc;
}
pub struct A;
pub fn func() {
fn _inner1<U: Trait>(_: U::Assoc) {}
fn _inner2<U: Trait>() -> U::Assoc { unimplemented!() }
impl A {
fn _inner1<U: Trait>(self, _: U::Assoc) {}
fn _inner2<U: Trait>(self) -> U::Assoc { unimplemented!() }
}
}
fn main() {}
| |
Remove legacy modes and exports | #[legacy_modes];
#[legacy_exports];
#[allow(ctypes)];
#[allow(heap_memory)];
#[allow(implicit_copies)];
#[allow(managed_heap_memory)];
#[allow(non_camel_case_types)];
#[allow(non_implicitly_copyable_typarams)];
#[allow(owned_heap_memory)];
#[allow(path_statement)];
#[allow(structural_records)];
#[allow(unrecognized_lint)];
#[allow(unused_imports)];
#[allow(vecs_implicitly_copyable)];
#[allow(while_true)];
extern mod std;
fn print<T>(+result: T) {
io::println(fmt!("%?", result));
}
| #[allow(ctypes)];
#[allow(heap_memory)];
#[allow(implicit_copies)];
#[allow(managed_heap_memory)];
#[allow(non_camel_case_types)];
#[allow(non_implicitly_copyable_typarams)];
#[allow(owned_heap_memory)];
#[allow(path_statement)];
#[allow(structural_records)];
#[allow(unrecognized_lint)];
#[allow(unused_imports)];
#[allow(vecs_implicitly_copyable)];
#[allow(while_true)];
extern mod std;
fn print<T>(+result: T) {
io::println(fmt!("%?", result));
}
|
Add implementation of johnson-subalgorithm with explicit matrix inversion. | use core::num::{Zero, One};
use core::vec::{len, push};
use nalgebra::ndim::dmat::{zero_mat_with_dim};
use nalgebra::traits::division_ring::DivisionRing;
use nalgebra::traits::sub_dot::SubDot;
use nalgebra::traits::inv::Inv;
use nalgebra::traits::workarounds::scalar_op::{ScalarMul, ScalarDiv};
pub struct ExplicitJohnsonSimplex<V, T>
{
points: ~[~V]
}
// FIXME: remove ToStr
impl<V: Copy + SubDot<T> + ScalarMul<T> + ScalarDiv<T> + Zero + Add<V, V>,
T: Ord + Copy + Clone + Eq + DivisionRing + ApproxEq<T> + Ord>
ExplicitJohnsonSimplex<V, T>
{
pub fn new(initial_point: &V) -> ExplicitJohnsonSimplex<V, T>
{ ExplicitJohnsonSimplex { points: ~[~*initial_point] } }
pub fn add_point(&mut self, pt: &V)
{ push(&mut self.points, ~*pt) }
pub fn project_origin(&mut self) -> Option<V>
{
let _0 = Zero::zero::<T>();
let _1 = One::one::<T>();
let dim = len(self.points);
let mut mat = zero_mat_with_dim(dim);
for uint::range(0u, dim) |i|
{ mat.set(0u, i, &_1) }
for uint::range(1u, dim) |i|
{
for uint::range(0u, dim) |j|
{
mat.set(
i,
j,
&self.points[i].sub_dot(self.points[0], self.points[j])
)
}
}
mat.invert();
let mut res = Zero::zero::<V>();
let mut normalizer = Zero::zero::<T>();
for uint::range(0u, dim) |i|
{
if (mat.at(i, 0u) > _0)
{
let offset = mat.at(i, 0u);
res += self.points[i].scalar_mul(&offset);
normalizer += offset;
}
}
res.scalar_div_inplace(&normalizer);
Some(res)
}
}
| |
Add test to make sure -Wunused-crate-dependencies works with tests | // Test-only use OK
// edition:2018
// check-pass
// aux-crate:bar=bar.rs
// compile-flags:--test
#![deny(unused_crate_dependencies)]
fn main() {}
#[test]
fn test_bar() {
assert_eq!(bar::BAR, "bar");
}
| |
Add solution to problem 39 | #[macro_use] extern crate libeuler;
/// If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are
/// exactly three solutions for p = 120.
///
/// {20,48,52}, {24,45,51}, {30,40,50}
///
/// For which value of p ≤ 1000, is the number of solutions maximised?
fn main() {
solutions! {
sol naive {
let mut max = 0;
let mut maxval = 0;
for i in 0..1000 {
let triangles = get_triangles(i);
if triangles.len() > max {
max = triangles.len();
maxval = i;
}
}
maxval
}
}
}
#[derive(Debug)]
struct Triangle {
one: i64,
two: i64,
three: i64
}
fn get_triangles(p: i64) -> Vec<Triangle> {
let mut retval = Vec::new();
for one in 1..p {
for two in one..p {
let three = p - one - two;
if three as f64 == (one.pow(2) as f64 + two.pow(2) as f64).sqrt() {
retval.push(Triangle {
one: one,
two: two,
three: three
});
}
}
}
retval
}
| |
Add test case for wasm non-clash. | // check-pass
#![crate_type = "lib"]
#[cfg(target_arch = "wasm32")]
mod wasm_non_clash {
mod a {
#[link(wasm_import_module = "a")]
extern "C" {
pub fn foo();
}
}
mod b {
#[link(wasm_import_module = "b")]
extern "C" {
pub fn foo() -> usize;
// #79581: These declarations shouldn't clash because foreign fn names are mangled
// on wasm32.
}
}
}
| |
Add rust code for nucleotide-count case | use std::collections::HashMap;
pub fn nucleotide_counts(serial: &str) -> Result<HashMap<char, usize>, &str> {
let counter = &mut [0usize; 4];
for s in serial.chars() {
match s {
'A' => counter[0] += 1,
'C' => counter[1] += 1,
'G' => counter[2] += 1,
'T' => counter[3] += 1,
_ => return Err("Invalid serial"),
}
}
Ok(
[
('A', counter[0]),
('C', counter[1]),
('G', counter[2]),
('T', counter[3]),
].iter()
.cloned()
.collect(),
)
}
pub fn count(n: char, serial: &str) -> Result<usize, &str> {
if n != 'A' && n != 'C' && n != 'G' && n != 'T' {
return Err("Invalid nucleotide");
}
let mut counter = 0;
for s in serial.chars() {
if s == n {
counter += 1;
continue;
}
if s != 'A' && s != 'C' && s != 'G' && s != 'T' {
return Err("Invalid serial");
}
}
Ok(counter)
}
| |
Add test for `box EXPR` dereferencing | // Copyright 2016 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(rustc_attrs, box_syntax)]
#[rustc_mir]
fn test() -> Box<i32> {
box 42
}
fn main() {
assert_eq!(*test(), 42);
}
| |
Add cfail test for custom attribute gate | // 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.
#[foo] //~ ERROR The attribute `foo`
fn main() {
} | |
Use an array to label all commands and add `ptr_write` command | use std::{io, fs};
macro_rules! readln {
() => {
{
let mut line = String::new();
match io::stdin().read_line(&mut line) {
Ok(n) => Some(line.trim().to_string()),
Err(e) => None
}
}
};
}
fn console_title(title: &str) {
}
#[no_mangle]
pub fn main() {
console_title("Test");
println!("Type help for a command list");
while let Some(line) = readln!() {
let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect();
if let Some(command) = args.get(0) {
println!("# {}", line);
match &command[..]
{
"panic" => panic!("Test panic"),
"ls" => {
// TODO: when libredox is completed
//fs::read_dir("/").unwrap().map(|dir| println!("{}", dir));
}
_ => println!("Commands: panic"),
}
}
}
}
| #![feature(alloc)]
#![feature(core)]
extern crate alloc;
extern crate core;
use alloc::boxed::Box;
use std::{io, fs, rand};
use core::ptr;
macro_rules! readln {
() => {
{
let mut line = String::new();
match io::stdin().read_line(&mut line) {
Ok(n) => Some(line.trim().to_string()),
Err(e) => None
}
}
};
}
fn console_title(title: &str) {
}
#[no_mangle]
pub fn main() {
console_title("Test");
println!("Type help for a command list");
while let Some(line) = readln!() {
let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect();
if let Some(command) = args.get(0) {
println!("# {}", line);
let console_commands = ["panic", "ls", "ptr_write"];
match &command[..]
{
command if command == console_commands[0] => panic!("Test panic"),
command if command == console_commands[1] => {
// TODO: import std::fs functions into libredox
//fs::read_dir("/").unwrap().map(|dir| println!("{}", dir));
}
command if command == console_commands[2] => {
let a_ptr = rand() as *mut u8;
// TODO: import Box::{from_raw, to_raw} methods in libredox
//let mut a_box = Box::new(rand() as u8);
unsafe {
ptr::write(a_ptr, rand() as u8);
//ptr::write(a_box.to_raw(), rand() as u8);
}
}
_ => println!("Commands: {}", console_commands.join(" ")),
}
}
}
}
|
Change typestate to use visit instead of walk | // error-pattern:Unsatisfied precondition constraint (for example, init(bar
// xfail-stage0
fn main() {
auto bar;
fn baz(int x) { }
bind baz(bar);
}
| |
Add a test for const | // run-pass
#![feature(cow_is_borrowed)]
use std::borrow::Cow;
fn main() {
const COW: Cow<str> = Cow::Borrowed("moo");
const IS_BORROWED: bool = COW.is_borrowed();
assert!(IS_BORROWED);
const IS_OWNED: bool = COW.is_owned();
assert!(!IS_OWNED);
}
| |
Add implementation of Leonid Volnitsky's fast substring search | extern crate core;
use core::mem;
use std::io;
use std::io::{BufReader, SeekSet};
use std::iter::range_step;
static hash_size:uint = 64*1024;
fn volnitsky(data: &[u8], substring: &[u8]) -> Option<uint> {
let mut dataReader = BufReader::new(data);
let mut substringReader = BufReader::new(substring);
let w_size = mem::size_of::<u16>();
let step = substring.len() - w_size + 1;
let mut hash = [0u8, ..hash_size];
for i in range(0, substring.len() - w_size).rev() {
substringReader.seek(i as i64, SeekSet).unwrap();
let mut hash_index = (substringReader.read_le_u16().unwrap() as uint) % hash_size;
while hash[hash_index] != 0 {
hash_index = (hash_index + 1) % hash_size;
}
hash[hash_index] = i as u8 + 1;
}
for offset in range_step(substring.len() - w_size, data.len() - substring.len() + 1, step) {
dataReader.seek(offset as i64, SeekSet).unwrap();
let mut hash_index = (dataReader.read_le_u16().unwrap() as uint) % hash_size;
'hash_check: loop {
if hash[hash_index] == 0 {
break;
}
let subOffset = offset - (hash[hash_index] as uint - 1);
for i in range(0,substring.len()) {
if data[subOffset + i] != substring[i] {
hash_index = (hash_index + 1) % hash_size;
continue 'hash_check;
}
}
return Some(subOffset);
}
}
return None;
// should have:
//return std::search(P-step+1,Se,SS,SSe);
}
fn main() {
let mut stdin = io::stdin();
let dataVec = stdin.read_to_end().unwrap();
let data = dataVec.slice(0,dataVec.len());
let substring = bytes!("Anything whatsoever related to the Rust programming language: an open-source systems programming language from Mozilla, emphasizing safety, concurrency, and speed.");
// let substring = bytes!("This eBook is for the use ");
println!("voln: {}", volnitsky(data, substring));
}
| |
Add comment explaining purpose of test | // 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 struct Foo { a: u32 }
pub struct Pass<'a, 'tcx: 'a>(&'a mut &'a (), &'a &'tcx ());
impl<'a, 'tcx> Pass<'a, 'tcx>
{
pub fn tcx(&self) -> &'a &'tcx () { self.1 }
fn lol(&mut self, b: &Foo)
{
b.c; //~ ERROR no field with that name was found
self.tcx();
}
}
fn main() {}
| // 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.
// Test that we do not see uninformative region-related errors
// when we get some basic type-checking failure. See #30580.
pub struct Foo { a: u32 }
pub struct Pass<'a, 'tcx: 'a>(&'a mut &'a (), &'a &'tcx ());
impl<'a, 'tcx> Pass<'a, 'tcx>
{
pub fn tcx(&self) -> &'a &'tcx () { self.1 }
fn lol(&mut self, b: &Foo)
{
b.c; //~ ERROR no field with that name was found
self.tcx();
}
}
fn main() {}
|
Add rust code for collatz-conjecture case | // return Ok(x) where x is the number of steps required to reach 1
pub fn collatz(n: u64) -> Result<u64, &'static str> {
if n < 1 {
return Err("Invalid number");
}
let mut result = n;
let mut steps = 0;
while result != 1 {
if result % 2 == 0 {
result /= 2;
} else {
result = 3 * result + 1;
}
steps += 1;
}
Ok(steps)
}
| |
Test yielding in crust functions | native mod rustrt {
fn rust_dbg_call(cb: *u8,
data: ctypes::uintptr_t) -> ctypes::uintptr_t;
}
crust fn cb(data: ctypes::uintptr_t) -> ctypes::uintptr_t {
if data == 1u {
data
} else {
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
task::yield();
rustrt::rust_dbg_call(cb, n)
}
fn main() {
iter::repeat(10u) {||
task::spawn {||
let result = count(5u);
#debug("result = %?", result);
assert result == 16u;
};
}
}
| |
Add example for custom timestamp | #[macro_use(o,slog_log,slog_trace,slog_debug,slog_info,slog_warn,slog_error,slog_crit)]
extern crate slog;
extern crate slog_term;
use std::time::{Duration, SystemTime};
use slog::DrainExt;
fn main() {
let now = SystemTime::now();
let streamer = slog_term::StreamerBuilder::new()
.use_custom_timestamp(Box::new(move || {
let elapsed = now.elapsed().unwrap();
format!("{:5}.{:06}", elapsed.as_secs(), elapsed.subsec_nanos()/1000)
}));
let log = slog::Logger::root(streamer.build().fuse(), o!());
slog_trace!(log, "logging a trace message");
std::thread::sleep(Duration::from_millis(250));
slog_debug!(log, "debug values"; "x" => 1, "y" => -1);
std::thread::sleep(Duration::from_millis(250));
slog_info!(log, "some interesting info"; "where" => "right here");
std::thread::sleep(Duration::from_millis(250));
slog_warn!(log, "be cautious!"; "why" => "you never know...");
std::thread::sleep(Duration::from_millis(250));
slog_error!(log, "type" => "unknown"; "wrong {}", "foobar");
std::thread::sleep(Duration::from_millis(250));
slog_crit!(log, "abandoning test");
}
| |
Add codegen test for multiple `asm!` options | // compile-flags: -O
// only-x86_64
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @pure
// CHECK-NOT: asm
// CHECK: ret void
#[no_mangle]
pub unsafe fn pure(x: i32) {
let y: i32;
asm!("", out("ax") y, in("bx") x, options(pure), options(nomem));
}
pub static mut VAR: i32 = 0;
pub static mut DUMMY_OUTPUT: i32 = 0;
// CHECK-LABEL: @readonly
// CHECK: call i32 asm
// CHECK: ret i32 1
#[no_mangle]
pub unsafe fn readonly() -> i32 {
VAR = 1;
asm!("", out("ax") DUMMY_OUTPUT, options(pure), options(readonly));
VAR
}
// CHECK-LABEL: @nomem
// CHECK-NOT: store
// CHECK: call i32 asm
// CHECK: store
// CHECK: ret i32 2
#[no_mangle]
pub unsafe fn nomem() -> i32 {
VAR = 1;
asm!("", out("ax") DUMMY_OUTPUT, options(pure), options(nomem));
VAR = 2;
VAR
}
// CHECK-LABEL: @not_nomem
// CHECK: store
// CHECK: call i32 asm
// CHECK: store
// CHECK: ret i32 2
#[no_mangle]
pub unsafe fn not_nomem() -> i32 {
VAR = 1;
asm!("", out("ax") DUMMY_OUTPUT, options(pure), options(readonly));
VAR = 2;
VAR
}
| |
Implement Counter struct and Iterator for it | struct Counter {
count: u32
}
impl Counter {
fn new() -> Counter {
Counter { count: 0 }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
self.count += 1;
if self.count < 6 {
Some(self.count)
} else {
None
}
}
} | |
Set the proper permissions of the executable for glsl-to-spirv | use std::env;
use std::fs;
use std::path::Path;
fn main() {
println!("cargo:rerun-if-changed=build/glslangValidator");
println!("cargo:rerun-if-changed=build/glslangValidator.exe");
let target = env::var("TARGET").unwrap();
let out_file = Path::new(&env::var("OUT_DIR").unwrap()).join("glslang_validator");
let path = if target.contains("windows") {
Path::new("build/glslangValidator.exe")
} else if target.contains("linux") {
Path::new("build/glslangValidator")
} else {
panic!("The platform `{}` is not supported", target);
};
if let Err(_) = fs::hard_link(&path, &out_file) {
fs::copy(&path, &out_file).unwrap();
}
//fs::set_permissions(&out_file, std::io::USER_EXEC).unwrap();
}
| use std::env;
use std::fs;
use std::fs::Permissions;
use std::path::Path;
fn main() {
println!("cargo:rerun-if-changed=build/glslangValidator");
println!("cargo:rerun-if-changed=build/glslangValidator.exe");
let target = env::var("TARGET").unwrap();
let out_file = Path::new(&env::var("OUT_DIR").unwrap()).join("glslang_validator");
let path = if target.contains("windows") {
Path::new("build/glslangValidator.exe")
} else if target.contains("linux") {
Path::new("build/glslangValidator")
} else {
panic!("The platform `{}` is not supported", target);
};
if let Err(_) = fs::hard_link(&path, &out_file) {
fs::copy(&path, &out_file).unwrap();
}
// setting permissions of the executable
{
#[cfg(linux)] fn permissions() -> Option<Permissions> {
use std::os::unix::fs::PermissionsExt;
Some(Permissions::from_mode(755))
}
#[cfg(not(linux))] fn permissions() -> Option<Permissions> { None }
if let Some(permissions) = permissions() {
fs::set_permissions(&out_file, permissions).unwrap();
}
}
}
|
Add executation of single commands | use std::io;
use std::io::Write; // need it to flush stdout
static PROMPT: &'static str = "$ ";
fn execute(cmd: &String) {
println!("you entered [{}]", cmd);
}
fn main() {
// we allocate a String for the user input
let mut input: String = String::new();
loop {
print!("{}", PROMPT);
if let Err(why) = io::stdout().flush() {
println!("error: {}", why);
continue;
}
// input probably has stuff in it from the last command, so clear
// it out
input.clear();
// read input into our String. if there was an error, print the
// error message and continue
if let Err(why) = io::stdin().read_line(&mut input){
println!("error: {}", why);
continue;
}
// trim the newline off and save it back
input = input.trim().to_string();
execute(&input);
if input == "exit" {
println!("Exiting!");
break;
}
}
}
| use std::io;
use std::io::Write; // need it to flush stdout
use std::process;
static PROMPT: &'static str = "$ ";
fn execute(cmd: &String) {
let ret = process::Command::new(cmd).output().unwrap();
println!("{}", String::from_utf8_lossy(&ret.stdout).trim());
}
fn main() {
// we allocate a String for the user input
let mut input: String = String::new();
loop {
print!("{}", PROMPT);
if let Err(why) = io::stdout().flush() {
println!("error: {}", why);
continue;
}
// input probably has stuff in it from the last command, so clear
// it out
input.clear();
// read input into our String. if there was an error, print the
// error message and continue
if let Err(why) = io::stdin().read_line(&mut input){
println!("error: {}", why);
continue;
}
// trim the newline off and save it back
input = input.trim().to_string();
execute(&input);
if input == "exit" {
println!("Exiting!");
break;
}
}
}
|
Make hand rank classes hashable. | extern crate cards;
use cards::card::{Card};
//TODO: this could be an option as well
//pub type CardSlot = Option<Card>;
pub enum CardSlot {
Empty,
Dealt(Card),
}
impl CardSlot {
pub fn expect_borrow(&self) -> &Card {
match self {
&CardSlot::Empty => panic!("You are trying to borrow a non-dealt card"),
&CardSlot::Dealt(ref x) => x
}
}
}
#[derive(Debug)]
#[derive(PartialEq)]
pub enum HandRankClass {
HighCard,
OnePair,
TwoPair,
ThreeOfAKind,
Straight,
Flush,
FullHouse,
FourOfAKind,
StraightFlush,
}
pub struct HandCards(pub CardSlot, pub CardSlot);
pub struct CommunityCards(pub CardSlot, pub CardSlot, pub CardSlot, pub CardSlot, pub CardSlot);
| extern crate cards;
use cards::card::{Card};
//TODO: this could be an option as well
//pub type CardSlot = Option<Card>;
pub enum CardSlot {
Empty,
Dealt(Card),
}
impl CardSlot {
pub fn expect_borrow(&self) -> &Card {
match self {
&CardSlot::Empty => panic!("You are trying to borrow a non-dealt card"),
&CardSlot::Dealt(ref x) => x
}
}
}
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq, Hash)]
pub enum HandRankClass {
HighCard,
OnePair,
TwoPair,
ThreeOfAKind,
Straight,
Flush,
FullHouse,
FourOfAKind,
StraightFlush,
}
pub struct HandCards(pub CardSlot, pub CardSlot);
pub struct CommunityCards(pub CardSlot, pub CardSlot, pub CardSlot, pub CardSlot, pub CardSlot);
|
Use a buffered reader (much, much, much faster) | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::env;
use std::fs::File;
use std::path::Path;
extern crate csv_checker;
fn report_errors_for_file(file: File) -> i32 {
let mut exit = 0;
let rx = csv_checker::publish_errors_for_csv(file);
for error in rx {
exit = 1;
println!("error at line {}, col {}: {}",
error.line,
error.col,
error.text);
}
exit
}
fn errors_for_args() -> i32 {
let mut exit_code: i32 = 0;
// Skip the first arg since it's the program itself
let paths = env::args().skip(1);
if paths.len() == 0 {
panic!("Provide some paths!");
}
for arg in paths {
println!("= {} =", arg);
let path = Path::new(&arg);
exit_code += match File::open(&path) {
Err(_) => {
println!("!!! Not found");
1
}
Ok(file) => report_errors_for_file(file),
};
}
exit_code
}
fn main() {
let exit_code = errors_for_args();
std::process::exit(exit_code);
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::env;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
extern crate csv_checker;
fn report_errors_for_file(file: File) -> i32 {
let mut exit = 0;
let reader = BufReader::new(file);
let rx = csv_checker::publish_errors_for_csv(reader);
for error in rx {
exit = 1;
println!("error at line {}, col {}: {}",
error.line,
error.col,
error.text);
}
exit
}
fn errors_for_args() -> i32 {
let mut exit_code: i32 = 0;
// Skip the first arg since it's the program itself
let paths = env::args().skip(1);
if paths.len() == 0 {
panic!("Provide some paths!");
}
for arg in paths {
println!("= {} =", arg);
let path = Path::new(&arg);
exit_code += match File::open(&path) {
Err(_) => {
println!("!!! Not found");
1
}
Ok(file) => report_errors_for_file(file),
};
}
exit_code
}
fn main() {
let exit_code = errors_for_args();
std::process::exit(exit_code);
}
|
Include client IP in UnprocessableEntity error | use chattium_oxide_lib::json::FromJsonnable;
use chattium_oxide_lib::ChatMessage;
use hyper::server::{Request, Response};
use hyper::status::StatusCode;
use hyper::method::Method;
use std::io::Read;
pub fn handle_client(req: Request, mut res: Response) {
let mut req = req;
*res.status_mut() = match req.method {
Method::Post => {
let mut reqbody = String::new();
match req.read_to_string(&mut reqbody) {
Ok(_) =>
match ChatMessage::from_json_string(&reqbody) {
Ok(mut message) => {
message.sender.fill_ip(req.remote_addr);
println!("{:?}", message);
StatusCode::Ok
},
Err(error) => {
println!("Couldn't process POSTed message: {}", error);
StatusCode::UnprocessableEntity
},
},
Err(error) => {
println!("Failed reading request from {}: {}", req.remote_addr, error);
StatusCode::UnsupportedMediaType // non-UTF-8
},
}
},
_ => StatusCode::ImATeapot,
}
}
| use chattium_oxide_lib::json::FromJsonnable;
use chattium_oxide_lib::ChatMessage;
use hyper::server::{Request, Response};
use hyper::status::StatusCode;
use hyper::method::Method;
use std::io::Read;
pub fn handle_client(req: Request, mut res: Response) {
let mut req = req;
*res.status_mut() = match req.method {
Method::Post => {
let mut reqbody = String::new();
match req.read_to_string(&mut reqbody) {
Ok(_) =>
match ChatMessage::from_json_string(&reqbody) {
Ok(mut message) => {
message.sender.fill_ip(req.remote_addr);
println!("{:?}", message);
StatusCode::Ok
},
Err(error) => {
println!("Couldn't process POSTed message from {}: {}", req.remote_addr, error);
StatusCode::UnprocessableEntity
},
},
Err(error) => {
println!("Failed reading request from {}: {}", req.remote_addr, error);
StatusCode::UnsupportedMediaType // non-UTF-8
},
}
},
_ => StatusCode::ImATeapot,
}
}
|
Change the Error handling and remove unsed code | // Needed for reading a Json File
// extern crate rustc_serialize;
// use rustc_serialize::json::Json;
// use std::fs::File;
// use std::io::Read;
use uuid::Uuid;
use libimagstore::store::Store;
use libimagstore::storeid::IntoStoreId;
use module_path::ModuleEntryPath;
use error::{TodoError, TodoErrorKind};
/// With the uuid we get the storeid and than we can delete the entry
pub fn deleteFunc(uuid: Uuid, store : &Store) {
// With this we can read from a .json File
// let mut file = File::open("text.json").unwrap();
// let mut data = String::new();
// file.rad_to_string(&mut data).unwrap();
//
// let jeson = Json::from_str(&data).unwrap();
// println!("{}", json.find_path(&["uuid"]).unwrap());
// With the uuid we get the storeid
let store_id = ModuleEntryPath::new(format!("taskwarrior/{}", uuid)).into_storeid();
// It deletes an entry
if let Err(e) = store.delete(store_id) {
return Err(TodoError::new(TodoErrorKind::StoreError, Some(Box::new(e)))).unwrap();
}
}
| use uuid::Uuid;
use libimagstore::store::Store;
use libimagstore::storeid::IntoStoreId;
use module_path::ModuleEntryPath;
use error::{TodoError, TodoErrorKind};
/// With the uuid we get the storeid and then we can delete the entry
pub fn deleteFunc(uuid: Uuid, store : &Store) -> Result<(),TodoError> {
// With the uuid we get the storeid
let store_id = ModuleEntryPath::new(format!("taskwarrior/{}", uuid)).into_storeid();
// It deletes an entry
match store.delete(store_id) {
Ok(val) => Ok(val),
Err(e) => Err(TodoError::new(TodoErrorKind::StoreError, Some(Box::new(e)))),
}
}
|
Use updated local declaration syntax. | // xfail-test FIXME #6257
// 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.
use std::cmp::{Less,Equal,Greater};
#[deriving(TotalEq,TotalOrd)]
struct A<'self> {
x: &'self int
}
fn main() {
let a = A { x: &1 }, b = A { x: &2 };
assert!(a.equals(&a));
assert!(b.equals(&b));
assert_eq!(a.cmp(&a), Equal);
assert_eq!(b.cmp(&b), Equal);
assert_eq!(a.cmp(&b), Less);
assert_eq!(b.cmp(&a), Greater);
}
| // 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.
use std::cmp::{Less,Equal,Greater};
#[deriving(TotalEq,TotalOrd)]
struct A<'self> {
x: &'self int
}
fn main() {
let (a, b) = (A { x: &1 }, A { x: &2 });
assert!(a.equals(&a));
assert!(b.equals(&b));
assert_eq!(a.cmp(&a), Equal);
assert_eq!(b.cmp(&b), Equal);
assert_eq!(a.cmp(&b), Less);
assert_eq!(b.cmp(&a), Greater);
}
|
Use the ErrorCode enum directly | #![no_std]
use libtock_low_level_debug::{AlertCode, LowLevelDebug};
use libtock_platform::Syscalls;
use libtock_runtime::TockSyscalls;
#[panic_handler]
fn panic_handler(_info: &core::panic::PanicInfo) -> ! {
// Signal a panic using the LowLevelDebug capsule (if available).
LowLevelDebug::<TockSyscalls>::print_alert_code(AlertCode::Panic);
// Exit with a non-zero exit code to indicate failure.
TockSyscalls::exit_terminate(1);
}
| #![no_std]
use libtock_low_level_debug::{AlertCode, LowLevelDebug};
use libtock_platform::{ErrorCode, Syscalls};
use libtock_runtime::TockSyscalls;
#[panic_handler]
fn panic_handler(_info: &core::panic::PanicInfo) -> ! {
// Signal a panic using the LowLevelDebug capsule (if available).
LowLevelDebug::<TockSyscalls>::print_alert_code(AlertCode::Panic);
// Exit with a non-zero exit code to indicate failure.
TockSyscalls::exit_terminate(ErrorCode::Fail as u32);
}
|
Remove is_whitespace function as no longer used | // 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/.
pub const NB_CHAR: char = ' '; // non breaking space
pub const NB_CHAR_NARROW: char = '\u{202F}'; // narrow non breaking space
pub const NB_CHAR_EM: char = '\u{2002}'; // demi em space
/// Custom function because we don't really want to touch \t or \n
///
/// This function detects spaces and non breking spaces
pub fn is_whitespace(c: char) -> bool {
c == ' ' || c == ' ' || c == ' '
}
| // 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/.
pub const NB_CHAR: char = ' '; // non breaking space
pub const NB_CHAR_NARROW: char = '\u{202F}'; // narrow non breaking space
pub const NB_CHAR_EM: char = '\u{2002}'; // demi em space
|
Clean up solution for Saddle Points | pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
let mut row_max = vec![Vec::new(); input.len()];
let mut col_min: Vec<Vec<(usize, u64)>> = vec![Vec::new(); input[0].len()];
for (row, values) in input.iter().enumerate() {
for (col, &value) in values.iter().enumerate() {
let mut c = &mut col_min[col];
if c.is_empty() || c[0].1 == value {
c.push((row, value));
} else if c[0].1 > value {
c.clear();
c.push((row, value));
}
let mut r = &mut row_max[row];
if r.is_empty() || r[0] == value {
r.push(value);
} else if r[0] < value {
r.clear();
r.push(value);
}
}
}
col_min
.iter()
.enumerate()
.fold(Vec::new(), |mut points, (col, values)| {
let mut col_points = values
.iter()
.filter(|c| row_max[c.0].contains(&c.1))
.map(|c| (c.0, col))
.collect();
points.append(&mut col_points);
points
})
}
| pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
let mut row_max = vec![None; input.len()];
let mut col_min = vec![(None, Vec::new()); input[0].len()];
for (row, values) in input.iter().enumerate() {
for (col, &value) in values.iter().enumerate() {
if row_max[row].filter(|&v| v >= value).is_none() {
row_max[row] = Some(value);
}
let mut c = &mut col_min[col];
if c.0.filter(|&v| v <= value).is_none() {
c.1.clear();
}
if c.0.filter(|&v| v < value).is_none() {
c.0 = Some(value);
c.1.push(row);
}
}
}
col_min
.iter()
.enumerate()
.fold(Vec::new(), |mut points, (col, (value, rows))| {
let mut col_points = rows
.iter()
.filter(|&&row| row_max[row] == *value)
.map(|&row| (row, col))
.collect();
points.append(&mut col_points);
points
})
}
|
Add a `ProgramBinder` field to `Context` | use super::gl_lib as gl;
use super::buffer::{ArrayBufferBinder, ElementArrayBufferBinder};
pub struct Context {
pub array_buffer: ArrayBufferBinder,
pub element_array_buffer: ElementArrayBufferBinder
}
impl Context {
pub unsafe fn current_context() -> Self {
Context {
array_buffer: ArrayBufferBinder,
element_array_buffer: ElementArrayBufferBinder
}
}
pub fn clear_color(&mut self, color: super::Color) {
unsafe {
gl::ClearColor(color.r, color.g, color.b, color.a);
}
}
pub fn clear(&mut self, buffers: super::BufferBits) {
unsafe {
gl::Clear(buffers.bits())
}
}
pub fn enable_vertex_attrib_array(&self, attrib: super::ProgramAttrib) {
unsafe {
gl::EnableVertexAttribArray(attrib.gl_index);
}
}
}
#[macro_export]
macro_rules! bind_array_buffer {
($gl:expr, $buffer:expr) => {
$gl.array_buffer.bind($buffer)
}
}
#[macro_export]
macro_rules! bind_element_array_buffer {
($gl:expr, $buffer:expr) => {
$gl.element_array_buffer.bind($buffer)
}
}
| use super::gl_lib as gl;
use super::buffer::{ArrayBufferBinder, ElementArrayBufferBinder};
use super::program::{ProgramBinder};
pub struct Context {
pub array_buffer: ArrayBufferBinder,
pub element_array_buffer: ElementArrayBufferBinder,
pub program: ProgramBinder
}
impl Context {
pub unsafe fn current_context() -> Self {
Context {
array_buffer: ArrayBufferBinder,
element_array_buffer: ElementArrayBufferBinder,
program: ProgramBinder
}
}
pub fn clear_color(&mut self, color: super::Color) {
unsafe {
gl::ClearColor(color.r, color.g, color.b, color.a);
}
}
pub fn clear(&mut self, buffers: super::BufferBits) {
unsafe {
gl::Clear(buffers.bits())
}
}
pub fn enable_vertex_attrib_array(&self, attrib: super::ProgramAttrib) {
unsafe {
gl::EnableVertexAttribArray(attrib.gl_index);
}
}
}
#[macro_export]
macro_rules! bind_array_buffer {
($gl:expr, $buffer:expr) => {
$gl.array_buffer.bind($buffer)
}
}
#[macro_export]
macro_rules! bind_element_array_buffer {
($gl:expr, $buffer:expr) => {
$gl.element_array_buffer.bind($buffer)
}
}
|
Put the consumer callback function into a type - box it so it can be moved around without cloning | use std::rc::*;
use std::ops::*;
use super::super::tree::*;
pub type PublisherRef = Box<Publisher>;
pub type ConsumerRef = Box<Consumer>;
///
/// A publisher reports changes to a tree
///
pub trait Publisher {
///
/// Publishes a change to the consumers of this component
///
fn publish(&mut self, change: TreeChange);
}
///
/// A consumer subscribes to published changes to a tree
///
pub trait Consumer {
///
/// Calls a function whenever a particular section of the tree has changed
///
fn subscribe(&mut self, address: TreeAddress, extent: TreeExtent, callback: Fn(TreeChange) -> ());
}
///
/// A component consumes a tree and publishes a tree.
///
pub trait Component : Drop {
}
///
/// References to components are used to keep track of the components that are currently active
///
pub type ComponentRef = Rc<Component>;
///
/// A component subscribes consumes a tree and publishes a transformed version. Components are built from
/// a factory.
///
pub trait ComponentFactory {
///
/// Creates a component that consumes from a particular tree and publishes to a different tree
///
fn create(&self, consumer: ConsumerRef, publisher: PublisherRef) -> ComponentRef;
}
| use std::rc::*;
use std::ops::*;
use super::super::tree::*;
pub type PublisherRef = Box<Publisher>;
pub type ConsumerRef = Box<Consumer>;
///
/// A publisher reports changes to a tree
///
pub trait Publisher {
///
/// Publishes a change to the consumers of this component
///
fn publish(&mut self, change: TreeChange);
}
///
/// Type of a consumer callback function
///
pub type ConsumerCallback = Box<Fn(TreeChange) -> ()>;
///
/// A consumer subscribes to published changes to a tree
///
pub trait Consumer {
///
/// Calls a function whenever a particular section of the tree has changed
///
fn subscribe(&mut self, address: TreeAddress, extent: TreeExtent, callback: ConsumerCallback);
}
///
/// A component consumes a tree and publishes a tree.
///
pub trait Component : Drop {
}
///
/// References to components are used to keep track of the components that are currently active
///
pub type ComponentRef = Rc<Component>;
///
/// A component subscribes consumes a tree and publishes a transformed version. Components are built from
/// a factory.
///
pub trait ComponentFactory {
///
/// Creates a component that consumes from a particular tree and publishes to a different tree
///
fn create(&self, consumer: ConsumerRef, publisher: PublisherRef) -> ComponentRef;
}
|
Replace the Into impl by a From impl | /// `ExpectedVersion` represents the different modes of optimistic locking when writing to a stream
/// using `WriteEventsBuilder`.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ExpectedVersion {
/// No optimistic locking
Any,
/// Expect a stream not to exist
NoStream,
/// Expect exact number of events in the stream
Exact(u32)
}
impl Into<i32> for ExpectedVersion {
/// Returns the wire representation.
fn into(self) -> i32 {
use self::ExpectedVersion::*;
match self {
Any => -2,
NoStream => -1,
Exact(ver) => ver as i32
}
}
}
| /// `ExpectedVersion` represents the different modes of optimistic locking when writing to a stream
/// using `WriteEventsBuilder`.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ExpectedVersion {
/// No optimistic locking
Any,
/// Expect a stream not to exist
NoStream,
/// Expect exact number of events in the stream
Exact(u32)
}
impl From<ExpectedVersion> for i32 {
/// Returns the wire representation.
fn from(version: ExpectedVersion) -> Self {
use self::ExpectedVersion::*;
match version {
Any => -2,
NoStream => -1,
Exact(ver) => ver as i32
}
}
}
|
Add macro_use for the decimal crate. | // Copyright 2013-2014 The Algebra Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Traits for algebra.
#![deny(non_camel_case_types)]
#![deny(unused_parens)]
#![deny(non_upper_case_globals)]
#![deny(unused_results)]
#![deny(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[macro_use]
extern crate approx;
#[cfg(feature = "decimal")]
extern crate decimal;
#[cfg(not(feature = "std"))]
extern crate libm;
extern crate num_complex;
extern crate num_traits as num;
#[cfg(not(feature = "std"))]
use core as std;
#[macro_use]
mod macros;
pub mod general;
pub mod linear;
| // Copyright 2013-2014 The Algebra Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Traits for algebra.
#![deny(non_camel_case_types)]
#![deny(unused_parens)]
#![deny(non_upper_case_globals)]
#![deny(unused_results)]
#![deny(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[macro_use]
extern crate approx;
#[cfg(feature = "decimal")]
#[macro_use]
extern crate decimal;
#[cfg(not(feature = "std"))]
extern crate libm;
extern crate num_complex;
extern crate num_traits as num;
#[cfg(not(feature = "std"))]
use core as std;
#[macro_use]
mod macros;
pub mod general;
pub mod linear;
|
Use the published version of libfuzzer-sys, not git | macro_rules! toml_template {
($name: expr) => {
format_args!(
r##"
[package]
name = "{0}-fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
edition = "2018"
[package.metadata]
cargo-fuzz = true
[dependencies.{0}]
path = ".."
[dependencies.libfuzzer-sys]
git = "https://github.com/rust-fuzz/libfuzzer-sys.git"
# Prevent this from interfering with workspaces
[workspace]
members = ["."]
"##,
$name
)
};
}
macro_rules! toml_bin_template {
($name: expr) => {
format_args!(
r#"
[[bin]]
name = "{0}"
path = "fuzz_targets/{0}.rs"
"#,
$name
)
};
}
macro_rules! gitignore_template {
() => {
format_args!(
r##"
target
corpus
artifacts
"##
)
};
}
macro_rules! target_template {
() => {
format_args!(
r##"#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {{
// fuzzed code goes here
}});
"##
)
};
}
| macro_rules! toml_template {
($name: expr) => {
format_args!(
r##"
[package]
name = "{0}-fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
edition = "2018"
[package.metadata]
cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.2"
[dependencies.{0}]
path = ".."
# Prevent this from interfering with workspaces
[workspace]
members = ["."]
"##,
$name
)
};
}
macro_rules! toml_bin_template {
($name: expr) => {
format_args!(
r#"
[[bin]]
name = "{0}"
path = "fuzz_targets/{0}.rs"
"#,
$name
)
};
}
macro_rules! gitignore_template {
() => {
format_args!(
r##"
target
corpus
artifacts
"##
)
};
}
macro_rules! target_template {
() => {
format_args!(
r##"#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {{
// fuzzed code goes here
}});
"##
)
};
}
|
Add description to theme crate. |
pub use selector::*;
pub use theme::*;
pub mod prelude;
mod selector;
mod theme;
| /*!
This crate provides functions to load a css files as theme and access it properties with
selectors.
This crate depends on the orbtk_utils crate.
# Example
Basic usage of the tree:
```rust,no_run
use orbtk_css_engine::prelude::*;
let mut theme = Theme::create_from_path("theme.css").build();
let selector = Selector::from("button");
let background = theme.brush("background", &selector);
```
*/
pub use selector::*;
pub use theme::*;
pub mod prelude;
mod selector;
mod theme;
|
Use fp64 detection instead of OS blacklist | //! MIPS
// Building this module (even if unused) for non-fp64 targets such as the Sony
// PSP fails with an LLVM error. There doesn't seem to be a good way to detect
// fp64 support as it is sometimes implied by the target cpu, so
// `#[cfg(target_feature = "fp64")]` will unfortunately not work. This is a
// fairly conservative workaround that only disables MSA intrinsics for the PSP.
#[cfg(not(target_os = "psp"))]
mod msa;
#[cfg(not(target_os = "psp"))]
pub use self::msa::*;
#[cfg(test)]
use stdarch_test::assert_instr;
/// Generates the trap instruction `BREAK`
#[cfg_attr(test, assert_instr(break))]
#[inline]
pub unsafe fn break_() -> ! {
crate::intrinsics::abort()
}
| //! MIPS
// Building this module (even if unused) for non-fp64 targets fails with an LLVM
// error.
#[cfg(target_feature = "fp64")]
mod msa;
#[cfg(target_feature = "fp64")]
pub use self::msa::*;
#[cfg(test)]
use stdarch_test::assert_instr;
/// Generates the trap instruction `BREAK`
#[cfg_attr(test, assert_instr(break))]
#[inline]
pub unsafe fn break_() -> ! {
crate::intrinsics::abort()
}
|
Add a couple more benchmarks, add bytes count so that we get more meaningless numbers | #![feature(test)]
extern crate indolentjson;
extern crate test;
use indolentjson::strings::*;
use test::Bencher;
#[bench]
fn noop_escape(b: &mut Bencher) {
b.iter(|| {
escape_bytes(b"test")
});
}
#[bench]
fn escape_controls(b: &mut Bencher) {
b.iter(|| {
escape_bytes(b"\t\n\r\\")
});
}
#[bench]
fn noop_unescape(b: &mut Bencher) {
b.iter(|| {
unescape_bytes(b"test")
});
}
#[bench]
fn unescape_controls(b: &mut Bencher) {
b.iter(|| {
unescape_bytes(br#"\t\n\r\\"#)
});
}
| #![feature(test)]
extern crate indolentjson;
extern crate test;
use indolentjson::strings::*;
use test::{black_box, Bencher};
#[bench]
fn noop_escape(b: &mut Bencher) {
let test_string = black_box(b"test");
b.bytes = test_string.len() as u64;
b.iter(|| { escape_bytes(test_string) });
}
#[bench]
fn escape_controls(b: &mut Bencher) {
let test_string = black_box(b"\t\n\r\\\"");
b.bytes = test_string.len() as u64;
b.iter(|| { escape_bytes(test_string) });
}
#[bench]
fn escape_mixed(b: &mut Bencher) {
let test_string = black_box(
b"This\nIsA\tMixture\x00OfStrings\x0cThat\"Need\\Escaping"
);
b.bytes = test_string.len() as u64;
b.iter(|| { escape_bytes(test_string) });
}
#[bench]
fn noop_unescape(b: &mut Bencher) {
let test_string = black_box(b"test");
b.bytes = test_string.len() as u64;
b.iter(|| { unescape_bytes(test_string) });
}
#[bench]
fn unescape_controls(b: &mut Bencher) {
let test_string = black_box(br#"\t\n\r\\\""#);
b.bytes = test_string.len() as u64;
b.iter(|| { unescape_bytes(test_string) });
}
#[bench]
fn unescape_mixed(b: &mut Bencher) {
let test_string = black_box(
br#"This\nIsA\tMixture\u0000OfStrings\fThat\"Need\\Escaping"#
);
b.bytes = test_string.len() as u64;
b.iter(|| { unescape_bytes(test_string) });
}
|
Use if-let as we only have a binary match | //! Check that functions don't accept an "excessive" number of arguments.
use syntax::ast::{Block, FnDecl, NodeId};
use syntax::codemap::Span;
use syntax::visit::FnKind;
use rustc::lint::{Context, LintArray, LintPass};
const MAX_ARGS_DEFAULT: usize = 6;
const MAX_ARGS_FOR_CLOSURE: usize = 4;
declare_lint!(FN_ARG_LIST_LENGTH, Warn, "Warn about long argument lists");
pub struct Pass;
fn get_max_args_allowed(kind: &FnKind) -> usize {
match kind {
&FnKind::FkFnBlock => MAX_ARGS_FOR_CLOSURE,
_ => MAX_ARGS_DEFAULT
}
}
impl LintPass for Pass {
fn get_lints(&self) -> LintArray {
lint_array!(FN_ARG_LIST_LENGTH)
}
fn check_fn(&mut self, cx: &Context, kind: FnKind, decl: &FnDecl, _: &Block,
span: Span, _: NodeId) {
if decl.inputs.len() > get_max_args_allowed(&kind) {
cx.span_lint(FN_ARG_LIST_LENGTH, span,
"function has an excessive number of arguments");
}
}
}
| //! Check that functions don't accept an "excessive" number of arguments.
use syntax::ast::{Block, FnDecl, NodeId};
use syntax::codemap::Span;
use syntax::visit::FnKind;
use rustc::lint::{Context, LintArray, LintPass};
const MAX_ARGS_DEFAULT: usize = 6;
const MAX_ARGS_FOR_CLOSURE: usize = 4;
declare_lint!(FN_ARG_LIST_LENGTH, Warn, "Warn about long argument lists");
pub struct Pass;
fn get_max_args_allowed(kind: &FnKind) -> usize {
if let &FnKind::FkFnBlock = kind {
MAX_ARGS_FOR_CLOSURE
} else {
MAX_ARGS_DEFAULT
}
}
impl LintPass for Pass {
fn get_lints(&self) -> LintArray {
lint_array!(FN_ARG_LIST_LENGTH)
}
fn check_fn(&mut self, cx: &Context, kind: FnKind, decl: &FnDecl, _: &Block,
span: Span, _: NodeId) {
if decl.inputs.len() > get_max_args_allowed(&kind) {
cx.span_lint(FN_ARG_LIST_LENGTH, span,
"function has an excessive number of arguments");
}
}
}
|
Revert "Changed implementation to be based on shuffled list" | use std::rand;
use std::rand::Rng;
fn main() {
println("Secret Santa");
let names = ~["Angus", "Greg", "Lewis", "Mike", "Isabel", "Rob", "Shannon", "Allan"];
let pairings = secret_santa(&names);
print_pairings(&pairings);
}
fn secret_santa<'r>(names: &~[&'r str]) -> ~[(&'r str,&'r str)] {
let mut rng = rand::rng();
let mut shuffled_names = rng.shuffle(names.clone());
println!("Picking pairings from: {:?}", names);
let mut pairs = ~[];
let first = shuffled_names.last().clone();
shuffled_names.unshift(first);
while shuffled_names.len() > 1 {
let chosen = shuffled_names.pop();
let partner = shuffled_names.last().clone();
pairs.push((chosen,partner));
}
return pairs.clone();
}
fn print_pairings(pairings: &~[(&str, &str)]) {
for &pair in pairings.iter() {
println!("{:?} --- is buying for ---> {:?}", pair.first(), pair.second());
}
} | use std::rand;
use std::rand::Rng;
fn main() {
println("Secret Santa");
let names = ~["Angus", "Greg", "Lewis", "Mike", "Isabel", "Rob", "Shannon", "Allan"];
let pairings = secret_santa(&names);
print_pairings(&pairings);
}
fn secret_santa<'r>(names: &~[&'r str]) -> ~[(&'r str,&'r str)] {
let mut rng = rand::rng();
let mut unshuffled_names = names.clone();
let mut shuffled_names = rng.shuffle(names.clone());
println!("Picking pairings from: {:?}", unshuffled_names);
let mut pairs = ~[];
while shuffled_names.len() > 0 {
let chosen = unshuffled_names.pop();
let partner = shuffled_names.pop();
if( chosen == partner ) {
unshuffled_names.push(chosen);
shuffled_names.push(partner);
if(shuffled_names.len() == 1) {
break;
}
rng.shuffle_mut(shuffled_names);
loop;
}
pairs.push((chosen,partner));
}
if(shuffled_names.len() == 1) {
println("Restarting - no good solution.");
secret_santa(names);
}
return pairs.clone();
}
fn print_pairings(pairings: &~[(&str, &str)]) {
for &pair in pairings.iter() {
println!("{:?} --- is buying for ---> {:?}", pair.first(), pair.second());
}
} |
Disable backtrace test on miri | #[rustversion::not(nightly)]
#[ignore]
#[test]
fn test_backtrace() {}
#[rustversion::nightly]
#[test]
fn test_backtrace() {
use anyhow::anyhow;
let error = anyhow!("oh no!");
let _ = error.backtrace();
}
| #![cfg(not(miri))]
#[rustversion::not(nightly)]
#[ignore]
#[test]
fn test_backtrace() {}
#[rustversion::nightly]
#[test]
fn test_backtrace() {
use anyhow::anyhow;
let error = anyhow!("oh no!");
let _ = error.backtrace();
}
|
Change the test not to rely on internals. | // ignore-windows: Concurrency on Windows is not supported yet.
//! Check that destructors of the library thread locals are executed immediately
//! after a thread terminates.
//!
//! FIXME: We should have a similar test for thread-local statics (statics
//! annotated with `#[thread_local]`) once they support destructors.
#![feature(thread_local_internals)]
use std::cell::RefCell;
use std::thread;
struct TestCell {
value: RefCell<u8>,
}
impl Drop for TestCell {
fn drop(&mut self) {
println!("Dropping: {}", self.value.borrow())
}
}
static A: std::thread::LocalKey<TestCell> = {
#[inline]
fn __init() -> TestCell {
TestCell { value: RefCell::new(0) }
}
unsafe fn __getit() -> Option<&'static TestCell> {
static __KEY: std::thread::__OsLocalKeyInner<TestCell> =
std::thread::__OsLocalKeyInner::new();
__KEY.get(__init)
}
unsafe { std::thread::LocalKey::new(__getit) }
};
fn main() {
thread::spawn(|| {
A.with(|f| {
assert_eq!(*f.value.borrow(), 0);
*f.value.borrow_mut() = 5;
});
})
.join()
.unwrap();
println!("Continue main.")
}
| // ignore-windows: Concurrency on Windows is not supported yet.
//! Check that destructors of the library thread locals are executed immediately
//! after a thread terminates.
use std::cell::RefCell;
use std::thread;
struct TestCell {
value: RefCell<u8>,
}
impl Drop for TestCell {
fn drop(&mut self) {
println!("Dropping: {}", self.value.borrow())
}
}
thread_local! {
static A: TestCell = TestCell { value: RefCell::new(0) };
}
fn main() {
thread::spawn(|| {
A.with(|f| {
assert_eq!(*f.value.borrow(), 0);
*f.value.borrow_mut() = 5;
});
})
.join()
.unwrap();
println!("Continue main.")
}
|
Prepare for upcoming public Codes enum | extern crate hyper;
extern crate json;
mod request;
mod response;
pub use request::Request;
pub use response::Response;
pub type Result = hyper::Result<Response>;
pub type Error = hyper::error::Error;
pub fn get(url: &str) -> Result {
Request::default().get(url)
}
pub fn post(url: &str) -> Result {
Request::default().post(url)
}
pub fn put(url: &str) -> Result {
Request::default().put(url)
}
pub fn head(url: &str) -> Result {
Request::default().head(url)
}
pub fn delete(url: &str) -> Result {
Request::default().delete(url)
}
| extern crate hyper;
extern crate json;
mod request;
mod response;
pub use request::Request;
pub use response::Response;
pub use response::Codes;
pub type Result = hyper::Result<Response>;
pub type Error = hyper::error::Error;
pub fn get(url: &str) -> Result {
Request::default().get(url)
}
pub fn post(url: &str) -> Result {
Request::default().post(url)
}
pub fn put(url: &str) -> Result {
Request::default().put(url)
}
pub fn head(url: &str) -> Result {
Request::default().head(url)
}
pub fn delete(url: &str) -> Result {
Request::default().delete(url)
}
|
Add hamming distance and test cases | use primal_bit::BitVec;
pub struct BehavioralBitvec {
bitvec: BitVec,
bitpos: usize,
}
impl BehavioralBitvec {
pub fn new(n: usize) -> Self {
BehavioralBitvec {
bitvec: BitVec::from_elem(n, false),
bitpos: 0,
}
}
#[inline]
pub fn push(&mut self, output: f64) {
if output >= 0.0 {
self.bitvec.set(self.bitpos, true);
}
self.bitpos += 1;
}
}
| use primal_bit::BitVec;
use hamming;
pub struct BehavioralBitvec {
bitvec: BitVec,
bitpos: usize,
}
impl BehavioralBitvec {
pub fn new(n: usize) -> Self {
BehavioralBitvec {
bitvec: BitVec::from_elem(n, false),
bitpos: 0,
}
}
pub fn hamming_distance(&self, other: &Self) -> u64 {
hamming::distance_fast(self.bitvec.as_bytes(), other.bitvec.as_bytes()).unwrap()
}
#[inline]
pub fn push(&mut self, output: f64) {
if output >= 0.0 {
self.bitvec.set(self.bitpos, true);
}
self.bitpos += 1;
}
}
#[test]
fn test_behavioral_bitvec() {
let mut a = BehavioralBitvec::new(3);
let mut b = BehavioralBitvec::new(3);
// [1, 1, 0]
a.push(1.0);
a.push(2.0);
a.push(-1.0);
let ba: Vec<_> = a.bitvec.iter().collect();
// [0, 1, 1]
b.push(-1.0);
b.push(1.0);
b.push(1.0);
let bb: Vec<_> = b.bitvec.iter().collect();
assert_eq!(vec![true, true, false], ba);
assert_eq!(vec![false, true, true], bb);
let d1 = a.hamming_distance(&b);
let d2 = b.hamming_distance(&a);
assert_eq!(d1, d2);
assert_eq!(2, d1);
}
|
Change process keep alive mechanism | use std::env;
use tougou_bot::commands::{ pic::PicCommand, ping::PingCommand, status::StatusCommand };
use tougou_bot::discord_client::*;
fn main() {
let token: String =
env::var("DISCORD_TOKEN").expect("Must set the environment variable `DISCORD_TOKEN`");
let client = serenity_discord_client::SerenityDiscordClient::new(&token);
client.register_command("pic", PicCommand).unwrap();
client.register_command("ping", PingCommand).unwrap();
client.register_command("status", StatusCommand).unwrap();
let mut temp = String::new();
std::io::stdin()
.read_line(&mut temp)
.expect("failed to read from console");
}
| use std::env;
use std::sync::{ Condvar, Mutex };
use tougou_bot::commands::{ pic::PicCommand, ping::PingCommand, status::StatusCommand };
use tougou_bot::discord_client::*;
fn main() {
let token: String =
env::var("DISCORD_TOKEN").expect("Must set the environment variable `DISCORD_TOKEN`");
let client = serenity_discord_client::SerenityDiscordClient::new(&token);
client.register_command("pic", PicCommand).unwrap();
client.register_command("ping", PingCommand).unwrap();
client.register_command("status", StatusCommand).unwrap();
let keep_alive = Condvar::new();
let keep_alive_lock = Mutex::new(false);
let _ = keep_alive.wait(keep_alive_lock.lock().unwrap()).expect("keep alive lock failed");
}
|
Implement unit tests for the trim lines fn | use std::io::{BufRead, Error};
pub fn read_and_trim_lines<T: BufRead>(buffered_reader: T) -> Result<Vec<String>, Error> {
buffered_reader
.lines()
.map(|r| Ok(crate::utils::trim_end_inplace(r?)))
.collect()
}
| use std::io::{BufRead, Error};
pub fn read_and_trim_lines<T: BufRead>(buffered_reader: T) -> Result<Vec<String>, Error> {
buffered_reader
.lines()
.map(|r| Ok(crate::utils::trim_end_inplace(r?)))
.collect()
}
// LCOV_EXCL_START
#[cfg(test)]
mod tests {
#[cfg(test)]
mod read_and_trim_lines_test {
use super::super::read_and_trim_lines;
use std::io::BufReader;
#[test]
fn valid_string() {
let input = "\tfoo\nbar \n qux\t\n \t\n";
let res = read_and_trim_lines(BufReader::new(input.as_bytes()));
assert!(res.is_ok());
let res_unwrapped = res.unwrap();
assert_eq!(res_unwrapped.len(), 4);
for (actual, expected) in res_unwrapped.iter().zip(vec!["\tfoo", "bar", " qux", ""]) {
assert_eq!(actual, expected);
}
}
#[test]
fn invalid_utf8_string() {
let input = b"\xe2\x28\xa1";
let res = read_and_trim_lines(BufReader::new(input.as_ref()));
assert!(res.is_err());
}
}
}
// LCOV_EXCL_STOP
|
Use hash function to consume all input at once. | extern crate identicon;
extern crate openssl;
extern crate test;
use openssl::crypto::hash::{Hasher, HashType};
use test::Bencher;
use identicon::Identicon;
#[bench]
fn generate(x: &mut Bencher) {
let source = String::from_str("42");
let input = source.as_bytes();
x.iter(|| {
let mut hash = Hasher::new(HashType::MD5);
hash.update(input);
let bytes = hash.finalize();
Identicon::new(&bytes[0..]).image();
});
}
| extern crate identicon;
extern crate openssl;
extern crate test;
use openssl::crypto::hash::{hash, Type};
use test::Bencher;
use identicon::Identicon;
#[bench]
fn generate(x: &mut Bencher) {
let source = String::from_str("42");
let input = source.as_bytes();
x.iter(|| {
let bytes = hash(Type::MD5, input);
Identicon::new(&bytes[0..]).image();
});
}
|
Simplify solution, use `loop` for endless loop | use std::env;
#[allow(while_true)]
fn main() {
let args: Vec<String> = env::args().collect();
match args.len() {
1 => {
while true {
println!("y");
}
},
_ => {
while true {
println!("{}", args[1]);
}
},
}
}
| use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let args = &args[1..];
let output = if args.is_empty() { "y".to_string() } else { args.join(" ") };
loop {
println!("{}", output)
}
}
|
Enable accidentally deleted v3 tests | #![cfg(test)]
extern crate protobuf;
extern crate protobuf_test_common;
#[cfg(feature = "with-bytes")]
extern crate bytes;
mod v2;
// `cfg(proto3)` is emitted by `build.rs`
#[cfg(proto3)]
mod v3;
mod common;
#[cfg(proto3)]
mod google;
mod interop;
mod include_generated;
| #![cfg(test)]
extern crate protobuf;
extern crate protobuf_test_common;
#[cfg(feature = "with-bytes")]
extern crate bytes;
mod v2;
mod v3;
mod common;
mod google;
mod interop;
mod include_generated;
|
Make example closer to docs | /**
* Copyright 2021 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
extern crate wasm_bindgen_rayon;
use rayon::prelude::*;
use wasm_bindgen::prelude::*;
// While this is a primitive test, it already requires Rayon to be spawned
// correctly, send tasks to different threads and collect the results back -
// which is all that we need to verify.
#[wasm_bindgen]
pub fn sum(numbers: &[i32]) -> i32 {
numbers.par_iter().sum()
}
| /**
* Copyright 2021 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pub use wasm_bindgen_rayon::init_thread_pool;
use rayon::prelude::*;
use wasm_bindgen::prelude::*;
// While this is a primitive test, it already requires Rayon to be spawned
// correctly, send tasks to different threads and collect the results back -
// which is all that we need to verify.
#[wasm_bindgen]
pub fn sum(numbers: &[i32]) -> i32 {
numbers.par_iter().sum()
}
|
Update to use path module correctly | use std::process::Command;
use std::env;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
// Invoke ISPC to compile our code
let ispc_status = Command::new("ispc").args(&["src/say_hello.ispc", "--pic", "-o"])
.arg(&format!("{}/say_hello.o", out_dir))
.status().unwrap();
if !ispc_status.success() {
panic!("ISPC compilation failed");
}
// Place our code into a static library we can link against
let link_status = Command::new("ar").args(&["crus", "libsay_hello.a", "say_hello.o"])
.current_dir(&Path::new(&out_dir))
.status().unwrap();
if !link_status.success() {
panic!("Linking ISPC code into archive failed");
}
println!("cargo:rustc-flags=-L native={}", out_dir);
}
| use std::path::Path;
use std::process::Command;
use std::env;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let debug = env::var("DEBUG").unwrap();
let mut ispc_args = vec!["src/say_hello.ispc", "--pic"];
if debug == "true" {
ispc_args.push("-g");
}
// Invoke ISPC to compile our code
let ispc_status = Command::new("ispc").args(&ispc_args[..])
.args(&["-o", &format!("{}/say_hello.o", out_dir)])
.status().unwrap();
if !ispc_status.success() {
panic!("ISPC compilation failed");
}
// Place our code into a static library we can link against
let link_status = Command::new("ar").args(&["crus", "libsay_hello.a", "say_hello.o"])
.current_dir(&Path::new(&out_dir))
.status().unwrap();
if !link_status.success() {
panic!("Linking ISPC code into archive failed");
}
println!("cargo:rustc-flags=-L native={}", out_dir);
}
|
Move ForkTable rustdoc to the correct place | #![crate_name = "seax_scheme"]
#![crate_type = "lib"]
#![feature(convert,core,box_syntax,box_patterns)]
#[macro_use]
extern crate seax_svm as svm;
pub mod ast;
/// Contains the Scheme parser.
///
/// This parser is based on the
/// [Scheme grammar](final/html/r6rs/r6rs-Z-H-7.html) given in the
/// [Revised<sup>6</sup> Report on Scheme](http://www.r6rs.org/) (R<sup>6</sup>RS).
/// Any deviations from the R6RS standard, especially those with an impact
/// on the valid programs accepted by the parser, will be noted in the
/// parser's RustDoc.
pub mod parser;
mod forktab;
/// An associative map data structure for representing scopes.
///
/// A `ForkTable` functions similarly to a standard associative map
/// data structure (such as a `HashMap`), but with the ability to
/// fork children off of each level of the map. If a key exists in any
/// of a child's parents, the child will 'pass through' that key. If a
/// new value is bound to a key in a child level, that child will overwrite
/// the previous entry with the new one, but the previous `key` -> `value`
/// mapping will remain in the level it is defined. This means that the parent
/// level will still provide the previous value for that key.
///
/// This is an implementation of the ForkTable data structure for
/// representing scopes. The ForkTable was initially described by
/// Max Clive. This implemention is based primarily by the Scala
/// reference implementation written by Hawk Weisman for the Decaf
/// compiler, which is available [here](https://github.com/hawkw/decaf/blob/master/src/main/scala/com/meteorcode/common/ForkTable.scala).
pub use self::forktab::ForkTable;
| #![crate_name = "seax_scheme"]
#![crate_type = "lib"]
#![feature(convert,core,box_syntax,box_patterns)]
#[macro_use]
extern crate seax_svm as svm;
pub mod ast;
/// Contains the Scheme parser.
///
/// This parser is based on the
/// [Scheme grammar](final/html/r6rs/r6rs-Z-H-7.html) given in the
/// [Revised<sup>6</sup> Report on Scheme](http://www.r6rs.org/) (R<sup>6</sup>RS).
/// Any deviations from the R6RS standard, especially those with an impact
/// on the valid programs accepted by the parser, will be noted in the
/// parser's RustDoc.
pub mod parser;
mod forktab;
pub use self::forktab::ForkTable;
|
Add test of an interpolated expression | use std::fmt::Display;
use thiserror::Error;
#[derive(Error, Debug)]
#[error("braced error: {msg}")]
struct BracedError {
msg: String,
}
#[derive(Error, Debug)]
#[error("braced error")]
struct BracedUnused {
extra: usize,
}
#[derive(Error, Debug)]
#[error("tuple error: {0}")]
struct TupleError(usize);
#[derive(Error, Debug)]
#[error("unit error")]
struct UnitError;
#[derive(Error, Debug)]
enum EnumError {
#[error("braced error: {id}")]
Braced { id: usize, },
#[error("tuple error: {0}")]
Tuple(usize),
#[error("unit error")]
Unit,
}
fn assert<T: Display>(expected: &str, value: T) {
assert_eq!(expected, value.to_string());
}
#[test]
fn test_display() {
assert(
"braced error: T",
BracedError {
msg: "T".to_owned(),
},
);
assert("braced error", BracedUnused { extra: 0 });
assert("tuple error: 0", TupleError(0));
assert("unit error", UnitError);
assert("braced error: 0", EnumError::Braced { id: 0 });
assert("tuple error: 0", EnumError::Tuple(0));
assert("unit error", EnumError::Unit);
}
| use std::fmt::Display;
use thiserror::Error;
#[derive(Error, Debug)]
#[error("braced error: {msg}")]
struct BracedError {
msg: String,
}
#[derive(Error, Debug)]
#[error("braced error")]
struct BracedUnused {
extra: usize,
}
#[derive(Error, Debug)]
#[error("tuple error: {0}")]
struct TupleError(usize);
#[derive(Error, Debug)]
#[error("unit error")]
struct UnitError;
#[derive(Error, Debug)]
enum EnumError {
#[error("braced error: {id}")]
Braced { id: usize, },
#[error("tuple error: {0}")]
Tuple(usize),
#[error("unit error")]
Unit,
}
#[derive(Error, Debug)]
#[error("1 + 1 = {}", 1 + 1)]
struct Arithmetic;
fn assert<T: Display>(expected: &str, value: T) {
assert_eq!(expected, value.to_string());
}
#[test]
fn test_display() {
assert(
"braced error: T",
BracedError {
msg: "T".to_owned(),
},
);
assert("braced error", BracedUnused { extra: 0 });
assert("tuple error: 0", TupleError(0));
assert("unit error", UnitError);
assert("braced error: 0", EnumError::Braced { id: 0 });
assert("tuple error: 0", EnumError::Tuple(0));
assert("unit error", EnumError::Unit);
assert("1 + 1 = 2", Arithmetic);
}
|
Use clippy plugin only on nightly | extern crate flate2;
extern crate regex;
extern crate tar;
extern crate time;
#[macro_use]
extern crate try_opt;
mod macros;
mod time_utils;
pub mod backend;
pub mod collections;
pub mod signatures;
| #![cfg_attr(unstable, feature(plugin))]
#![cfg_attr(unstable, plugin(clippy))]
extern crate flate2;
extern crate regex;
extern crate tar;
extern crate time;
#[macro_use]
extern crate try_opt;
mod macros;
mod time_utils;
pub mod backend;
pub mod collections;
pub mod signatures;
|
Adjust default config to use the new split configs | use std::io::prelude::*;
use std::path::Path;
use std::fs::{File, create_dir};
fn main() {
let dst = Path::new(concat!(env!("HOME"), "/.xr3wm/config.rs"));
if !dst.exists() {
match create_dir(dst.parent().unwrap()) {
Ok(_) => {
let mut f = File::create(&dst).unwrap();
f.write_all(b"#![allow(unused_imports)]
extern crate xr3wm;
use std::default::Default;
use xr3wm::core::*;
#[no_mangle]
pub extern fn configure(cfg: &mut Config, ws_cfg_list: &mut Vec<WorkspaceConfig>) {
}").unwrap();
}
Err(msg) => {
panic!("Failed to create config directory: {}", msg);
}
}
}
}
| use std::io::prelude::*;
use std::path::Path;
use std::fs::{File, create_dir};
fn main() {
let dst = Path::new(concat!(env!("HOME"), "/.xr3wm/config.rs"));
if !dst.exists() {
match create_dir(dst.parent().unwrap()) {
Ok(_) => {
let mut f = File::create(&dst).unwrap();
f.write_all(b"#![allow(unused_imports)]
extern crate xr3wm;
use std::default::Default;
use xr3wm::core::*;
use xr3wm::layout::*;
#[no_mangle]
pub extern fn configure_workspaces() -> Vec<WorkspaceConfig> {
(1usize..10)
.map(|idx| {
WorkspaceConfig {
tag: idx.to_string(),
screen: 0,
layout: Strut::new(Choose::new(vec![Tall::new(1, 0.5, 0.05), Rotate::new(Tall::new(1, 0.5, 0.05)), Full::new()])),
}
})
.collect()
}
#[no_mangle]
pub extern fn configure_wm() -> Config {
let mut cfg: Config = Default::default();
cfg
}").unwrap();
}
Err(msg) => {
panic!("Failed to create config directory: {}", msg);
}
}
}
}
|
Switch from f64 to f32 | // 单元结构体
struct Nil;
// 元组结构体
struct Pair(i32, f64);
// 带有两个字段的结构体
struct Point {
x: f64,
y: f64,
}
// 结构体可以作为另一个结构体的字段
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn main() {
// 实例化结构体 `Point`
let point: Point = Point { x: 0.3, y: 0.4 };
// 访问 point 的字段
println!("point coordinates: ({}, {})", point.x, point.y);
// 使用 `let` 绑定来解构 point
let Point { x: my_x, y: my_y } = point;
let _rectangle = Rectangle {
// 结构体的实例化也是一个表达式
p1: Point { x: my_y, y: my_x },
p2: point,
};
// 实例化一个单元结构体
let _nil = Nil;
// 实例化一个元组结构体
let pair = Pair(1, 0.1);
// 解构一个元组结构体
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
}
| // 单元结构体
struct Nil;
// 元组结构体
struct Pair(i32, f32);
// 带有两个字段的结构体
struct Point {
x: f32,
y: f32,
}
// 结构体可以作为另一个结构体的字段
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn main() {
// 实例化结构体 `Point`
let point: Point = Point { x: 0.3, y: 0.4 };
// 访问 point 的字段
println!("point coordinates: ({}, {})", point.x, point.y);
// 使用 `let` 绑定来解构 point
let Point { x: my_x, y: my_y } = point;
let _rectangle = Rectangle {
// 结构体的实例化也是一个表达式
p1: Point { x: my_y, y: my_x },
p2: point,
};
// 实例化一个单元结构体
let _nil = Nil;
// 实例化一个元组结构体
let pair = Pair(1, 0.1);
// 解构一个元组结构体
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.