blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
140
| path
stringlengths 5
183
| src_encoding
stringclasses 6
values | length_bytes
int64 12
5.32M
| score
float64 2.52
4.94
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 12
5.32M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
e85788c6cf19875366b4425c33ddf3bcc263d02c
|
Rust
|
edgardSchi/rust-chess
|
/src/main.rs
|
UTF-8
| 4,494 | 3.5625 | 4 |
[] |
no_license
|
extern crate pleco;
use rand::Rng;
use pleco::{Board};
enum StartColor {
White,
Black
}
enum PlayMode {
Human,
Computer
}
enum TurnEnt {
Human,
Computer
}
fn main() {
match start_menu() {
PlayMode::Computer => {computer_game();}
PlayMode::Human => {human_game();}
}
}
//Menu for choosing if the user wants to play against a computer or human
fn start_menu() -> PlayMode {
println!("Play against a human or computer? [1/2]");
println!("1) Computer");
println!("2) Human");
let mut player_input = String::new();
std::io::stdin().read_line(&mut player_input).unwrap();
match player_input.trim_end() {
"1" => PlayMode::Computer,
"2" => PlayMode::Human,
_ => {
println!("Invalid option!");
start_menu()
}
}
}
//Menu for choosing which color the user wants to play as
fn color_menu() -> StartColor {
println!("What color do you want to play? [w/b]");
let mut player_input = String::new();
std::io::stdin().read_line(&mut player_input).unwrap();
match player_input.trim_end() {
"w" => StartColor::White,
"b" => StartColor::Black,
_ => {
println!("Invalid option!");
color_menu()
}
}
}
//Query move from user
fn query_move() -> String {
println!("Your move: ");
let mut player_input = String::new();
std::io::stdin().read_line(&mut player_input).unwrap();
player_input.trim_end().to_lowercase()
}
//start a computer game
fn computer_game() {
let start_color = color_menu();
let mut board = Board::start_pos();
print_board(&board.fen());
match start_color {
StartColor::White => {
while true {
if make_move(&mut board, TurnEnt::Human) {break};
if make_move(&mut board, TurnEnt::Computer) {break};
}
}
StartColor::Black => {
while true {
if make_move(&mut board, TurnEnt::Computer) {break};
if make_move(&mut board, TurnEnt::Human) {break};
}
}
}
}
//start a game with two humans
fn human_game() {
let mut board = Board::start_pos();
print_board(&board.fen());
while true {
if make_move(&mut board, TurnEnt::Human) {break}
if make_move(&mut board, TurnEnt::Human) {break}
}
}
//Check if a player won or a stalemate was achieved
fn check_winning_conditions(board : &mut Board) -> bool {
if board.stalemate() {
println!("Stalemate!");
true
} else if board.checkmate() {
println!("Checkmate! {} won!", board.turn().other_player());
true
} else {
false
}
}
//Make a move based on the current player
fn make_move(board : &mut Board, entity : TurnEnt) -> bool {
println!("Current player: {}", board.turn());
match entity {
TurnEnt::Computer => {computer_move(board);}
TurnEnt::Human => {
let player_move = query_move();
let mut success = board.apply_uci_move(&player_move);
while !success {
println!("Invalid move!");
success = board.apply_uci_move(&query_move());
}
}
}
print_board(&board.fen());
check_winning_conditions(board)
}
//Let the computer make a move (right now only a random valid move)
fn computer_move(board : &mut Board) {
let moves = board.generate_moves();
let vec_moves = moves.vec();
let mut rng = rand::thread_rng();
let rand = rng.gen_range(0..vec_moves.len());
board.apply_move(vec_moves[rand]);
println!("Computer move: {}", vec_moves[rand].stringify());
print_board(&board.fen());
}
//Print the board to the console
fn print_board(position : &str) {
let mut rows : Vec<&str> = position.split("/").collect();
let temp : Vec<&str> = rows[7].split(" ").collect();
rows[7] = temp[0];
let mut i = 8;
println!("");
for s in rows {
print!("{} ", i);
i -= 1;
for c in s.chars() {
match c {
'0'..='9' => {
let n = c.to_digit(10).unwrap();
for i in 0..n {
print!(" -");
}
}
_ => {
print!(" {}", c);
}
}
}
print!("\n");
}
println!("\n a b c d e f g h \n");
}
| true |
af267604387221bcba285ca213d00b490fc6b0fb
|
Rust
|
okard/rust-playground
|
/storage/tests/test_storage_mem.rs
|
UTF-8
| 2,532 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
extern crate storage;
use storage::{KeyValueStorage, ContentStorage, MemoryStorage, ReadHandle, WriteHandle};
#[test]
fn simple_mem_storage()
{
let mut storage = MemoryStorage::new();
let mut storage : &mut KeyValueStorage = &mut storage;
//insert via slice
let mut key = &mut ReadHandle::Slice("test".as_bytes());
let r = storage.put(&mut key, &mut ReadHandle::Slice("hello world".as_bytes()));
assert!(r.is_ok());
//read via Write trait
let mut value : Vec<u8> = Vec::new();
let r = storage.get(&mut key, &mut WriteHandle::Writer(&mut value, None));
assert!(r.is_ok());
assert_eq!(&value[..], "hello world".as_bytes());
//read via slice
let mut value = [0u8; 11];
let r = storage.get(&mut key, &mut WriteHandle::Slice(&mut value));
println!("{:?}", r);
assert!(r.is_ok());
assert_eq!(&value, "hello world".as_bytes());
}
#[test]
fn insert_via_reader()
{
use std::io::{Cursor, Seek, SeekFrom};
let mut storage = MemoryStorage::new();
let mut storage : &mut KeyValueStorage = &mut storage;
//insert via reader without size limit
let mut key_source = &mut Cursor::new("test".as_bytes());
let mut value_source = &mut Cursor::new("hello world".as_bytes());
{
let mut key = &mut ReadHandle::Reader(&mut key_source, None);
let mut value = &mut ReadHandle::Reader(&mut value_source, None);
let r = storage.put(&mut key, &mut value);
assert!(r.is_ok());
}
//check written value
let r = key_source.seek(SeekFrom::Start(0)); //reset cursor
assert!(r.is_ok() && r.unwrap() == 0);
{
let mut value : Vec<u8> = Vec::new();
let mut key = &mut ReadHandle::Reader(&mut key_source, None);
let r = storage.get(&mut key, &mut WriteHandle::Writer(&mut value, None));
assert!(r.is_ok());
assert_eq!(&value[..], "hello world".as_bytes());
}
}
#[test]
fn content_storage()
{
use std::io::{Cursor};
let mut storage = MemoryStorage::new();
let mut storage : &mut ContentStorage = &mut storage;
//insert via reader without size limit
let mut content_source = &mut Cursor::new("hello world".as_bytes());
let mut key : Vec<u8> = Vec::new();
let r = storage.put(&mut ReadHandle::Reader(&mut content_source, None), &mut WriteHandle::Writer(&mut key, None));
assert!(r.is_ok());
{
let mut content : Vec<u8> = Vec::new();
let mut key = &mut Cursor::new(&key[..]);
let mut key = &mut ReadHandle::Reader(&mut key, None);
let r = storage.get(&mut key, &mut WriteHandle::Writer(&mut content, None));
assert!(r.is_ok());
assert_eq!(&content[..], "hello world".as_bytes());
}
}
| true |
6d85a5ada212c52becef721fce2f2ed7e5e24d78
|
Rust
|
malikolivier/yl
|
/rust/src/lib.rs
|
UTF-8
| 2,502 | 3.375 | 3 |
[
"BSD-3-Clause-Clear"
] |
permissive
|
use std::io;
use std::io::BufRead;
use std::io::Read;
use std::io::Write;
use std::fs;
mod interpreter;
mod parser;
pub fn is_interactive(args: &[String]) -> bool {
args.len() <= 1
}
fn usage() {
println!("yl [-e \"Inline code\"] [file]");
}
#[derive(Debug)]
pub enum YlError {
Message(&'static str),
Io(io::Error),
}
pub fn get_code(args: &[String]) -> Result<String, YlError> {
debug_assert!(args.len() >= 2);
match args[1].as_ref() {
"-e" => {
if args.len() <= 2 {
usage();
return Err(YlError::Message("Not enough arguments"))
} else {
Ok(args[2].clone())
}
},
_ => {
let mut f = try!(fs::File::open(&args[1]).map_err(YlError::Io));
let mut code = String::new();
try!(f.read_to_string(&mut code).map_err(YlError::Io));
Ok(code)
}
}
}
fn write_prompt() -> Result<(), io::Error> {
print!("> ");
io::stdout().flush()
}
pub fn run_prompt() -> Result<(), Box<io::Error>> {
let scope = interpreter::Scope::global();
write_prompt()?;
let stdin = io::stdin();
for line in stdin.lock().lines() {
let ast = parser::parse(&line?);
let ret = scope.evaluate(&ast, false);
interpreter::print(&ret);
write_prompt()?;
}
Ok(())
}
pub fn evaluate_code_with_exit_status(code: String) -> i32 {
let ast = parser::parse(&code);
let scope = interpreter::Scope::global();
let ret = scope.evaluate(&ast, true);
match ret {
interpreter::Var::Num(n) => n as i32,
_ => 0,
}
}
#[cfg(test)]
mod get_code {
use super::get_code;
#[test]
fn from_cli() {
let args = vec!["yl".to_string(),
"-e".to_string(),
"(code)".to_string()];
assert_eq!(
get_code(&args).unwrap(),
"(code)"
);
}
#[test]
fn from_file() {
let args = vec!["yl".to_string(),
"../test/argv.yl".to_string()];
assert_eq!(
get_code(&args).unwrap(),
"(print (argv 0))\n"
);
}
#[test]
fn from_non_existing_file() {
let args = vec!["yl".to_string(),
"I DON'T EXIST.yl".to_string()];
assert!(
match get_code(&args) {
Ok(_) => false,
Err(_) => true,
}
);
}
}
| true |
3bf78636cc3f6dd89a87cb9bed741a6d2f1fd51c
|
Rust
|
flegac/rust-mcts
|
/mini-nn/src/algo/mutations/add_mut.rs
|
UTF-8
| 987 | 3.078125 | 3 |
[] |
no_license
|
use rand_distr::Distribution;
use rand_distr::Normal;
use tensor_lib::tensor::Tensor;
use tensor_lib::traits::view::View;
use crate::algo::mutation::Mutation;
use rand::distributions::Uniform;
pub struct AddMut {
pub power: f32
}
impl AddMut {
pub fn new(power: f32) -> Self {
AddMut { power }
}
}
impl Mutation<Tensor> for AddMut {
fn mutate(&self, m: &mut Tensor) {
let mut rng = rand::thread_rng();
let normal = Normal::new(0.0, 1.0).unwrap();
let offset = Uniform::new(0, m.shape().len()).sample(&mut rng);
let r = normal.sample(&mut rng);
let x = m.get(offset) + r * self.power;
m.insert(offset, x);
// let normal = Normal::new(0.0, 1.0).unwrap();
// for i in 0..adn.shape().len() {
// let r = normal.sample(&mut rng);
// if r > 0.0 {
// let x = adn.get(i) + self.power;
// adn.insert(i, x);
// }
// }
}
}
| true |
547dc30cde13eaed638c930c1140f9ea42fd79da
|
Rust
|
irevoire/aoc2018
|
/day8/src/bin/stats.rs
|
UTF-8
| 371 | 2.953125 | 3 |
[] |
no_license
|
use aoc::*;
use day8::*;
fn main() {
let data: Vec<usize> = parser::input::<String>()
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();
let tree = Node::parse(&data).0;
let depth = tree.depth();
let size = tree.size();
answer!("Your tree has a depth of {}.", depth);
answer!("It contains {} nodes.", size);
}
| true |
0a6c2b031a40facb96a5c53be39975ecdbaba550
|
Rust
|
cbarrete/keyell
|
/src/types/vec3.rs
|
UTF-8
| 2,534 | 3.46875 | 3 |
[] |
no_license
|
use rand::{thread_rng, Rng};
use std::ops::{Add, Div, Mul, Neg, Sub};
#[derive(Clone, Debug, PartialEq)]
pub struct Vec3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Vec3 {
pub fn new(x: f64, y: f64, z: f64) -> Self {
Self { x, y, z }
}
pub fn len(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2) + self.z.powi(2)).sqrt()
}
pub fn unit(&self) -> UnitVec3 {
UnitVec3(self / self.len())
}
}
#[derive(Clone)]
pub struct UnitVec3(Vec3);
impl UnitVec3 {
pub fn unchecked_from(v: &Vec3) -> Self {
Self(v.clone())
}
pub fn get(&self) -> &Vec3 {
&self.0
}
pub fn random() -> Self {
let mut rng = thread_rng();
let random_vector = Vec3 {
x: rng.gen_range(-1., 1.),
y: rng.gen_range(-1., 1.),
z: rng.gen_range(-1., 1.),
};
random_vector.unit()
}
}
impl Neg for &UnitVec3 {
type Output = UnitVec3;
fn neg(self) -> Self::Output {
UnitVec3(-self.0.clone())
}
}
macro_rules! vecs_ops {
($t1:ty, $t2:ty) => {
impl Add<$t2> for $t1 {
type Output = Vec3;
fn add(self, rhs: $t2) -> Self::Output {
Self::Output {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
}
}
}
impl Sub<$t2> for $t1 {
type Output = Vec3;
fn sub(self, rhs: $t2) -> Self::Output {
Self::Output {
x: self.x - rhs.x,
y: self.y - rhs.y,
z: self.z - rhs.z,
}
}
}
};
}
vecs_ops!(Vec3, Vec3);
vecs_ops!(&Vec3, Vec3);
vecs_ops!(Vec3, &Vec3);
vecs_ops!(&Vec3, &Vec3);
macro_rules! f64_ops {
($t:ty) => {
impl Mul<$t> for f64 {
type Output = Vec3;
fn mul(self, rhs: $t) -> Self::Output {
Self::Output {
x: self * rhs.x,
y: self * rhs.y,
z: self * rhs.z,
}
}
}
impl Div<f64> for $t {
type Output = Vec3;
fn div(self, rhs: f64) -> Self::Output {
(1. / rhs) * self
}
}
impl Neg for $t {
type Output = Vec3;
fn neg(self) -> Self::Output {
-1. * self
}
}
};
}
f64_ops!(Vec3);
f64_ops!(&Vec3);
| true |
0dca45637dc212611b76887945c4efa4b43c1acd
|
Rust
|
bibhas2/scanner
|
/src/lib.rs
|
UTF-8
| 1,924 | 3.921875 | 4 |
[] |
no_license
|
pub struct Scanner<'a> {
chars:std::str::Chars<'a>,
word:String
}
impl <'a> Scanner<'a> {
pub fn new(line : &'a str) -> Scanner {
Scanner {
word: String::new(),
chars: line.chars()
}
}
pub fn next<T>(&mut self) -> Option<T>
where T : std::str::FromStr
{
self.word.truncate(0);
let mut start_mode = true;
//Eat space
loop {
match self.chars.next() {
Some(ch) => {
if ch.is_whitespace() {
if start_mode == true {
continue;
} else {
break;
}
} else {
start_mode = false;
self.word.push(ch);
}
},
None => {
break;
}
}
}
if self.word.len() == 0 {
return None;
}
match self.word.parse::<T>() {
Ok(val) => return Some(val),
_ => return None
}
}
}
#[test]
fn test1() {
let line = " 12 34.56 ";
let mut s = Scanner::new(line);
let i_val:Option<i64> = s.next();
assert!(i_val == Some(12));
let f_val:Option<f64> = s.next();
assert!(f_val == Some(34.56));
let no_val:Option<f64> = s.next();
assert!(no_val == None);
}
#[test]
fn test2() {
let line = " 12 34.56 ";
let mut s = Scanner::new(line);
let f_val:Option<f64> = s.next();
//Integer is parsed as float just fine
assert!(f_val == Some(12.0));
}
#[test]
fn test3() {
let line = " 34.56 ";
let mut s = Scanner::new(line);
let i_val:Option<i64> = s.next();
//Float can not be parsed as Integer
assert!(i_val == None);
}
| true |
a460afa168a99571c617a7d548732d90379ddc41
|
Rust
|
maikelwever/acid-store
|
/src/store/open_store.rs
|
UTF-8
| 1,364 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019-2021 Wren Powell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::store::DataStore;
/// A value which can be used to open a `DataStore`.
pub trait OpenStore {
/// The type of `DataStore` which this value can be used to open.
type Store: DataStore + 'static;
/// Open or create a data store of type `Store`.
///
/// This opens the data store, creating it if it does not already exist.
///
/// # Errors
/// - `Error::UnsupportedStore`: The data store is an unsupported format. This can happen if
/// the serialized data format changed or if the storage represented by this value does not
/// contain a valid data store.
/// - `Error::Store`: An error occurred with the data store.
/// - `Error::Io`: An I/O error occurred.
fn open(&self) -> crate::Result<Self::Store>;
}
| true |
d6a03fb82802e652b6e0bdef96dd7898ad354a37
|
Rust
|
drmason13/exercism-rust-armstrong-numbers
|
/src/lib.rs
|
UTF-8
| 333 | 3.5625 | 4 |
[] |
no_license
|
pub fn is_armstrong_number(num: u32) -> bool {
let num_digits = digits(num);
let mut sum = 0;
let mut temp = num;
while temp > 0 {
let digit = temp % 10;
temp /= 10;
sum += digit.pow(num_digits);
}
sum == num
}
pub fn digits(num: u32) -> u32 {
(num as f32).log10() as u32 + 1
}
| true |
9ac61362afbcb50b6deecfc6e8b0db68f7fb2df9
|
Rust
|
EmbarkStudios/wasmer
|
/lib/interface-types/src/errors.rs
|
UTF-8
| 6,650 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
//! The error module contains all the data structures that represent
//! an error.
use crate::{ast::InterfaceType, interpreter::Instruction};
use std::{
error::Error,
fmt::{self, Display, Formatter},
result::Result,
string::{self, ToString},
};
/// A type alias for instruction's results.
pub type InstructionResult<T> = Result<T, InstructionError>;
/// A type alias for the interpreter result.
pub type InterpreterResult<T> = Result<T, InstructionError>;
/// Structure to represent errors when casting from an `InterfaceType`
/// to a native value.
#[derive(Debug)]
pub struct WasmValueNativeCastError {
/// The initial type.
pub from: InterfaceType,
/// The targeted type.
///
/// `InterfaceType` is used to represent the native type by
/// associativity.
pub to: InterfaceType,
}
impl Error for WasmValueNativeCastError {}
impl Display for WasmValueNativeCastError {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
write!(formatter, "{:?}", self)
}
}
/// Structure to represent the errors for instructions.
#[derive(Debug)]
pub struct InstructionError {
/// The instruction that raises the error.
pub instruction: Instruction,
/// The error kind.
pub error_kind: InstructionErrorKind,
}
impl InstructionError {
pub(crate) fn new(instruction: Instruction, error_kind: InstructionErrorKind) -> Self {
Self {
instruction,
error_kind,
}
}
}
impl Error for InstructionError {}
impl Display for InstructionError {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
write!(
formatter,
"`{}` {}",
(&self.instruction).to_string(),
self.error_kind
)
}
}
/// The kind of instruction errors.
#[derive(Debug)]
pub enum InstructionErrorKind {
/// The instruction needs to read an invocation input at index `index`, but it's missing.
InvocationInputIsMissing {
/// The invocation input index.
index: u32,
},
/// Failed to cast from a WIT value to a native value.
ToNative(WasmValueNativeCastError),
/// Failed to cast from `from` to `to`.
LoweringLifting {
/// The initial type.
from: InterfaceType,
/// The targeted type.
to: InterfaceType,
},
/// Read a value from the stack, but it doesn't have the expected
/// type.
InvalidValueOnTheStack {
/// The expected type.
expected_type: InterfaceType,
/// The received type.
received_type: InterfaceType,
},
/// Need to read some values from the stack, but it doesn't
/// contain enough data.
StackIsTooSmall {
/// The number of values that were needed.
needed: usize,
},
/// The local or import function doesn't exist.
LocalOrImportIsMissing {
/// The local or import function index.
function_index: u32,
},
/// Values given to a local or import function doesn't match the
/// function signature.
LocalOrImportSignatureMismatch {
/// The local or import function index.
function_index: u32,
/// The expected signature.
expected: (Vec<InterfaceType>, Vec<InterfaceType>),
/// The received signature.
received: (Vec<InterfaceType>, Vec<InterfaceType>),
},
/// Failed to call a local or import function.
LocalOrImportCall {
/// The local or import function index that has been called.
function_index: u32,
},
/// The memory doesn't exist.
MemoryIsMissing {
/// The memory indeX.
memory_index: u32,
},
/// Tried to read out of bounds of the memory.
MemoryOutOfBoundsAccess {
/// The access index.
index: usize,
/// The memory length.
length: usize,
},
/// The string contains invalid UTF-8 encoding.
String(string::FromUtf8Error),
}
impl Error for InstructionErrorKind {}
impl Display for InstructionErrorKind {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
match self {
Self::InvocationInputIsMissing { index } => write!(
formatter,
"cannot access invocation inputs #{} because it doesn't exist",
index
),
Self::ToNative(WasmValueNativeCastError { from, .. }) => write!(
formatter,
"failed to cast the WIT value `{:?}` to its native type",
from,
),
Self::LoweringLifting { from, to } => {
write!(formatter, "failed to cast `{:?}` to `{:?}`", from, to)
}
Self::InvalidValueOnTheStack {
expected_type,
received_type,
} => write!(
formatter,
"read a value of type `{:?}` from the stack, but the type `{:?}` was expected",
received_type, expected_type,
),
Self::StackIsTooSmall { needed } => write!(
formatter,
"needed to read `{}` value(s) from the stack, but it doesn't contain enough data",
needed
),
Self::LocalOrImportIsMissing { function_index } => write!(
formatter,
"the local or import function `{}` doesn't exist",
function_index
),
Self::LocalOrImportSignatureMismatch { function_index, expected, received } => write!(
formatter,
"the local or import function `{}` has the signature `{:?} -> {:?}` but it received values of kind `{:?} -> {:?}`",
function_index,
expected.0,
expected.1,
received.0,
received.1,
),
Self::LocalOrImportCall { function_index } => write!(
formatter,
"failed while calling the local or import function `{}`",
function_index
),
Self::MemoryIsMissing { memory_index } => write!(
formatter,
"memory `{}` does not exist",
memory_index,
),
Self::MemoryOutOfBoundsAccess { index, length } => write!(
formatter,
"read out of the memory bounds (index {} > memory length {})",
index,
length,
),
Self::String(error) => write!(
formatter,
"{}",
error
),
}
}
}
| true |
d029e072b8f48379946a8758ab71263b2d80241c
|
Rust
|
mtx2d/lochnes
|
/src/video.rs
|
UTF-8
| 2,917 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
use sdl2::pixels::PixelFormatEnum::RGB24;
use sdl2::render::{Canvas, RenderTarget, Texture, TextureCreator};
use std::sync::RwLock;
#[derive(Debug, Clone, Copy)]
pub struct Point {
pub x: u16,
pub y: u16,
}
#[derive(Debug, Clone, Copy)]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
}
pub trait Video {
fn draw_point(&self, point: Point, color: Color);
fn present(&self);
fn clear(&self);
}
pub struct NullVideo;
impl Video for NullVideo {
fn draw_point(&self, _point: Point, _color: Color) {}
fn present(&self) {}
fn clear(&self) {}
}
pub struct TextureBufferedVideo<'a> {
buffer: RwLock<Vec<Color>>,
width: u32,
height: u32,
frame: RwLock<Texture<'a>>,
}
impl<'a> TextureBufferedVideo<'a> {
pub fn new<T>(
texture_creator: &'a TextureCreator<T>,
width: u32,
height: u32,
) -> Result<Self, sdl2::render::TextureValueError> {
let black = Color { r: 0, g: 0, b: 0 };
let buffer = vec![black; width as usize * height as usize];
let buffer = RwLock::new(buffer);
let frame = texture_creator.create_texture_streaming(RGB24, width, height)?;
let frame = RwLock::new(frame);
Ok(TextureBufferedVideo {
buffer,
frame,
width,
height,
})
}
pub fn copy_to(&self, canvas: &mut Canvas<impl RenderTarget>) -> Result<(), String> {
let current_frame = self.frame.read().unwrap();
canvas.copy(¤t_frame, None, None)?;
Ok(())
}
}
impl<'a, 'b> Video for TextureBufferedVideo<'b> {
fn draw_point(&self, point: Point, color: Color) {
let mut buffer = self.buffer.write().unwrap();
let offset = point.y as usize * self.width as usize + point.x as usize;
buffer[offset] = color;
}
fn present(&self) {
let buffer = self.buffer.read().unwrap();
let mut frame = self.frame.write().unwrap();
frame
.with_lock(None, |frame_buffer, pitch| {
for y in 0..self.height {
for x in 0..self.width {
let offset = y as usize * self.width as usize + x as usize;
let color = buffer[offset];
let frame_offset = y as usize * pitch + (x as usize * 3);
frame_buffer[frame_offset] = color.r;
frame_buffer[frame_offset + 1] = color.g;
frame_buffer[frame_offset + 2] = color.b;
}
}
})
.unwrap();
}
fn clear(&self) {}
}
impl<'a, V> Video for &'a V
where
V: Video,
{
fn draw_point(&self, point: Point, color: Color) {
(*self).draw_point(point, color);
}
fn present(&self) {
(*self).present();
}
fn clear(&self) {
(*self).clear();
}
}
| true |
7d5a056c10401b958b20b525b6fb0b3b55250ff4
|
Rust
|
hirokazuy/rust-sample
|
/rust-book/enumtype/src/main.rs
|
UTF-8
| 754 | 3.140625 | 3 |
[] |
no_license
|
#[derive(Debug)]
struct IpV4Addr {
addr: u32
}
#[derive(Debug)]
struct IpV6Addr {
addr: String
}
impl IpV4Addr {
fn from(v1: i8, v2: i8, v3: i8, v4: i8) -> IpV4Addr {
IpV4Addr {
addr: (v1 as u32) << 24
| (v2 as u32) << 16
| (v3 as u32) << 8
| v4 as u32,
}
}
}
impl IpV6Addr {
fn from(addr: String) -> IpV6Addr {
IpV6Addr {
addr
}
}
}
#[derive(Debug)]
enum IpAddress {
V4(IpV4Addr),
V6(IpV6Addr),
}
fn main() {
let addr = IpAddress::V4(IpV4Addr::from(127, 0, 0, 1));
println!("addr is {:#?}", addr);
let addr6 = IpAddress::V6(IpV6Addr::from(String::from("::1")));
println!("addr is {:#?}", addr6);
}
| true |
03cda20846953bcdcce0bf23ab99f121a2641fc3
|
Rust
|
estysdesu/AoC
|
/2019/02/src/main.rs
|
UTF-8
| 824 | 3.15625 | 3 |
[] |
no_license
|
use std::fs;
extern crate intcode;
fn main() {
let filename = "./input.txt";
let orig_intcodes: Vec<u32> = process_input(filename);
for n in 0..=99 {
// noun
for v in 0..=99 {
// verb
let mut intcodes = orig_intcodes.clone();
intcode::process(&mut intcodes, Some(n), Some(v));
let output = intcodes[0];
if output == 19690720 {
println!("{}", 100 * n + v)
}
}
}
// println!("{:?}", intcodes);
}
fn process_input(filename: &str) -> Vec<u32> {
let contents = fs::read_to_string(filename).expect("error reading file");
let content_vec: Vec<u32> = contents
.split(",")
.map(|m| m.parse().expect("error parsing str to int"))
.collect();
return content_vec;
}
| true |
fe271563262d30294eadd73ef7d27fc7dc6b1448
|
Rust
|
VinceOPS/rust-wasm-introduction
|
/packages/bank-account/src/lib.rs
|
UTF-8
| 1,253 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
use std::convert::TryFrom;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct Account {
balance: i32,
}
#[wasm_bindgen]
impl Account {
pub fn new(amount: i32) -> Account {
Account { balance: amount }
}
/// deposit money, `amount`, added to the current `balance`
pub fn deposit(&mut self, amount: u16) -> i32 {
self.balance = self.balance + i32::try_from(amount).ok().unwrap();
return self.balance;
}
/// withdraw money, `amount`, subtracted from the current `balance`
pub fn withdraw(&mut self, amount: u16) -> i32 {
self.balance = self.balance - i32::try_from(amount).ok().unwrap();
return self.balance;
}
pub fn get_balance(&self) -> i32 {
return self.balance;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_deposits_the_given_amount() {
let mut acc = Account::new(500);
assert_eq!(acc.deposit(500), 1000);
}
#[test]
fn it_withdraws_the_given_amount() {
let mut acc = Account::new(500);
assert_eq!(acc.withdraw(500), 0);
}
#[test]
fn test_negative_balance_on_withdraw() {
let mut acc = Account::new(200);
assert_eq!(acc.withdraw(500), -300);
}
}
| true |
495b0c3deb15a3fcaae6261d9ac8b7566c0ba6d6
|
Rust
|
rotty/lexpr-rs
|
/lexpr/src/value/from.rs
|
UTF-8
| 2,104 | 3.09375 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::borrow::Cow;
use crate::{Cons, Number, Value};
macro_rules! impl_from_number {
(
$($ty:ty),*
) => {
$(
impl From<$ty> for Value {
#[inline]
fn from(n: $ty) -> Self {
Value::Number(Number::from(n))
}
}
)*
};
}
impl_from_number!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64);
impl From<char> for Value {
#[inline]
fn from(c: char) -> Self {
Value::Char(c)
}
}
impl From<&str> for Value {
#[inline]
fn from(s: &str) -> Self {
Value::String(s.into())
}
}
impl<'a> From<Cow<'a, str>> for Value {
#[inline]
fn from(s: Cow<'a, str>) -> Self {
Value::from(s.as_ref())
}
}
impl From<Box<str>> for Value {
#[inline]
fn from(s: Box<str>) -> Self {
Value::String(s)
}
}
impl From<String> for Value {
#[inline]
fn from(s: String) -> Self {
Value::String(s.into_boxed_str())
}
}
impl From<bool> for Value {
#[inline]
fn from(v: bool) -> Self {
Value::Bool(v)
}
}
impl From<&[u8]> for Value {
#[inline]
fn from(bytes: &[u8]) -> Self {
Value::Bytes(bytes.into())
}
}
impl From<Box<[u8]>> for Value {
#[inline]
fn from(bytes: Box<[u8]>) -> Self {
Value::Bytes(bytes)
}
}
impl From<Vec<u8>> for Value {
#[inline]
fn from(bytes: Vec<u8>) -> Self {
Value::Bytes(bytes.into_boxed_slice())
}
}
impl From<Number> for Value {
fn from(n: Number) -> Self {
Value::Number(n)
}
}
impl<T, U> From<(T, U)> for Value
where
T: Into<Value>,
U: Into<Value>,
{
fn from((car, cdr): (T, U)) -> Self {
Value::Cons(Cons::new(car, cdr))
}
}
impl From<Cons> for Value {
fn from(pair: Cons) -> Self {
Value::Cons(pair)
}
}
impl From<Vec<Value>> for Value {
fn from(elts: Vec<Value>) -> Self {
Value::Vector(elts.into())
}
}
impl From<Box<[Value]>> for Value {
fn from(elts: Box<[Value]>) -> Self {
Value::Vector(elts)
}
}
| true |
4b017c797fd37a5e0287e107f6943a49c127a4b6
|
Rust
|
zombodb/zombodb
|
/src/zql/transformations/field_finder.rs
|
UTF-8
| 3,824 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use crate::zql::ast::{Expr, IndexLink, QualifiedField};
pub fn find_fields(expr: &mut Expr, root_index: &IndexLink, indexes: &Vec<IndexLink>) {
match expr {
Expr::Null => unreachable!(),
Expr::Subselect(i, e) => find_fields(e, i, indexes),
Expr::Expand(_i, e, f) => {
if let Some(filter) = f {
find_fields(filter, root_index, indexes);
}
find_fields(e, root_index, indexes)
}
Expr::Nested(_, e) => find_fields(e, root_index, indexes),
Expr::Not(r) => find_fields(r, root_index, indexes),
Expr::WithList(v) | Expr::AndList(v) | Expr::OrList(v) => v
.iter_mut()
.for_each(|e| find_fields(e, root_index, indexes)),
Expr::Linked(_, _) => unreachable!("No Expr::Linked node should exist yet"),
Expr::Json(_) => {}
Expr::Contains(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::Eq(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::Gt(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::Lt(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::Gte(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::Lte(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::Ne(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::DoesNotContain(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::Regex(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::MoreLikeThis(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::FuzzyLikeThis(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
Expr::Matches(f, _) => f.index = find_link_for_field(&f, root_index, indexes),
}
}
pub fn find_link_for_field(
field_name: &QualifiedField,
root_index: &IndexLink,
indexes: &Vec<IndexLink>,
) -> Option<IndexLink> {
if field_name.index.is_some() {
// we already know where the field lives
return field_name.index.clone();
}
for mut index in Some(root_index).into_iter().chain(indexes.into_iter()) {
if index.is_this_index() {
// 'this.index', typically from an #expand or #subselect, means the original index
index = root_index;
}
if index.name.is_some() && *index.name.as_ref().unwrap() == field_name.base_field() {
// the base field name is the same as this named index link, so that's where it comes from
return Some(index.clone());
}
let relation = if index == root_index {
// if we can't open the root_index, that's okay, we'll just not do anything about that
// this should only happen during our unit tests where we don't specify a valid table/index
match index.open_table() {
Ok(relation) => Some(relation),
Err(_) => None,
}
} else {
// but we definitely want to ensure we can open a linked index, and we'll panic!() if we can't
Some(index.open_table().unwrap_or_else(|e| {
panic!(
"failed to open linked index's table '{}': {}",
index.qualified_index.table_name(),
e
)
}))
};
if let Some(relation) = relation {
for att in relation.tuple_desc().iter() {
if att.name() == field_name.base_field() {
// the table behind this index link contains this field
return Some(index.clone());
}
}
}
}
Some(root_index.clone())
}
| true |
5fc2f328313f0469fb570ff4606daf3d8e554321
|
Rust
|
arnfaldur/deeper
|
/engine/transforms/src/lib.rs
|
UTF-8
| 1,076 | 2.640625 | 3 |
[] |
no_license
|
pub use components::*;
pub use systems::TransformBuilderExtender;
pub use crate::entity_smith::TransformEntitySmith;
pub mod components;
mod entity_smith;
mod systems;
// #[derive(Default)]
// struct SceneGraph {
// entity: Option<Entity>,
// //changed: bool,
// //parent: Weak<SceneNode>, // Weak pointers probably won't cut it
// children: Vec<SceneGraph>, // TODO: consider using a smallvec here
// }
// #[derive(Default)]
// struct Ancestry {
// pub tree: HashMap<Entity, Node>,
// }
// impl Ancestry {
// pub fn first_gen(self, ent: Entity) -> bool {
// self.tree
// .get(&ent)
// .map_or(false, |Node { parent, .. }| parent.is_none())
// }
// pub fn get_parent(&self, entity: Entity) -> Option<Entity> {
// self.tree
// .get(&entity)
// .map(|Node { parent, .. }| *parent)
// .flatten()
// }
// pub fn get_children(&self, entity: Entity) -> Option<&Vec<Entity>> {
// self.tree.get(&entity).map(|Node { children, .. }| children)
// }
// }
| true |
1fbeab4e5d92b366471aa7265c3f13888964623d
|
Rust
|
SmedbergM/AdventOfCode2019
|
/intcode/src/lib.rs
|
UTF-8
| 21,922 | 3.203125 | 3 |
[] |
no_license
|
use std::collections::VecDeque;
use std::convert::TryFrom;
#[derive(Clone)]
pub struct Program {
memory: Vec<i64>,
instruction_pointer: usize,
relative_base: i64,
return_code: Option<i64>,
input_buffer: VecDeque<i64>
}
impl Program {
pub fn from_str(line: &str) -> Program {
let memory: Vec<i64> = line.split(",")
.flat_map(|s| i64::from_str_radix(s, 10).ok()).collect();
Program { memory,
instruction_pointer: 0,
relative_base: 0,
return_code: None,
input_buffer: VecDeque::new()
}
}
fn current_instruction(&self) -> Option<Instruction> {
match self.memory.get(self.instruction_pointer) {
None => {
eprintln!("No instruction found at {}", &self.instruction_pointer);
None
},
Some(x) => Instruction::parse(x)
}
}
fn get(&mut self, idx: usize, mode: &ParameterMode) -> Option<i64> {
let read_idx = match mode {
ParameterMode::Immediate => idx,
ParameterMode::Positional => self.memory[idx] as usize,
ParameterMode::Relative => self.relative_idx(idx)
};
if read_idx >= self.memory.len() {
self.memory.resize(read_idx + 1, 0);
}
self.memory.get(read_idx).map(|x| *x)
}
fn relative_idx(&self, idx: usize) -> usize {
(self.relative_base + self.memory[idx]) as usize
}
pub fn read_input(&mut self, input: i64) {
self.input_buffer.push_back(input)
}
fn set(&mut self, idx: usize, value: i64, mode: &ParameterMode) {
let write_idx = match mode {
ParameterMode::Positional => self.memory[idx] as usize,
ParameterMode::Relative => self.relative_idx(idx),
_ => {
eprintln!("Setting values in Immediate mode is not supported!");
idx
}
};
if write_idx >= self.memory.len() {
self.memory.resize(write_idx + 1, 0);
}
self.memory[write_idx] = value;
}
fn step(&mut self) -> State {
enum StepResult {
Halt,
Jump,
Crash,
Fwd(usize),
Output(i64)
}
fn perform_jump_if(this: &mut Program, nonzero: bool, m1: &ParameterMode, m2: &ParameterMode) -> StepResult {
match this.get(this.instruction_pointer + 1, m1) {
None => StepResult::Crash,
Some(p1) if (p1 != 0) == nonzero => match this.get(this.instruction_pointer + 2, m2) {
None => StepResult::Crash,
Some(p2) => match usize::try_from(p2) {
Err(_) => StepResult::Crash,
Ok(p2) => {
this.instruction_pointer = p2;
StepResult::Jump
}
}
},
_ => StepResult::Fwd(3)
}
};
let step_result = match self.current_instruction() {
None => StepResult::Crash,
Some(Instruction::Halt) => StepResult::Halt,
Some(Instruction::Add { m1, m2, m3 }) => {
let addend1 = self.get(self.instruction_pointer + 1, &m1).unwrap();
let addend2 = self.get(self.instruction_pointer + 2, &m2).unwrap();
self.set(self.instruction_pointer + 3, addend1 + addend2, &m3);
StepResult::Fwd(4)
},
Some(Instruction::Mult { m1, m2, m3 }) => {
let factor1 = self.get(self.instruction_pointer + 1, &m1).unwrap();
let factor2 = self.get(self.instruction_pointer + 2, &m2).unwrap();
self.set(self.instruction_pointer + 3, factor1 * factor2, &m3);
StepResult::Fwd(4)
},
Some(Instruction::Input { m1 }) => {
match self.input_buffer.pop_front() {
None => StepResult::Crash,
Some(input) => {
self.set(self.instruction_pointer + 1, input, &m1);
StepResult::Fwd(2)
}
}
},
Some(Instruction::Output { m1 }) => {
match self.get(self.instruction_pointer + 1, &m1) {
None => StepResult::Crash,
Some(out) => {
self.return_code = Some(out);
StepResult::Output(out)
}
}
},
Some(Instruction::JumpIfTrue { m1, m2 }) => perform_jump_if(self, true, &m1, &m2),
Some(Instruction::JumpIfFalse { m1, m2 }) => perform_jump_if(self, false, &m1, &m2),
Some(Instruction::LessThan { m1, m2, m3 }) => {
match self.get(self.instruction_pointer + 1, &m1).and_then(|p1| self.get(self.instruction_pointer + 2, &m2).map(|p2| (p1, p2))) {
None => StepResult::Crash,
Some((p1, p2)) => {
self.set(self.instruction_pointer + 3, (p1 < p2) as i64, &m3);
StepResult::Fwd(4)
}
}
},
Some(Instruction::Equals { m1, m2, m3 }) => {
match self.get(self.instruction_pointer + 1, &m1).and_then(|p1| self.get(self.instruction_pointer + 2, &m2).map(|p2| (p1, p2))) {
None => StepResult::Crash,
Some((p1, p2)) => {
self.set(self.instruction_pointer + 3, (p1 == p2) as i64, &m3);
StepResult::Fwd(4)
}
}
},
Some(Instruction::RelativeBaseAdjust { m1 }) => {
match self.get(self.instruction_pointer + 1, &m1) {
None => StepResult::Crash,
Some(p1) => {
self.relative_base += p1;
StepResult::Fwd(2)
}
}
}
};
match step_result {
StepResult::Crash => {
return State::Crashed;
},
StepResult::Output(out) => {
self.instruction_pointer += 2;
match self.current_instruction() {
Some(Instruction::Input { .. }) => {
return State::OutputAwaitingInput(out)
},
_ => {
return State::Output(out)
}
}
},
StepResult::Fwd(len) => {
self.instruction_pointer += len;
},
_ => ()
};
match self.current_instruction() {
Some(Instruction::Halt) => State::Done,
Some(Instruction::Input { .. }) if self.input_buffer.is_empty() => State::AwaitingInput,
None => State::Crashed,
_ => State::Running
}
}
pub fn run_and_print(&mut self, inputs: &[i64]) -> Option<i64> {
self.run(inputs, |x| {println!("Output: {}", &x)})
}
pub fn run<F>(&mut self, inputs: &[i64], mut on_output: F) -> Option<i64>
where F: FnMut(i64) {
for input in inputs {
self.read_input(*input);
}
loop {
let state = self.await_output();
match state {
State::Output(out) => {
on_output(out);
continue
},
State::Done => return self.return_code,
State::Crashed => {
eprintln!("Program reports crashed state");
return self.return_code
},
State::AwaitingInput if self.input_buffer.is_empty() => {
eprintln!("Program wants input but none available");
return self.return_code
},
State::AwaitingInput => continue,
State::OutputAwaitingInput(out) if self.input_buffer.is_empty() => {
on_output(out);
eprintln!("Program wants input but none available");
return self.return_code
},
State::OutputAwaitingInput(out) => {
on_output(out);
continue
},
State::Running => continue
}
}
}
pub fn await_output(&mut self) -> State {
match self.current_instruction() {
None => State::Crashed,
Some(Instruction::Input { .. }) if self.input_buffer.is_empty() => State::AwaitingInput,
_ => {
loop {
match self.step() {
State::Running => continue,
state => return state
}
}
}
}
}
pub fn is_terminated(&self) -> bool {
match self.current_instruction() {
Some(Instruction::Halt) => true,
_ => false
}
}
pub fn overwrite_memory(&mut self, idx: usize, word: i64) {
self.memory[idx] = word;
}
}
#[derive(PartialEq, Debug)]
pub enum State {
Output(i64),
OutputAwaitingInput(i64),
AwaitingInput,
Running,
Done,
Crashed
}
enum Instruction {
Halt,
Add { m1: ParameterMode, m2: ParameterMode, m3: ParameterMode },
Mult { m1: ParameterMode, m2: ParameterMode, m3: ParameterMode },
Input { m1: ParameterMode },
Output { m1: ParameterMode },
JumpIfTrue { m1: ParameterMode, m2: ParameterMode },
JumpIfFalse { m1: ParameterMode, m2: ParameterMode },
LessThan { m1: ParameterMode, m2: ParameterMode, m3: ParameterMode },
Equals { m1: ParameterMode, m2: ParameterMode, m3: ParameterMode },
RelativeBaseAdjust { m1: ParameterMode }
}
impl Instruction {
fn parse(abcde: &i64) -> Option<Instruction> {
match abcde.rem_euclid(100) {
99 => Some(Instruction::Halt),
1 => {
Instruction::parse_three(abcde / 100).map(|(m1, m2, m3)| {
Instruction::Add { m1, m2, m3 }
})
},
2 => {
Instruction::parse_three(abcde / 100).map(|(m1, m2, m3)| {
Instruction::Mult { m1, m2, m3 }
})
},
3 => {
Instruction::parse_one(abcde / 100).map(|m1| Instruction::Input { m1 })
},
4 => {
Instruction::parse_one(abcde / 100).map(|m1| Instruction::Output { m1 })
},
5 => {
Instruction::parse_two(abcde / 100).map(|(m1, m2)| {
Instruction::JumpIfTrue { m1, m2 }
})
},
6 => {
Instruction::parse_two(abcde / 100).map(|(m1, m2)| {
Instruction::JumpIfFalse { m1, m2 }
})
},
7 => {
Instruction::parse_three(abcde / 100).map(|(m1, m2, m3)| {
Instruction::LessThan { m1, m2, m3 }
})
},
8 => {
Instruction::parse_three(abcde / 100).map(|(m1, m2, m3)| {
Instruction::Equals { m1, m2, m3 }
})
},
9 => {
Instruction::parse_one(abcde / 100).map(|m1| Instruction::RelativeBaseAdjust { m1 })
}
_ => None
}
}
fn parse_one(abc: i64) -> Option<ParameterMode> {
ParameterMode::of(&abc.rem_euclid(10))
}
fn parse_two(abc: i64) -> Option<(ParameterMode, ParameterMode)> {
let c = abc.rem_euclid(10);
let b = (abc / 10).rem_euclid(10);
ParameterMode::of(&c).and_then(|m1| {
ParameterMode::of(&b).map(|m2| {
(m1, m2)
})
})
}
fn parse_three(abc: i64) -> Option<(ParameterMode, ParameterMode, ParameterMode)> {
let c = abc.rem_euclid(10);
let b = (abc / 10).rem_euclid(10);
let a = (abc / 100).rem_euclid(10);
ParameterMode::of(&c).and_then(|m1| {
ParameterMode::of(&b).and_then(|m2| {
ParameterMode::of(&a).map(|m3| {
(m1, m2, m3)
})
})
})
}
}
enum ParameterMode {
Positional,
Immediate,
Relative
}
impl ParameterMode {
fn of(k: &i64) -> Option<ParameterMode> {
match k {
0 => Some(ParameterMode::Positional),
1 => Some(ParameterMode::Immediate),
2 => Some(ParameterMode::Relative),
_ => None
}
}
}
#[cfg(test)]
mod day02_tests {
use super::*;
#[test]
fn add_spec() {
let mut program = Program::from_str("1,0,0,0,99");
assert_eq!(program.step(), State::Done);
assert_eq!(program.memory[..], [2,0,0,0,99]);
assert_eq!(program.instruction_pointer, 4);
assert_eq!(program.step(), State::Done);
}
#[test]
fn multiply_spec() {
let mut program = Program::from_str("2,3,0,3,99");
assert_eq!(program.step(), State::Done);
assert_eq!(program.memory[..], [2,3,0,6,99]);
assert_eq!(program.instruction_pointer, 4);
assert_eq!(program.step(), State::Done);
let mut program = Program::from_str("2,4,4,5,99,0");
assert_eq!(program.step(), State::Done);
assert_eq!(program.memory[..], [2,4,4,5,99,9801]);
assert_eq!(program.instruction_pointer, 4);
assert_eq!(program.step(), State::Done);
}
}
#[cfg(test)]
mod day05_tests {
use super::*;
#[test]
fn equal_test() {
let mut program = Program::from_str("3,9,8,9,10,9,4,9,99,-1,8");
program.read_input(8);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(1));
let mut program = Program::from_str("3,9,8,9,10,9,4,9,99,-1,8");
program.read_input(17);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(0));
let mut program = Program::from_str("3,3,1108,-1,8,3,4,3,99");
program.read_input(8);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(1));
let mut program = Program::from_str("3,3,1108,-1,8,3,4,3,99");
program.read_input(-17);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(0));
}
#[test]
fn less_than_test() {
let code = "3,9,7,9,10,9,4,9,99,-1,8";
let mut program = Program::from_str(code);
program.read_input(-17);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(1));
let mut program = Program::from_str(code);
program.read_input(8);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(0));
let mut program = Program::from_str(code);
program.read_input(31);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(0));
let code = "3,3,1107,-1,8,3,4,3,99";
let mut program = Program::from_str(code);
program.read_input(-17);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(1));
let mut program = Program::from_str(code);
program.read_input(8);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(0));
let mut program = Program::from_str(code);
program.read_input(31);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Running);
assert_eq!(program.step(), State::Output(0));
}
#[test]
fn jump_test() {
let code = "3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9";
let mut program = Program::from_str(code);
program.read_input(0);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 2);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 9);
assert_eq!(program.step(), State::Output(0));
let mut program = Program::from_str(code);
program.read_input(-17);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 2);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 5);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 9);
assert_eq!(program.step(), State::Output(1));
assert_eq!(program.instruction_pointer, 11);
let mut program = Program::from_str(code);
program.read_input(42);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 2);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 5);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 9);
assert_eq!(program.step(), State::Output(1));
assert_eq!(program.instruction_pointer, 11);
}
#[test]
fn jump_test_2() {
let code = "3,3,1105,-1,9,1101,0,0,12,4,12,99,1";
let mut program = Program::from_str(code);
let input = 0;
program.read_input(input);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 2);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 5);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 9);
assert_eq!(program.step(), State::Output((input != 0) as i64));
let mut program = Program::from_str(code);
let input = 17;
program.read_input(input);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 2);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 9);
assert_eq!(program.step(), State::Output((input != 0) as i64));
let mut program = Program::from_str(code);
let input = -256;
program.read_input(input);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 2);
assert_eq!(program.step(), State::Running);
assert_eq!(program.instruction_pointer, 9);
assert_eq!(program.step(), State::Output((input != 0) as i64));
}
#[test]
fn longer_test() {
let code = "3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99";
let mut program = Program::from_str(code);
program.read_input(-3);
loop {
match program.step() {
State::Crashed | State::Done => panic!(),
State::Output(x) => {
assert_eq!(x, 999);
break
},
_ => () // continue
}
}
let mut program = Program::from_str(code);
program.read_input(8);
loop {
match program.step() {
State::Crashed | State::Done => panic!(),
State::Output(x) => {
assert_eq!(x, 1000);
break
},
_ => () // continue
}
}
let mut program = Program::from_str(code);
program.read_input(88);
loop {
match program.step() {
State::Crashed | State::Done => panic!(),
State::Output(x) => {
assert_eq!(x, 1001);
break
},
_ => () // continue
}
}
}
#[test]
fn clone_test() {
let code = "3,3,1105,-1,9,1101,0,0,12,4,12,99,1";
let mut program = Program::from_str(code);
let program2 = program.clone();
program.read_input(-1);
program.step();
assert_ne!(program.instruction_pointer, program2.instruction_pointer);
}
}
#[cfg(test)]
mod relative_base_test {
use super::*;
#[test]
fn quine_test() {
let mut program = Program::from_str("109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99");
let mut outputs = vec!();
program.run(&[], &mut |x| { outputs.push(x)});
assert_eq!(outputs[..], [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]);
}
#[test]
fn long_test() {
let mut program = Program::from_str("1102,34915192,34915192,7,4,7,99,0");
let mut out = 0;
program.run(&[], &mut |x| { out = x});
let out_str = format!("{}", out);
assert_eq!(out_str.len(), 16);
let mut program = Program::from_str("104,1125899906842624,99");
out = 0;
program.run(&[], &mut |x| { out = x});
assert_eq!(out, 1125899906842624);
}
}
| true |
7fde9cab4695a45ac266ac1a5b899577860d3304
|
Rust
|
irevoire/lexer
|
/src/reader.rs
|
UTF-8
| 6,229 | 3.75 | 4 |
[] |
no_license
|
pub struct Reader {
buf: Vec<char>,
cursor: usize,
line_number: usize,
}
impl Reader {
pub fn new<R: std::io::Read>(reader: &mut R) -> Self {
let mut buf = String::new();
reader.read_to_string(&mut buf).unwrap(); // if fail we stop everything
Reader {
buf: buf.chars().collect(),
cursor: 0,
line_number: 0,
}
}
pub fn next(&mut self) -> Option<&char> {
if let Some(c) = self.buf.get(self.cursor) {
if *c == '\n' {
self.line_number += 1;
}
self.cursor += 1;
return Some(c);
}
None
}
pub fn skip(&mut self, n: usize) -> &mut Self {
for _ in 0..n {
self.next();
}
self
}
pub fn prev(&mut self) -> Option<&char> {
self.cursor = self.cursor.checked_sub(1)?;
if let Some(c) = self.buf.get(self.cursor) {
if *c == '\n' {
self.line_number -= 1;
}
return Some(c);
}
None
}
/// Define what should separate each word in the langage
/// At this time it's ' ', '\n', '\n'
fn is_separator(c: char) -> bool {
c == ' ' || c == '\t' || c == '\n'
}
/// Return a word between the current position and the next separator
/// See the is_separator function to see when it stop
/// TODO This function do a copy of the word. It could probably do it
/// in place with a better way to handle the buffer
pub fn get_word(&mut self) -> String {
let start = self.cursor;
while let Some(c) = self.next() {
if Reader::is_separator(*c) {
self.prev();
break;
}
}
self.buf[start..self.cursor].iter().collect::<String>()
}
pub fn skip_separator(&mut self) -> &mut Self {
while let Some(c) = self.next() {
if Reader::is_separator(*c) {
continue;
}
self.prev(); // to get back on the last non shitty chr
break;
}
self
}
pub fn line_number(&self) -> usize {
self.line_number
}
}
#[cfg(test)]
mod tests {
use super::*;
fn init(s: &str) -> Reader {
let mut reader = std::io::Cursor::new(s);
Reader::new(&mut reader)
}
#[test]
fn test_next() {
let mut reader = init("ab");
assert_eq!(reader.cursor, 0);
assert_eq!(reader.next(), Some(&'a'));
assert_eq!(reader.cursor, 1);
assert_eq!(reader.next(), Some(&'b'));
assert_eq!(reader.cursor, 2);
assert_eq!(reader.next(), None);
assert_eq!(reader.cursor, 2);
}
#[test]
fn test_next_utf8() {
let mut reader = init("a😘b🥰");
reader.next();
assert_eq!(reader.next(), Some(&'😘'));
assert_eq!(reader.cursor, 2);
reader.next();
assert_eq!(reader.next(), Some(&'🥰'));
assert_eq!(reader.cursor, 4);
assert_eq!(reader.next(), None);
}
#[test]
fn test_empty_next() {
let mut reader = init("");
assert_eq!(reader.next(), None);
assert_eq!(reader.cursor, 0);
}
#[test]
fn test_prev() {
let mut reader = init("ab");
assert_eq!(reader.prev(), None);
}
#[test]
fn test_prev_utf8() {
let mut reader = init("a😘b🥰");
reader.skip(4);
assert_eq!(reader.prev(), Some(&'🥰'));
assert_eq!(reader.cursor, 3);
reader.prev();
assert_eq!(reader.prev(), Some(&'😘'));
assert_eq!(reader.cursor, 1);
reader.prev();
assert_eq!(reader.prev(), None);
}
#[test]
fn test_empty_prev() {
let mut reader = init("");
assert_eq!(reader.prev(), None);
assert_eq!(reader.cursor, 0);
}
#[test]
fn test_next_and_prev() {
let mut reader = init("ab");
assert_eq!(reader.cursor, 0);
assert_eq!(reader.next(), Some(&'a'));
assert_eq!(reader.cursor, 1);
assert_eq!(reader.next(), Some(&'b'));
assert_eq!(reader.cursor, 2);
assert_eq!(reader.next(), None);
assert_eq!(reader.cursor, 2);
assert_eq!(reader.prev(), Some(&'b'));
assert_eq!(reader.cursor, 1);
assert_eq!(reader.prev(), Some(&'a'));
assert_eq!(reader.cursor, 0);
assert_eq!(reader.prev(), None);
assert_eq!(reader.cursor, 0);
}
#[test]
fn test_get_word() {
let mut reader = init("Hello Word!");
assert_eq!(reader.get_word(), "Hello");
assert_eq!(reader.get_word(), "");
assert_eq!(reader.next(), Some(&' '));
assert_eq!(reader.get_word(), "Word!");
assert_eq!(reader.next(), None);
}
#[test]
fn test_skip_separator() {
let mut reader = init(" a bc ");
reader.skip_separator();
assert_eq!(reader.next(), Some(&'a'));
reader.skip_separator();
assert_eq!(reader.next(), Some(&'b'));
reader.skip_separator();
assert_eq!(reader.next(), Some(&'c'));
reader.skip_separator();
assert_eq!(reader.next(), None);
}
#[test]
fn test_skip() {
let mut reader = init("abcdef");
reader.skip(1);
assert_eq!(reader.next(), Some(&'b'));
reader.skip(2);
assert_eq!(reader.next(), Some(&'e'));
reader.skip(10);
assert_eq!(reader.next(), None);
}
#[test]
fn test_line_number_next() {
let mut reader = init("a\nc");
assert_eq!(reader.line_number(), 0);
reader.next();
assert_eq!(reader.line_number(), 0);
reader.next();
assert_eq!(reader.line_number(), 1);
reader.next();
assert_eq!(reader.line_number(), 1);
}
#[test]
fn test_line_number_prev() {
let mut reader = init("a\nc");
reader.next();
reader.next(); // line number should be one
reader.prev(); // we should go back to zero
assert_eq!(reader.line_number(), 0);
reader.prev();
assert_eq!(reader.line_number(), 0);
}
}
| true |
fedfd0d3f61733b4260c046db1fe4bd760e03966
|
Rust
|
getsentry/symbolic
|
/symbolic-common/src/byteview.rs
|
UTF-8
| 8,531 | 3.796875 | 4 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! A wrapper type providing direct memory access to binary data.
//!
//! See the [`ByteView`] struct for more documentation.
//!
//! [`ByteView`]: struct.ByteView.html
use std::borrow::Cow;
use std::fs::File;
use std::io;
use std::ops::Deref;
use std::path::Path;
use std::sync::Arc;
use memmap2::Mmap;
use crate::cell::StableDeref;
/// The owner of data behind a ByteView.
///
/// This can either be an mmapped file, an owned buffer or a borrowed binary slice.
#[derive(Debug)]
enum ByteViewBacking<'a> {
Buf(Cow<'a, [u8]>),
Mmap(Mmap),
}
impl Deref for ByteViewBacking<'_> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
match *self {
ByteViewBacking::Buf(ref buf) => buf,
ByteViewBacking::Mmap(ref mmap) => mmap,
}
}
}
/// A smart pointer for byte data.
///
/// This type can be used to uniformly access bytes that were created either from mmapping in a
/// path, a vector or a borrowed slice. A `ByteView` dereferences into a `&[u8]` and guarantees
/// random access to the underlying buffer or file.
///
/// A `ByteView` can be constructed from borrowed slices, vectors or memory mapped from the file
/// system directly.
///
/// # Example
///
/// The most common way to use `ByteView` is to construct it from a file handle. This will own the
/// underlying file handle until the `ByteView` is dropped:
///
/// ```
/// use std::io::Write;
/// use symbolic_common::ByteView;
///
/// fn main() -> Result<(), std::io::Error> {
/// let mut file = tempfile::tempfile()?;
/// file.write_all(b"1234");
///
/// let view = ByteView::map_file(file)?;
/// assert_eq!(view.as_slice(), b"1234");
/// Ok(())
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ByteView<'a> {
backing: Arc<ByteViewBacking<'a>>,
}
impl<'a> ByteView<'a> {
fn with_backing(backing: ByteViewBacking<'a>) -> Self {
ByteView {
backing: Arc::new(backing),
}
}
/// Constructs a `ByteView` from a `Cow`.
///
/// # Example
///
/// ```
/// use std::borrow::Cow;
/// use symbolic_common::ByteView;
///
/// let cow = Cow::Borrowed(&b"1234"[..]);
/// let view = ByteView::from_cow(cow);
/// ```
pub fn from_cow(cow: Cow<'a, [u8]>) -> Self {
ByteView::with_backing(ByteViewBacking::Buf(cow))
}
/// Constructs a `ByteView` from a byte slice.
///
/// # Example
///
/// ```
/// use symbolic_common::ByteView;
///
/// let view = ByteView::from_slice(b"1234");
/// ```
pub fn from_slice(buffer: &'a [u8]) -> Self {
ByteView::from_cow(Cow::Borrowed(buffer))
}
/// Constructs a `ByteView` from a vector of bytes.
///
/// # Example
///
/// ```
/// use symbolic_common::ByteView;
///
/// let vec = b"1234".to_vec();
/// let view = ByteView::from_vec(vec);
/// ```
pub fn from_vec(buffer: Vec<u8>) -> Self {
ByteView::from_cow(Cow::Owned(buffer))
}
/// Constructs a `ByteView` from an open file handle by memory mapping the file.
///
/// See [`ByteView::map_file_ref`] for a non-consuming version of this constructor.
///
/// # Example
///
/// ```
/// use std::io::Write;
/// use symbolic_common::ByteView;
///
/// fn main() -> Result<(), std::io::Error> {
/// let mut file = tempfile::tempfile()?;
/// let view = ByteView::map_file(file)?;
/// Ok(())
/// }
/// ```
pub fn map_file(file: File) -> Result<Self, io::Error> {
Self::map_file_ref(&file)
}
/// Constructs a `ByteView` from an open file handle by memory mapping the file.
///
/// The main difference with [`ByteView::map_file`] is that this takes the [`File`] by
/// reference rather than consuming it.
///
/// # Example
///
/// ```
/// use std::io::Write;
/// use symbolic_common::ByteView;
///
/// fn main() -> Result<(), std::io::Error> {
/// let mut file = tempfile::tempfile()?;
/// let view = ByteView::map_file_ref(&file)?;
/// Ok(())
/// }
/// ```
pub fn map_file_ref(file: &File) -> Result<Self, io::Error> {
let backing = match unsafe { Mmap::map(file) } {
Ok(mmap) => ByteViewBacking::Mmap(mmap),
Err(err) => {
// this is raised on empty mmaps which we want to ignore. The 1006 Windows error
// looks like "The volume for a file has been externally altered so that the opened
// file is no longer valid."
if err.kind() == io::ErrorKind::InvalidInput
|| (cfg!(windows) && err.raw_os_error() == Some(1006))
{
ByteViewBacking::Buf(Cow::Borrowed(b""))
} else {
return Err(err);
}
}
};
Ok(ByteView::with_backing(backing))
}
/// Constructs a `ByteView` from any `std::io::Reader`.
///
/// **Note**: This currently consumes the entire reader and stores its data in an internal
/// buffer. Prefer [`open`] when reading from the file system or [`from_slice`] / [`from_vec`]
/// for in-memory operations. This behavior might change in the future.
///
/// # Example
///
/// ```
/// use std::io::Cursor;
/// use symbolic_common::ByteView;
///
/// fn main() -> Result<(), std::io::Error> {
/// let reader = Cursor::new(b"1234");
/// let view = ByteView::read(reader)?;
/// Ok(())
/// }
/// ```
///
/// [`open`]: struct.ByteView.html#method.open
/// [`from_slice`]: struct.ByteView.html#method.from_slice
/// [`from_vec`]: struct.ByteView.html#method.from_vec
pub fn read<R: io::Read>(mut reader: R) -> Result<Self, io::Error> {
let mut buffer = vec![];
reader.read_to_end(&mut buffer)?;
Ok(ByteView::from_vec(buffer))
}
/// Constructs a `ByteView` from a file path by memory mapping the file.
///
/// # Example
///
/// ```no_run
/// use symbolic_common::ByteView;
///
/// fn main() -> Result<(), std::io::Error> {
/// let view = ByteView::open("test.txt")?;
/// Ok(())
/// }
/// ```
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
let file = File::open(path)?;
Self::map_file(file)
}
/// Returns a slice of the underlying data.
///
///
/// # Example
///
/// ```
/// use symbolic_common::ByteView;
///
/// let view = ByteView::from_slice(b"1234");
/// let data = view.as_slice();
/// ```
#[inline(always)]
pub fn as_slice(&self) -> &[u8] {
self.backing.deref()
}
}
impl AsRef<[u8]> for ByteView<'_> {
#[inline(always)]
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
impl Deref for ByteView<'_> {
type Target = [u8];
#[inline(always)]
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
unsafe impl StableDeref for ByteView<'_> {}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Seek, Write};
use similar_asserts::assert_eq;
use tempfile::NamedTempFile;
#[test]
fn test_open_empty_file() -> Result<(), std::io::Error> {
let tmp = NamedTempFile::new()?;
let view = ByteView::open(tmp.path())?;
assert_eq!(&*view, b"");
Ok(())
}
#[test]
fn test_open_file() -> Result<(), std::io::Error> {
let mut tmp = NamedTempFile::new()?;
tmp.write_all(b"1234")?;
let view = ByteView::open(tmp.path())?;
assert_eq!(&*view, b"1234");
Ok(())
}
#[test]
fn test_mmap_fd_reuse() -> Result<(), std::io::Error> {
let mut tmp = NamedTempFile::new()?;
tmp.write_all(b"1234")?;
let view = ByteView::map_file_ref(tmp.as_file())?;
// This deletes the file on disk.
let _path = tmp.path().to_path_buf();
let mut file = tmp.into_file();
#[cfg(not(windows))]
{
assert!(!_path.exists());
}
// Ensure we can still read from the the file after mmapping and deleting it on disk.
let mut buf = Vec::new();
file.rewind()?;
file.read_to_end(&mut buf)?;
assert_eq!(buf, b"1234");
drop(file);
// Ensure the byteview can still read the file as well.
assert_eq!(&*view, b"1234");
Ok(())
}
}
| true |
6525bcee14b444c260e76d5e5499bedba6969876
|
Rust
|
ia7ck/competitive-programming
|
/AtCoder/abc231/src/bin/f/main.rs
|
UTF-8
| 1,567 | 2.515625 | 3 |
[] |
no_license
|
use coordinate_compression::CoordinateCompression;
use fenwick_tree::FenwickTree;
use input_i_scanner::InputIScanner;
use std::iter::FromIterator;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let n = scan!(usize);
let a = scan!(u32; n);
let b = scan!(u32; n);
let com_a = CoordinateCompression::from_iter(a.iter().copied());
let com_b = CoordinateCompression::from_iter(b.iter().copied());
let mut bs = vec![vec![]; com_a.size()];
for i in 0..n {
bs[com_a.find_index(&a[i])].push(com_b.find_index(&b[i]));
}
for i in 0..bs.len() {
bs[i].sort();
bs[i].reverse();
}
let mut tree = FenwickTree::new(com_b.size(), 0usize);
let mut ans = 0;
for bs in bs {
let mut j = 0;
while j < bs.len() {
let mut dup = 1;
while j + 1< bs.len() && bs[j] == bs[j + 1] {
j += 1;
dup += 1;
}
tree.add(bs[j], dup);
ans += dup * tree.sum(bs[j]..com_b.size());
j += 1;
}
}
println!("{}", ans);
}
| true |
049966f2d13d5c7f03de03c261a7ccc48651eb07
|
Rust
|
nuta/archives
|
/noa-lsp/src/editor/flash.rs
|
UTF-8
| 1,562 | 2.703125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::time::{Duration, Instant};
use noa_buffer::cursor::Range;
use crate::view::View;
const FLASH_DURATION_MS: Duration = Duration::from_millis(360);
pub struct Flash {
range: Range,
flashed_at: Option<Instant>,
}
pub struct FlashManager {
flashes: Vec<Flash>,
}
impl FlashManager {
pub fn new() -> FlashManager {
FlashManager {
flashes: Vec::new(),
}
}
pub fn next_timeout(&self) -> Option<Duration> {
if self.flashes.is_empty() {
None
} else {
Some(Duration::from_millis(20))
}
}
pub fn highlight(&mut self, view: &mut View) {
self.flashes.retain_mut(|flash| match flash.flashed_at {
Some(flashed_at) if flashed_at.elapsed() > FLASH_DURATION_MS => false,
Some(flashed_at) => {
let total = FLASH_DURATION_MS.as_millis();
let elapsed = flashed_at.elapsed().as_millis();
if total / 3 <= elapsed && elapsed < total * 2 / 3 {
view.clear_highlight(flash.range);
} else {
view.highlight(flash.range, "buffer.flash");
}
true
}
None => {
flash.flashed_at = Some(Instant::now());
view.highlight(flash.range, "buffer.flash");
true
}
});
}
pub fn flash(&mut self, range: Range) {
self.flashes.push(Flash {
range,
flashed_at: None,
});
}
}
| true |
5a4673d5c3f014df0afb97e62b2c5ba438cd0339
|
Rust
|
seanwallawalla-forks/nushell
|
/crates/nu-protocol/src/syntax_shape.rs
|
UTF-8
| 2,555 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug};
use serde::{Deserialize, Serialize};
/// The syntactic shapes that values must match to be passed into a command. You can think of this as the type-checking that occurs when you call a function.
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum SyntaxShape {
/// Any syntactic form is allowed
Any,
/// Strings and string-like bare words are allowed
String,
/// A dotted path to navigate the table
ColumnPath,
/// A dotted path to navigate the table (including variable)
FullColumnPath,
/// Only a numeric (integer or decimal) value is allowed
Number,
/// A range is allowed (eg, `1..3`)
Range,
/// Only an integer value is allowed
Int,
/// A filepath is allowed
FilePath,
/// A glob pattern is allowed, eg `foo*`
GlobPattern,
/// A block is allowed, eg `{start this thing}`
Block,
/// A table is allowed, eg `[first second]`
Table,
/// A filesize value is allowed, eg `10kb`
Filesize,
/// A duration value is allowed, eg `19day`
Duration,
/// An operator
Operator,
/// A math expression which expands shorthand forms on the lefthand side, eg `foo > 1`
/// The shorthand allows us to more easily reach columns inside of the row being passed in
RowCondition,
/// A general math expression, eg the `1 + 2` of `= 1 + 2`
MathExpression,
}
impl SyntaxShape {
pub fn syntax_shape_name(&self) -> &str {
match self {
SyntaxShape::Any => "any",
SyntaxShape::String => "string",
SyntaxShape::FullColumnPath => "column path (with variable)",
SyntaxShape::ColumnPath => "column path",
SyntaxShape::Number => "number",
SyntaxShape::Range => "range",
SyntaxShape::Int => "integer",
SyntaxShape::FilePath => "file path",
SyntaxShape::GlobPattern => "pattern",
SyntaxShape::Block => "block",
SyntaxShape::Table => "table",
SyntaxShape::Duration => "duration",
SyntaxShape::Filesize => "filesize",
SyntaxShape::Operator => "operator",
SyntaxShape::RowCondition => "condition",
SyntaxShape::MathExpression => "math expression",
}
}
}
impl PrettyDebug for SyntaxShape {
/// Prepare SyntaxShape for pretty-printing
fn pretty(&self) -> DebugDocBuilder {
DbgDocBldr::kind(self.syntax_shape_name().to_string())
}
}
| true |
a253c25dd769cc5de556acb9e2d1b9a16bcb18c9
|
Rust
|
KristianWahlroos/RustPractice
|
/smart_pointers/src/main.rs
|
UTF-8
| 3,072 | 3.390625 | 3 |
[] |
no_license
|
use List::{Cons, Nil};
use std::mem::drop;
use std::rc::Rc;
// enum List {
// Cons(i32, Box<List>),
// Nil,
// }
enum List {
Cons(i32, Rc<List>),
Nil,
}
fn main() {
// let list = Cons(1,
// Box::new(Cons(2,
// Box::new(Cons(3,
// Box::new(Nil))))));
let jou_list = Rc::new(Cons(1,
Rc::new(Cons(2,
Rc::new(Cons(3,
Rc::new(Nil)))))));
println!("There are {} jous at the x!", Rc::strong_count(&jou_list));
let jou_a_list = Cons(3, Rc::clone(&jou_list));
println!("There are {} jous at the x!", Rc::strong_count(&jou_list));
let jou_b_list = Cons(4, Rc::clone(&jou_list));
println!("There are {} jous at the x!", Rc::strong_count(&jou_list));
let x = 5;
let y = Box::new(x);
assert_eq!(5, *y);
let m = Box::new(String::from("Rust"));
hello(&m);
let n = Box::new(String::from("Rust"));
hello(&(*n)[..]);
let e = JouDrop {data: String::from("Drop the mic!")};
drop(e);
let c = JouDrop {data: String::from("Drop the jou program! JOU!")};
let d = JouDrop {data: String::from("Drop the mike!")};
}
fn hello(name: &str) {
println!("Hello {}", name);
}
struct JouDrop {
data : String,
}
impl Drop for JouDrop {
fn drop(&mut self) {
println!("Dropping jou jou {}", self.data);
}
}
pub trait Joussenger {
fn send(&self, msg: &str);
}
pub struct LimitTracker<'a, T: 'a + Joussenger> {
joussenger: &'a T,
value: usize,
max: usize,
}
impl<'a, T> LimitTracker<'a, T>
where T: Joussenger {
pub fn new(joussenger: &T, max: usize) -> LimitTracker<T> {
LimitTracker {
joussenger,
value: 0,
max,
}
}
pub fn set_value(&mut self, value:usize) {
self.value = value;
let percentage_of_max = self.value as f64 / self. max as f64;
if percentage_of_max >= 0.75 && percentage_of_max < 0.9 {
self.joussenger.send("Warning: You did bad, you used almost all your quota");
} else if percentage_of_max >= 0.9 && percentage_of_max < 1.0 {
self.joussenger.send("Urgent warning: Stop stupid, your quota is almost done");
} else if percentage_of_max >= 0.9 && percentage_of_max < 1.0 {
self.joussenger.send("Error: You are done for!");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
struct MockJoussenger {
sent_messages: RefCell<Vec<String>>,
}
impl MockJoussenger {
fn new() -> MockJoussenger {
MockJoussenger { sent_messages: RefCell::new(vec![]) }
}
}
impl Joussenger for MockJoussenger {
fn send(&self, message:&str) {
self.sent_messages.borrow_mut().push(String::from(message));
}
}
#[test]
fn it_send_over_75_pervent_warning_message() {
let mock_joussenger = MockJoussenger::new();
let mut limit_tracker = LimitTracker::new(&mock_joussenger, 100);
limit_tracker.set_value(89);
assert_eq!(mock_joussenger.sent_messages.borrow().len(), 1);
}
}
| true |
e53416dfc7e62efdeda659a36605bc0bcefe7f9c
|
Rust
|
realbigsean/lighthouse
|
/lcli/src/parse_ssz.rs
|
UTF-8
| 2,460 | 3.15625 | 3 |
[
"Apache-2.0"
] |
permissive
|
use clap::ArgMatches;
use clap_utils::parse_required;
use serde::Serialize;
use ssz::Decode;
use std::fs::File;
use std::io::Read;
use std::str::FromStr;
use types::*;
enum OutputFormat {
Json,
Yaml,
}
impl FromStr for OutputFormat {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"json" => Ok(Self::Json),
"yaml" => Ok(Self::Yaml),
_ => Err(format!("Invalid output format \"{}\"", s)),
}
}
}
pub fn run_parse_ssz<T: EthSpec>(matches: &ArgMatches) -> Result<(), String> {
let type_str = matches.value_of("type").ok_or("No type supplied")?;
let filename = matches.value_of("ssz-file").ok_or("No file supplied")?;
let format = parse_required(matches, "format")?;
let mut bytes = vec![];
let mut file =
File::open(filename).map_err(|e| format!("Unable to open {}: {}", filename, e))?;
file.read_to_end(&mut bytes)
.map_err(|e| format!("Unable to read {}: {}", filename, e))?;
info!("Using {} spec", T::spec_name());
info!("Type: {:?}", type_str);
match type_str {
"signed_block_base" => decode_and_print::<SignedBeaconBlockBase<T>>(&bytes, format)?,
"signed_block_altair" => decode_and_print::<SignedBeaconBlockAltair<T>>(&bytes, format)?,
"block_base" => decode_and_print::<BeaconBlockBase<T>>(&bytes, format)?,
"block_altair" => decode_and_print::<BeaconBlockAltair<T>>(&bytes, format)?,
"state_base" => decode_and_print::<BeaconStateBase<T>>(&bytes, format)?,
"state_altair" => decode_and_print::<BeaconStateAltair<T>>(&bytes, format)?,
other => return Err(format!("Unknown type: {}", other)),
};
Ok(())
}
fn decode_and_print<T: Decode + Serialize>(
bytes: &[u8],
output_format: OutputFormat,
) -> Result<(), String> {
let item = T::from_ssz_bytes(bytes).map_err(|e| format!("SSZ decode failed: {:?}", e))?;
match output_format {
OutputFormat::Json => {
println!(
"{}",
serde_json::to_string(&item)
.map_err(|e| format!("Unable to write object to JSON: {:?}", e))?
);
}
OutputFormat::Yaml => {
println!(
"{}",
serde_yaml::to_string(&item)
.map_err(|e| format!("Unable to write object to YAML: {:?}", e))?
);
}
}
Ok(())
}
| true |
d3a55370525a94b51149e86983ad4f2f8a1170fd
|
Rust
|
vaxpl/poller-rs
|
/src/epoll.rs
|
UTF-8
| 5,648 | 3.046875 | 3 |
[] |
no_license
|
//! Linux 增强型 I/O 事件通知。
//!
use crate::{Events, SysError};
use libc::{close, epoll_create1, epoll_ctl, epoll_wait};
use std::any::Any;
use std::collections::HashMap;
use std::sync::Arc;
impl From<u32> for Events {
fn from(val: u32) -> Self {
let mut events = Events::new();
if (val & libc::EPOLLIN as u32) == libc::EPOLLIN as u32 {
events = events.read();
}
if (val & libc::EPOLLOUT as u32) == libc::EPOLLOUT as u32 {
events = events.write();
}
if (val & libc::EPOLLERR as u32) == libc::EPOLLERR as u32 {
events = events.error();
}
events
}
}
impl Into<u32> for Events {
fn into(self) -> u32 {
let mut events = 0u32;
if self.has_read() {
events |= libc::EPOLLIN as u32;
}
if self.has_write() {
events |= libc::EPOLLOUT as u32;
}
if self.has_error() {
events |= libc::EPOLLERR as u32;
}
events
}
}
/// 定义事件关联上下文。
pub type EventContext = Arc<dyn Any + Send + Sync>;
/// 定义事件数据。
///
/// # Fields
/// * `0` - 触发的文件描述符。
/// * `1` - 触发的事件集合。
/// * `2` - 触发的事件对应上下文。
pub type EventData<'a> = (i32, Events, Option<&'a EventContext>);
/// 定义文件 I/O 事件通知器。
///
/// 每个实例可以管理多个 `fd` 的 I/O 事件。
#[derive(Debug)]
pub struct Poller {
epoll_fd: i32,
watches: HashMap<i32, (Events, Option<EventContext>)>,
}
impl Default for Poller {
fn default() -> Self {
Self {
epoll_fd: -1,
watches: HashMap::new(),
}
}
}
impl Drop for Poller {
fn drop(&mut self) {
if self.epoll_fd > 0 {
unsafe {
close(self.epoll_fd);
};
self.epoll_fd = -1;
}
}
}
impl Poller {
/// 创建一个新的 I/O 事件通知器。
pub fn new() -> Result<Self, SysError> {
let epoll_fd = unsafe { epoll_create1(0) };
if epoll_fd < 0 {
Err(SysError::last())
} else {
Ok(Self {
epoll_fd,
watches: HashMap::new(),
})
}
}
/// 添加一个文件描述符到监视列表中。
///
/// **注意:** 此函数不会把 `fd` 的所有权转移到 `Poller` 内,请确保在 `Poller` 活动期内 `fd` 都是可用的。
pub fn add(
&mut self,
fd: i32,
events: Events,
ctx: Option<EventContext>,
) -> Result<(), SysError> {
unsafe {
let mut ev = libc::epoll_event {
events: events.into(),
u64: fd as u64,
};
let err = epoll_ctl(self.epoll_fd, libc::EPOLL_CTL_ADD, fd, &mut ev);
if err < 0 {
return Err(SysError::last());
}
self.watches.insert(fd, (events, ctx));
Ok(())
}
}
/// 将一个文件描述符从监视列表中移除。
pub fn remove(&mut self, fd: i32) -> Result<(), SysError> {
if !self.watches.contains_key(&fd) {
return Err(SysError::from(libc::ENOENT));
}
let err =
unsafe { epoll_ctl(self.epoll_fd, libc::EPOLL_CTL_DEL, fd, std::ptr::null_mut()) };
if err < 0 {
Err(SysError::last())
} else {
self.watches.remove(&fd).unwrap();
Ok(())
}
}
/// 拉取所有被监测到的 I/O 事件。
///
/// # Examples
///
/// ```
/// use poller::{Events, Poller};
/// let mut poller = Poller::new().unwrap();
/// poller.add(1, Events::new().write(), None).unwrap();
/// for (fd, events, ctx) in poller.pull_events(1000).unwrap().iter() {
/// println!("Fd={}, Events={}, Context={:?}", fd, events, ctx);
/// }
/// ```
pub fn pull_events(&self, timeout_ms: i32) -> Result<Vec<EventData>, SysError> {
unsafe {
let mut ev: Vec<libc::epoll_event> = Vec::with_capacity(self.watches.len());
let nfds = epoll_wait(
self.epoll_fd,
ev.as_mut_ptr(),
self.watches.len() as i32,
timeout_ms,
);
if nfds < 0 {
return Err(SysError::last());
}
ev.set_len(nfds as usize);
Ok(ev
.into_iter()
.map(|x| {
if let Some(v) = self.watches.get(&(x.u64 as i32)) {
(x.u64 as i32, Events::from(x.events), v.1.as_ref())
} else {
(x.u64 as i32, Events::from(x.events), None)
}
})
.collect())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_poller() {
unsafe {
let cstr = std::ffi::CString::new("/proc/uptime").unwrap();
let fd = libc::open(cstr.as_ptr(), libc::O_RDONLY);
let mut poller = Poller::new().unwrap();
assert_eq!(poller.add(fd, Events::new().read(), None).is_ok(), true);
for _ in 0..1000 {
assert_eq!(poller.pull_events(1000).unwrap().len(), 1);
}
assert_eq!(poller.remove(fd).is_ok(), true);
for _ in 0..1000 {
assert_eq!(poller.add(fd, Events::new().read(), None).is_ok(), true);
assert_eq!(poller.remove(fd).is_ok(), true);
}
libc::close(fd);
}
}
}
| true |
7cf2693d8ce74f7042c34ec4d7928e25f0e92e66
|
Rust
|
zeyonaut/mun
|
/crates/mun_codegen/src/ir/function.rs
|
UTF-8
| 3,106 | 2.65625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use crate::ir::{body::BodyIrGenerator, dispatch_table::DispatchTable, type_table::TypeTable};
use crate::{CodeGenParams, IrDatabase, Module, OptimizationLevel};
use inkwell::passes::{PassManager, PassManagerBuilder};
use inkwell::types::AnyTypeEnum;
use inkwell::values::FunctionValue;
use super::body::ExternalGlobals;
use std::collections::HashMap;
/// Constructs a PassManager to optimize functions for the given optimization level.
pub(crate) fn create_pass_manager(
module: &Module,
optimization_lvl: OptimizationLevel,
) -> PassManager<FunctionValue> {
let pass_builder = PassManagerBuilder::create();
pass_builder.set_optimization_level(optimization_lvl);
let function_pass_manager = PassManager::create(module);
pass_builder.populate_function_pass_manager(&function_pass_manager);
function_pass_manager.initialize();
function_pass_manager
}
/// Generates a `FunctionValue` for a `hir::Function`. This function does not generate a body for
/// the `hir::Function`. That task is left to the `gen_body` function. The reason this is split
/// between two functions is that first all signatures are generated and then all bodies. This
/// allows bodies to reference `FunctionValue` wherever they are declared in the file.
pub(crate) fn gen_signature(
db: &dyn IrDatabase,
f: hir::Function,
module: &Module,
params: CodeGenParams,
) -> FunctionValue {
let name = {
let name = f.name(db.upcast()).to_string();
if params.make_marshallable {
format!("{}_wrapper", name)
} else {
name
}
};
if let AnyTypeEnum::FunctionType(ty) = db.type_ir(f.ty(db.upcast()), params) {
module.add_function(&name, ty, None)
} else {
panic!("not a function type")
}
}
/// Generates the body of a `hir::Function` for an associated `FunctionValue`.
pub(crate) fn gen_body<'a, 'b>(
db: &'a dyn IrDatabase,
function: (hir::Function, FunctionValue),
llvm_functions: &'a HashMap<hir::Function, FunctionValue>,
dispatch_table: &'b DispatchTable,
type_table: &'b TypeTable,
external_globals: ExternalGlobals,
) {
let mut code_gen = BodyIrGenerator::new(
db,
function,
llvm_functions,
dispatch_table,
type_table,
CodeGenParams {
make_marshallable: false,
},
external_globals,
);
code_gen.gen_fn_body();
}
/// Generates the body of a wrapper around `hir::Function` for its associated
/// `FunctionValue`
pub(crate) fn gen_wrapper_body<'a, 'b>(
db: &'a dyn IrDatabase,
function: (hir::Function, FunctionValue),
llvm_functions: &'a HashMap<hir::Function, FunctionValue>,
dispatch_table: &'b DispatchTable,
type_table: &'b TypeTable,
external_globals: ExternalGlobals,
) {
let mut code_gen = BodyIrGenerator::new(
db,
function,
llvm_functions,
dispatch_table,
type_table,
CodeGenParams {
make_marshallable: true,
},
external_globals,
);
code_gen.gen_fn_wrapper();
}
| true |
50cc8565519c77b3ee5768b9fde9034f87eec736
|
Rust
|
shaneutt/krustlet
|
/tests/podsmiter/src/main.rs
|
UTF-8
| 6,848 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::fmt::Display;
use k8s_openapi::api::{
core::v1::{Namespace, Pod},
storage::v1::StorageClass,
};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
use k8s_openapi::Metadata;
use kube::api::{Api, DeleteParams, ListParams};
const E2E_NS_PREFIXES: &[&str] = &["wasi-e2e"];
#[tokio::main(flavor = "multi_thread")]
async fn main() -> anyhow::Result<()> {
let result = smite_all_integration_test_resources().await;
match &result {
Ok(message) => println!("{}", message),
Err(e) => println!("{}", e),
};
result.map(|_| ())
}
async fn smite_all_integration_test_resources() -> anyhow::Result<&'static str> {
let client = match kube::Client::try_default().await {
Ok(c) => c,
Err(e) => {
return Err(anyhow::anyhow!(
"Failed to acquire Kubernetes client: {}",
e
))
}
};
let namespaces = list_e2e_namespaces(client.clone()).await?;
let storageclasses = list_storageclasses(client.clone()).await?;
if namespaces.is_empty() && storageclasses.is_empty() {
return Ok("No e2e namespaces or StorageClasses found");
}
if !confirm_smite(&namespaces, &storageclasses) {
return Ok("Operation cancelled");
}
let pod_smite_operations = namespaces
.iter()
.map(|ns| smite_namespace_pods(client.clone(), ns));
let pod_smite_results = futures::future::join_all(pod_smite_operations).await;
let (_, pod_smite_errors) = pod_smite_results.partition_success();
if !pod_smite_errors.is_empty() {
return Err(smite_failure_error(&pod_smite_errors));
}
println!("Requested force-delete of all pods; requesting delete of namespaces...");
Smiter::new(namespaces, None, DeleteParams::default())
.smite::<Namespace>(client.clone())
.await?;
println!("Requesting delete of storage classes...");
Smiter::new(storageclasses, None, DeleteParams::default())
.smite::<StorageClass>(client)
.await?;
Ok("All e2e resources force-deleted; namespace cleanup may take a couple of minutes")
}
async fn list_e2e_namespaces(client: kube::Client) -> anyhow::Result<Vec<String>> {
println!("Finding e2e namespaces...");
let nsapi: Api<Namespace> = Api::all(client.clone());
let nslist = nsapi.list(&ListParams::default()).await?;
Ok(nslist
.iter()
.map(name_of)
.filter(|s| is_e2e_resource(s.as_str()))
.collect())
}
fn name_of(ns: &impl Metadata<Ty = ObjectMeta>) -> String {
ns.metadata().name.as_ref().unwrap().to_owned()
}
fn is_e2e_resource(item: &str) -> bool {
E2E_NS_PREFIXES
.iter()
.any(|prefix| item.starts_with(prefix))
}
async fn smite_namespace_pods(client: kube::Client, namespace: &str) -> anyhow::Result<()> {
println!("Finding pods in namespace {}...", namespace);
let podapi: Api<Pod> = Api::namespaced(client.clone(), namespace);
let pods = podapi.list(&ListParams::default()).await?;
let names_to_delete = pods
.into_iter()
.map(|p| p.metadata.name.unwrap_or_default())
.collect();
println!("Deleting pods in namespace {}...", namespace);
let smiter = Smiter::new(
names_to_delete,
Some(namespace.to_owned()),
DeleteParams {
grace_period_seconds: Some(0),
..DeleteParams::default()
},
);
smiter.smite::<Pod>(client).await
}
fn smite_failure_error<T: Display>(errors: &[T]) -> anyhow::Error {
let message_list = errors
.iter()
.map(|e| format!("{}", e))
.collect::<Vec<_>>()
.join("\n");
anyhow::anyhow!(
"Some integration test resources were not cleaned up:\n{}",
message_list
)
}
fn confirm_smite(namespaces: &[String], storageclasses: &[String]) -> bool {
println!(
"Smite these resources and namespaces (all resources within it)?:\nNamespaces: {}\nStorageClasses: {} (y/n) ",
namespaces.join(", "),
storageclasses.join(", "),
);
let mut response = String::new();
match std::io::stdin().read_line(&mut response) {
Err(e) => {
eprintln!("Error reading response: {}", e);
confirm_smite(namespaces, storageclasses)
}
Ok(_) => response.starts_with('y') || response.starts_with('Y'),
}
}
async fn list_storageclasses(client: kube::Client) -> anyhow::Result<Vec<String>> {
let sc: Api<StorageClass> = Api::all(client);
let all = sc.list(&ListParams::default()).await?;
Ok(all
.items
.into_iter()
.map(|class| class.metadata.name.unwrap_or_default())
.filter(|s| is_e2e_resource(s.as_str()))
.collect())
}
struct Smiter {
names_to_smite: Vec<String>,
namespace: Option<String>,
params: DeleteParams,
}
impl Smiter {
fn new(names_to_smite: Vec<String>, namespace: Option<String>, params: DeleteParams) -> Self {
Smiter {
names_to_smite,
namespace,
params,
}
}
async fn smite<T>(self, client: kube::Client) -> anyhow::Result<()>
where
T: kube::Resource + Clone + serde::de::DeserializeOwned + std::fmt::Debug,
<T as kube::Resource>::DynamicType: Default,
{
let api: Api<T> = match self.namespace.as_ref() {
Some(ns) => Api::namespaced(client, ns),
None => Api::all(client),
};
let smite_operations = self
.names_to_smite
.iter()
.map(|name| (name, api.clone(), self.params.clone()))
.map(|(name, api, params)| async move {
api.delete(name, ¶ms).await?;
Ok::<_, kube::Error>(())
});
let smite_results = futures::future::join_all(smite_operations).await;
let (_, smite_errors) = smite_results.partition_success();
if !smite_errors.is_empty() {
return Err(smite_failure_error(&smite_errors));
}
Ok(())
}
}
// TODO: deduplicate with oneclick
trait ResultSequence {
type SuccessItem;
type FailureItem;
fn partition_success(self) -> (Vec<Self::SuccessItem>, Vec<Self::FailureItem>);
}
impl<T, E: std::fmt::Debug> ResultSequence for Vec<Result<T, E>> {
type SuccessItem = T;
type FailureItem = E;
fn partition_success(self) -> (Vec<Self::SuccessItem>, Vec<Self::FailureItem>) {
let (success_results, error_results): (Vec<_>, Vec<_>) =
self.into_iter().partition(|r| r.is_ok());
let success_values = success_results.into_iter().map(|r| r.unwrap()).collect();
let error_values = error_results
.into_iter()
.map(|r| r.err().unwrap())
.collect();
(success_values, error_values)
}
}
| true |
0def211ac65659fd9f90773201edfb88836b5452
|
Rust
|
rchaser53/miri-slide-demo
|
/src/outof_index.rs
|
UTF-8
| 68 | 2.78125 | 3 |
[] |
no_license
|
fn outof_index() {
let a = [1, 2, 3];
let b = 3;
a[b];
}
| true |
f859fc6321886ea8ecf5993bd993af2f12ab4f36
|
Rust
|
bmellstrom/ocs-server-dummy
|
/src/diameter/avp_parsers.rs
|
UTF-8
| 1,062 | 2.78125 | 3 |
[
"ISC"
] |
permissive
|
use std::result::Result;
use byteorder::{ByteOrder, BigEndian};
use super::ParseError;
use super::avps::AvpId;
use super::avp_header::AvpHeader;
pub type ParserFn<T> = Fn(AvpId, &[u8], &mut T) -> Result<(), ParseError>;
pub fn parse_avps<T>(buffer: &[u8], avp_parser: &ParserFn<T>, result: &mut T) -> Result<(), ParseError> {
let mut pos = 0;
while pos < buffer.len() {
let header = AvpHeader::parse(&buffer[pos..])?;
let padded_len = round_up(header.total_len());
if padded_len > buffer.len() - pos {
return Err(ParseError::InvalidAvpLength);
}
let start = pos + header.header_len();
let end = pos + header.total_len();
avp_parser(header.avp_id, &buffer[start..end], result)?;
pos += padded_len;
}
Ok(())
}
fn round_up(value: usize) -> usize {
(value + 3) & 0xFFFFFFFFFFFFFFFC
}
pub fn parse_u32(buffer: &[u8]) -> Result<u32, ParseError> {
if buffer.len() != 4 {
return Err(ParseError::InvalidAvpLength);
}
Ok(BigEndian::read_u32(buffer))
}
| true |
aa78926e650c2027d16b5e2d6e9c0c13d3fc5ea5
|
Rust
|
davidbegin/messin-with-iterators
|
/src/deep_dive.rs
|
UTF-8
| 960 | 3.96875 | 4 |
[] |
no_license
|
pub fn iterator_classes() {
println!("3 components of iterators:");
println!("\t * iterators give you a sequence of values");
println!("\t * iterator adapters operate on an iterator and returns a new iterator");
println!("\t * consumers operator on iterators and return a final set of values");
consumers();
}
fn consumers() {
let collected_values = vec![1, 2, 3].iter().map(|&i| i + 1).collect::<Vec<_>>();
// vec![1, 2, 3].iter().map(|&i| i + 1);
// when we pass x to find, it is borrowed, so we can't do a comparison against it
//
// so we have to deference it
vec![1, 2, 3].iter().map(|&i| i + 1).find(|x| *x > 2);
// find returns an option
let the_one_i_was_looking_for = vec![1, 2, 3].iter().map(|&i| i + 1).find(|i| *i > 2);
option_taker(the_one_i_was_looking_for);
}
fn option_taker(found_number: Option<i32>) {
println!("\nunwrapping options like a boss: {}", found_number.unwrap());
}
| true |
ddb8c5c22afa5f10a0b602418b5434fb89414cad
|
Rust
|
wt/pciids
|
/src/pci_id_data.rs
|
UTF-8
| 54,895 | 2.78125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::collections::HashMap;
use std::concat;
use anyhow::{anyhow, Context, Result};
use log::{debug, info};
use pest::Parser;
use pest_derive::Parser;
#[derive(Debug)]
pub struct PciIdData {
vendors: PciVendors,
classes: PciClasses,
}
impl PciIdData {
pub fn new() -> Self {
PciIdData {
vendors: PciVendors::new(),
classes: PciClasses::new(),
}
}
}
impl Default for PciIdData {
fn default() -> Self {
Self::new()
}
}
impl PciIdData {
pub fn add_pci_ids_data(&mut self, pciids_data_stream: &mut dyn std::io::Read) -> Result<()> {
let mut num_vendors = 0;
let mut num_classes = 0;
info!("Parsing pci.id data!");
let mut unparsed_data = String::new();
pciids_data_stream.read_to_string(&mut unparsed_data)?;
if let Ok(parse) = PciIdsParser::parse(Rule::file, &unparsed_data) {
for line_pair in parse {
match line_pair.as_rule() {
Rule::vendor => {
num_vendors += 1;
debug!("vendor: {:#?}", &line_pair);
self.add_vendor_from_vendor_pairs(&mut line_pair.into_inner())?;
}
Rule::class => {
num_classes += 1;
debug!("class: {:#?}", &line_pair);
self.add_class_from_class_pairs(&mut line_pair.into_inner())?;
}
Rule::EOI => info!("End of input reached."),
_ => unreachable!(),
}
}
info!(
concat!(
"Number of objects imported from the pci.ids database: ",
"vendors({}) and classes({})",
),
num_vendors, num_classes
);
} else {
info!("Couldn't parse pci.ids file.");
}
Ok(())
}
fn add_vendor_from_vendor_pairs(
&mut self,
vendor_pairs: &mut pest::iterators::Pairs<Rule>,
) -> Result<()> {
let vendor_id_pair = vendor_pairs
.next()
.ok_or_else(|| anyhow!("No vendor id found."))?;
let vendor_id = u16::from_str_radix(vendor_id_pair.as_str(), 16)
.with_context(|| format!("Invalid vendor_id: {}", vendor_id_pair.as_str()))?;
let vendor_name = vendor_pairs
.next()
.ok_or_else(|| anyhow!("No vendor name found."))?
.as_str();
let mut pci_vendor = PciVendor::new(vendor_id, &vendor_name);
for device_pair in vendor_pairs {
pci_vendor.add_device_from_device_pairs(&mut device_pair.into_inner())?;
}
self.vendors.entry(vendor_id).or_insert(pci_vendor);
Ok(())
}
pub fn get_vendor(&self, vendor_id: &u16) -> Result<&PciVendor> {
Ok(self
.vendors
.get(&vendor_id)
.ok_or_else(|| anyhow!("Vendor {} not found.", vendor_id))?)
}
fn add_class_from_class_pairs(
&mut self,
class_pairs: &mut pest::iterators::Pairs<Rule>,
) -> Result<()> {
let class_id_pair = class_pairs
.next()
.ok_or_else(|| anyhow!("No class id found."))?;
let class_id = u8::from_str_radix(class_id_pair.as_str(), 16)
.with_context(|| format!("Invalid class_id: {}", class_id_pair.as_str()))?;
let class_name = class_pairs
.next()
.ok_or_else(|| anyhow!("No class name found."))?
.as_str();
let mut class = PciClass::new(class_id, &class_name);
for subclass_pair in class_pairs {
class.add_subclass_from_subclass_pairs(&mut subclass_pair.into_inner())?;
}
self.classes.entry(class_id).or_insert(class);
Ok(())
}
pub fn get_class(&self, class_id: &u8) -> Result<&PciClass> {
Ok(self
.classes
.get(&class_id)
.ok_or_else(|| anyhow!("Class {} not found.", class_id))?)
}
}
type PciVendors = HashMap<u16, PciVendor>;
#[derive(Debug)]
pub struct PciVendor {
pub id: u16,
pub name: String,
devices: HashMap<u16, PciDevice>,
}
impl PciVendor {
fn new(id: u16, name: &str) -> Self {
PciVendor {
id,
name: String::from(name),
devices: HashMap::new(),
}
}
fn add_device_from_device_pairs(
&mut self,
device_pairs: &mut pest::iterators::Pairs<Rule>,
) -> Result<()> {
let device_id_pair = device_pairs
.next()
.ok_or_else(|| anyhow!("No device id found."))?;
let device_id = u16::from_str_radix(device_id_pair.as_str(), 16)
.with_context(|| format!("Invalid device: {}", device_id_pair.as_str()))?;
let device_name = device_pairs
.next()
.ok_or_else(|| anyhow!("No device name found."))?
.as_str();
let mut pci_device = PciDevice::new(device_id, &device_name);
for subsystem_pair in device_pairs {
pci_device.add_subsystem_from_subsystem_pairs(&mut subsystem_pair.into_inner())?;
}
self.devices.entry(device_id).or_insert(pci_device);
Ok(())
}
pub fn get_device(&self, device_id: &u16) -> Result<&PciDevice> {
Ok(self
.devices
.get(&device_id)
.ok_or_else(|| anyhow!("Device {} not found.", device_id))?)
}
}
impl PartialEq for PciVendor {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.name == other.name
}
}
impl Eq for PciVendor {}
#[derive(Debug)]
pub struct PciDevice {
pub id: u16,
pub name: String,
subsystems: HashMap<(u16, u16), PciSubsystem>,
}
impl PciDevice {
fn new(id: u16, name: &str) -> Self {
PciDevice {
id,
name: String::from(name),
subsystems: HashMap::new(),
}
}
fn add_subsystem_from_subsystem_pairs(
&mut self,
subsystem_pairs: &mut pest::iterators::Pairs<Rule>,
) -> Result<()> {
let subsystem_id_pair = subsystem_pairs
.next()
.ok_or_else(|| anyhow!("No subsystem id found."))?;
let mut subsystem_id_inners = match subsystem_id_pair.as_rule() {
Rule::subsystem_id => Ok(subsystem_id_pair.into_inner()),
_ => Err(anyhow!("Tried to add non subsystem to subsystem data.")),
}?;
let subvendor_id_pair = subsystem_id_inners
.next()
.ok_or_else(|| anyhow!("No subvendor id found."))?;
let subvendor_id = u16::from_str_radix(subvendor_id_pair.as_str(), 16)?;
debug!("subvendor_id_pair: {:#?}", &subvendor_id_pair);
let subdevice_id_pair = subsystem_id_inners
.next()
.ok_or_else(|| anyhow!("No subdevice id found."))?;
let subdevice_id = u16::from_str_radix(subdevice_id_pair.as_str(), 16)?;
let subsystem_name = subsystem_pairs
.next()
.ok_or_else(|| anyhow!("No subsystem name found."))?
.as_str();
let pci_subsystem = PciSubsystem::new(subvendor_id, subdevice_id, &subsystem_name);
self.subsystems
.entry((subvendor_id, subdevice_id))
.or_insert(pci_subsystem);
Ok(())
}
pub fn get_subsystem(&self, subsystem_id: &(u16, u16)) -> Result<&PciSubsystem> {
Ok(self
.subsystems
.get(&subsystem_id)
.ok_or_else(|| anyhow!("Subsystem {} {} not found.", subsystem_id.0, subsystem_id.1))?)
}
}
impl PartialEq for PciDevice {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.name == other.name
}
}
impl Eq for PciDevice {}
#[derive(Debug)]
pub struct PciSubsystem {
pub subvendor_id: u16,
pub subdevice_id: u16,
pub name: String,
}
impl PciSubsystem {
fn new(subvendor_id: u16, subdevice_id: u16, name: &str) -> Self {
PciSubsystem {
subvendor_id,
subdevice_id,
name: String::from(name),
}
}
}
impl PartialEq for PciSubsystem {
fn eq(&self, other: &Self) -> bool {
self.subvendor_id == other.subvendor_id
&& self.subdevice_id == other.subdevice_id
&& self.name == other.name
}
}
impl Eq for PciSubsystem {}
type PciClasses = HashMap<u8, PciClass>;
#[derive(Debug)]
pub struct PciClass {
pub id: u8,
pub name: String,
subclasses: HashMap<u8, PciSubclass>,
}
impl PciClass {
fn new(id: u8, name: &str) -> Self {
PciClass {
id,
name: String::from(name),
subclasses: HashMap::new(),
}
}
fn add_subclass_from_subclass_pairs(
&mut self,
subclass_pairs: &mut pest::iterators::Pairs<Rule>,
) -> Result<()> {
let subclass_id_pair = subclass_pairs
.next()
.ok_or_else(|| anyhow!("No subclass id found."))?;
let subclass_id = u8::from_str_radix(subclass_id_pair.as_str(), 16)
.with_context(|| format!("Invalid subclass: {}", subclass_id_pair.as_str()))?;
let subclass_name = subclass_pairs
.next()
.ok_or_else(|| anyhow!("No subclass name found."))?
.as_str();
let mut subclass = PciSubclass::new(subclass_id, &subclass_name);
for prog_if_pair in subclass_pairs {
subclass.add_prog_if_from_prog_if_pairs(&mut prog_if_pair.into_inner())?;
}
self.subclasses.entry(subclass_id).or_insert(subclass);
Ok(())
}
pub fn get_subclass(&self, subclass_id: &u8) -> Result<&PciSubclass> {
Ok(self
.subclasses
.get(&subclass_id)
.ok_or_else(|| anyhow!("Subclass {} not found.", subclass_id))?)
}
}
impl PartialEq for PciClass {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.name == other.name
}
}
impl Eq for PciClass {}
#[derive(Debug)]
pub struct PciSubclass {
pub id: u8,
pub name: String,
prog_interfaces: HashMap<u8, PciProgInterface>,
}
impl PciSubclass {
fn new(id: u8, name: &str) -> Self {
PciSubclass {
id,
name: String::from(name),
prog_interfaces: HashMap::new(),
}
}
fn add_prog_if_from_prog_if_pairs(
&mut self,
prog_if_pairs: &mut pest::iterators::Pairs<Rule>,
) -> Result<()> {
let prog_if_id_pair = prog_if_pairs
.next()
.ok_or_else(|| anyhow!("No programming interface id found."))?;
let prog_if_id = u8::from_str_radix(prog_if_id_pair.as_str(), 16).with_context(|| {
format!(
"Invalid programming interface: {}",
prog_if_id_pair.as_str()
)
})?;
let prog_if_name = prog_if_pairs
.next()
.ok_or_else(|| anyhow!("No programming interface name found."))?
.as_str();
let prog_if = PciProgInterface::new(prog_if_id, &prog_if_name);
self.prog_interfaces.entry(prog_if_id).or_insert(prog_if);
Ok(())
}
pub fn get_prog_interface(&self, prog_interface_id: &u8) -> Result<&PciProgInterface> {
Ok(self
.prog_interfaces
.get(&prog_interface_id)
.ok_or_else(|| anyhow!("Programming interface {} not found.", prog_interface_id))?)
}
}
impl PartialEq for PciSubclass {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.name == other.name
}
}
impl Eq for PciSubclass {}
#[derive(Debug)]
pub struct PciProgInterface {
pub id: u8,
pub name: String,
}
impl PciProgInterface {
fn new(id: u8, name: &str) -> Self {
PciProgInterface {
id,
name: String::from(name),
}
}
}
impl PartialEq for PciProgInterface {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.name == other.name
}
}
impl Eq for PciProgInterface {}
#[derive(Parser)]
#[grammar = "pciids.pest"]
struct PciIdsParser;
#[cfg(test)]
mod tests {
use super::*;
use pest::consumes_to;
use rand::{Rng, SeedableRng};
use std::vec::Vec;
fn hex_char_width<T>() -> usize {
2 * std::mem::size_of::<T>()
}
fn as_max_len_hex_string<T: std::fmt::UpperHex>(n: T) -> String {
format!("{:0width$X}", n, width = hex_char_width::<T>())
}
struct FakeVendorData {
expected_id: u16,
expected_id_hex_string: String,
expected_name: String,
unparsed_data: String,
simple_unparsed_data: String,
devices: Vec<FakeDeviceData>,
}
impl FakeVendorData {
fn new_with_devices(devices: Vec<FakeDeviceData>) -> Self {
let expected_id = rand::random::<_>();
let expected_name = format!("Fake vendor ({})", as_max_len_hex_string(expected_id));
let simple_unparsed_data =
format!("{} {}", as_max_len_hex_string(expected_id), expected_name);
let full_unparsed_data = devices
.iter()
.map(|d| d.unparsed_data.clone())
.fold(simple_unparsed_data.clone(), |acc, x| {
format!("{}\n{}", acc, x)
});
FakeVendorData {
expected_id: expected_id,
expected_id_hex_string: as_max_len_hex_string(expected_id),
expected_name: expected_name.clone(),
unparsed_data: full_unparsed_data,
simple_unparsed_data: simple_unparsed_data,
devices: devices,
}
}
fn new() -> Self {
Self::new_with_devices(Vec::<_>::new())
}
fn check(&self, vendor: &PciVendor) -> Result<()> {
assert_eq!(vendor.id, self.expected_id);
assert_eq!(vendor.name, self.expected_name);
Ok(())
}
}
#[test]
fn test_vendor_simple_parse() -> Result<()> {
let fake_vendor_data = FakeVendorData::new();
println!("Unparsed_data: {:?}", &fake_vendor_data.unparsed_data);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_vendor_data.unparsed_data,
rule: Rule::vendor,
tokens: [
vendor(0, fake_vendor_data.unparsed_data.len(), [
vendor_id(0, 4),
vendor_name(5, fake_vendor_data.unparsed_data.len())
])
]
};
let mut parsed_data = PciIdsParser::parse(Rule::vendor, &fake_vendor_data.unparsed_data)?;
let vendor_pair = parsed_data.next().ok_or(anyhow!("No vendor line."))?;
let mut vendor_inners = match vendor_pair.as_rule() {
Rule::vendor => Ok(vendor_pair.into_inner()),
x => Err(anyhow!(format!(
"Vendor line didn't parse as such. Parsed as {:?}",
x
))),
}?;
let end = parsed_data.next();
assert!(end.is_none(), "Something found after vendor line.");
let vendor_id_pair = vendor_inners.next().ok_or(anyhow!("No vendor id."))?;
assert_eq!(
vendor_id_pair.as_str(),
fake_vendor_data.expected_id_hex_string,
"Vendor id doesn't match."
);
let vendor_name_pair = vendor_inners.next().ok_or(anyhow!("No vendor name."))?;
assert_eq!(
vendor_name_pair.as_str(),
fake_vendor_data.expected_name,
"Vendor name doesn't match."
);
let end = vendor_inners.next();
assert!(end.is_none(), "Something found after vendor name.");
Ok(())
}
#[test]
fn test_vendor_simple_add() -> Result<()> {
let fake_vendor_data = FakeVendorData::new();
println!("Unparsed_data: {:?}", &fake_vendor_data.unparsed_data);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_vendor_data.unparsed_data,
rule: Rule::vendor,
tokens: [
vendor(0, fake_vendor_data.unparsed_data.len(), [
vendor_id(0, 4),
vendor_name(5, fake_vendor_data.unparsed_data.len())
])
]
};
let mut parsed_vendor = PciIdsParser::parse(Rule::vendor, &fake_vendor_data.unparsed_data)?;
println!("parsed_vendor: {:#?}", &parsed_vendor);
let vendor_pair = parsed_vendor.next().context("No parsed vendor.")?;
println!("vendor_pair: {:#?}", &vendor_pair);
let mut pci_data = PciIdData::new();
pci_data.add_vendor_from_vendor_pairs(&mut vendor_pair.into_inner())?;
let vendor = &pci_data.get_vendor(&fake_vendor_data.expected_id)?;
fake_vendor_data.check(vendor)?;
Ok(())
}
#[test]
fn test_vendor_complex_add() -> Result<()> {
let fake_subsystem_data = FakeSubsystemData::new();
let fake_device_data = FakeDeviceData::new_with_subsystems(vec![fake_subsystem_data]);
let fake_vendor_data = FakeVendorData::new_with_devices(vec![fake_device_data]);
println!("Unparsed_data: {:?}", &fake_vendor_data.unparsed_data);
let vendor_end = fake_vendor_data.simple_unparsed_data.len();
let device_start = vendor_end + 1;
println!("{}", device_start);
let device_end = device_start + fake_vendor_data.devices[0].simple_unparsed_data.len();
println!("{}", device_end);
let subsystem_start = device_end + 1;
pest::parses_to! {
parser: PciIdsParser,
input: &fake_vendor_data.unparsed_data,
rule: Rule::vendor,
tokens: [
vendor(0, fake_vendor_data.unparsed_data.len(), [
vendor_id(0, 4),
vendor_name(5, vendor_end),
device(device_start + 0, fake_vendor_data.unparsed_data.len(), [
device_id(device_start + 1, device_start + 5),
device_name(device_start + 6, device_end),
subsystem(subsystem_start, fake_vendor_data.unparsed_data.len(), [
subsystem_id(subsystem_start + 2, subsystem_start+11, [
subvendor_id(subsystem_start+2, subsystem_start+6),
subdevice_id(subsystem_start+7, subsystem_start+11)
]),
subsystem_name(subsystem_start+12, fake_vendor_data.unparsed_data.len()),
])
])
])
]
};
let mut parsed_vendor = PciIdsParser::parse(Rule::vendor, &fake_vendor_data.unparsed_data)?;
println!("parsed_vendor: {:#?}", &parsed_vendor);
let vendor_pair = parsed_vendor.next().context("No parsed vendor.")?;
println!("vendor_pair: {:#?}", &vendor_pair);
let mut pci_data = PciIdData::new();
pci_data.add_vendor_from_vendor_pairs(&mut vendor_pair.into_inner())?;
println!("pci_data: {:#?}", pci_data);
let vendor = &pci_data.get_vendor(&fake_vendor_data.expected_id)?;
fake_vendor_data.check(&vendor)?;
let device = &vendor.get_device(&fake_vendor_data.devices[0].expected_id)?;
fake_vendor_data.devices[0].check(device)?;
let subsystem = &device.get_subsystem(&(
fake_vendor_data.devices[0].subsystems[0].expected_subvendor_id,
fake_vendor_data.devices[0].subsystems[0].expected_subdevice_id,
))?;
fake_vendor_data.devices[0].subsystems[0].check(&subsystem)?;
Ok(())
}
struct FakeDeviceData {
expected_id: u16,
expected_id_hex_string: String,
expected_name: String,
unparsed_data: String,
simple_unparsed_data: String,
subsystems: Vec<FakeSubsystemData>,
}
impl FakeDeviceData {
fn new_with_subsystems(subsystems: Vec<FakeSubsystemData>) -> Self {
let expected_id = rand::random::<_>();
let expected_id_hex_string = as_max_len_hex_string(expected_id);
let expected_name = format!("Fake device ({})", as_max_len_hex_string(expected_id));
let simple_unparsed_data =
format!("\t{} {}", as_max_len_hex_string(expected_id), expected_name);
let full_unparsed_data = subsystems
.iter()
.map(|d| d.unparsed_data.clone())
.fold(simple_unparsed_data.clone(), |acc, x| {
format!("{}\n{}", acc, x)
});
FakeDeviceData {
expected_id: expected_id,
expected_id_hex_string: expected_id_hex_string.clone(),
expected_name: expected_name.clone(),
unparsed_data: full_unparsed_data,
simple_unparsed_data: simple_unparsed_data,
subsystems: subsystems,
}
}
fn new() -> Self {
Self::new_with_subsystems(Vec::<_>::new())
}
fn check(&self, device: &PciDevice) -> Result<()> {
assert_eq!(device.id, self.expected_id);
assert_eq!(device.name, self.expected_name);
Ok(())
}
}
#[test]
fn test_device_simple_parse() -> Result<()> {
let fake_device_data = FakeDeviceData::new();
println!("Unparsed_data: {:?}", &fake_device_data.unparsed_data);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_device_data.unparsed_data,
rule: Rule::device,
tokens: [
device(0, fake_device_data.unparsed_data.len(), [
device_id(1, 5),
device_name(6, fake_device_data.unparsed_data.len())
])
]
};
let mut parsed_device = PciIdsParser::parse(Rule::device, &fake_device_data.unparsed_data)?;
let device_pair = parsed_device.next().ok_or(anyhow!("No device line."))?;
let mut device_inners = match device_pair.as_rule() {
Rule::device => Ok(device_pair.into_inner()),
x => Err(anyhow!(format!(
"Device line didn't parse as such. Parsed as {:?}",
x
))),
}?;
let end = parsed_device.next();
assert!(end.is_none(), "Something found after device line.");
let device_id_pair = device_inners.next().ok_or(anyhow!("No device id."))?;
assert_eq!(
device_id_pair.as_str(),
fake_device_data.expected_id_hex_string,
"Device id doesn't match."
);
let device_name_pair = device_inners.next().ok_or(anyhow!("No device name."))?;
assert_eq!(
device_name_pair.as_str(),
fake_device_data.expected_name,
"Device name doesn't match."
);
let end = device_inners.next();
assert!(end.is_none(), "Something found after device name.");
Ok(())
}
#[test]
fn test_device_simple_add() -> Result<()> {
let fake_device_data = FakeDeviceData::new();
println!("Unparsed_data: {:?}", &fake_device_data.unparsed_data);
let mut parsed_device = PciIdsParser::parse(Rule::device, &fake_device_data.unparsed_data)?;
println!("parsed_device: {:#?}", &parsed_device);
let device_pair = parsed_device.next().context("No parsed device.")?;
println!("device_pair: {:#?}", &device_pair);
let mut vendor_data = PciVendor::new(rand::random::<_>(), "Fake vendor");
vendor_data.add_device_from_device_pairs(&mut device_pair.into_inner())?;
println!("vendor_data: {:#?}", vendor_data);
let device_data = &vendor_data.get_device(&fake_device_data.expected_id)?;
assert_eq!(device_data.id, fake_device_data.expected_id);
assert_eq!(device_data.name, fake_device_data.expected_name);
Ok(())
}
#[test]
fn test_device_complex_add() -> Result<()> {
let fake_subsystem_data = FakeSubsystemData::new();
let fake_device_data = FakeDeviceData::new_with_subsystems(vec![fake_subsystem_data]);
println!("Unparsed_data: {:?}", &fake_device_data.unparsed_data);
let unparsed_device_string_len = fake_device_data.simple_unparsed_data.len();
pest::parses_to! {
parser: PciIdsParser,
input: &fake_device_data.unparsed_data,
rule: Rule::device,
tokens: [
device(0, fake_device_data.unparsed_data.len(), [
device_id(1, 5),
device_name(6, unparsed_device_string_len),
subsystem(unparsed_device_string_len+1, fake_device_data.unparsed_data.len(), [
subsystem_id(unparsed_device_string_len + 3, unparsed_device_string_len+12, [
subvendor_id(unparsed_device_string_len+3, unparsed_device_string_len+7),
subdevice_id(unparsed_device_string_len+8, unparsed_device_string_len+12)
]),
subsystem_name(unparsed_device_string_len+13, fake_device_data.unparsed_data.len()),
])
])
]
};
let mut parsed_device = PciIdsParser::parse(Rule::device, &fake_device_data.unparsed_data)?;
println!("parsed_device: {:#?}", &parsed_device);
let device_pair = parsed_device.next().context("No parsed device.")?;
println!("device_pair: {:#?}", &device_pair);
let mut vendor = PciVendor::new(rand::random::<_>(), "Fake vendor");
vendor.add_device_from_device_pairs(&mut device_pair.into_inner())?;
println!("vendor: {:#?}", vendor);
let device = &vendor.get_device(&fake_device_data.expected_id)?;
fake_device_data.check(device)?;
let subsystem = &device.get_subsystem(&(
fake_device_data.subsystems[0].expected_subvendor_id,
fake_device_data.subsystems[0].expected_subdevice_id,
))?;
fake_device_data.subsystems[0].check(&subsystem)?;
Ok(())
}
struct FakeSubsystemData {
expected_subvendor_id: u16,
expected_subvendor_id_hex_string: String,
expected_subdevice_id: u16,
expected_subdevice_id_hex_string: String,
expected_subsystem_name: String,
unparsed_data: String,
}
impl FakeSubsystemData {
fn new() -> Self {
let expected_subvendor_id = rand::random::<_>();
let expected_subvendor_id_hex_string = as_max_len_hex_string(expected_subvendor_id);
let expected_subdevice_id = rand::random::<_>();
let expected_subdevice_id_hex_string = as_max_len_hex_string(expected_subdevice_id);
let expected_subsystem_name = format!(
"Fake subsystem ({}:{})",
as_max_len_hex_string(expected_subvendor_id),
as_max_len_hex_string(expected_subdevice_id)
);
FakeSubsystemData {
expected_subvendor_id: expected_subvendor_id,
expected_subvendor_id_hex_string: expected_subvendor_id_hex_string.clone(),
expected_subdevice_id: expected_subdevice_id,
expected_subdevice_id_hex_string: expected_subdevice_id_hex_string.clone(),
expected_subsystem_name: expected_subsystem_name.clone(),
unparsed_data: format!(
"\t\t{} {} {}",
expected_subvendor_id_hex_string,
expected_subdevice_id_hex_string,
expected_subsystem_name
),
}
}
fn check(&self, subsystem: &PciSubsystem) -> Result<()> {
assert_eq!(subsystem.subvendor_id, self.expected_subvendor_id);
assert_eq!(subsystem.subdevice_id, self.expected_subdevice_id);
assert_eq!(subsystem.name, self.expected_subsystem_name);
Ok(())
}
}
#[test]
fn test_subsystem_simple_parse() -> Result<()> {
let fake_subsystem_data = FakeSubsystemData::new();
println!("Unparsed_data: {:?}", &fake_subsystem_data.unparsed_data);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_subsystem_data.unparsed_data,
rule: Rule::subsystem,
tokens: [
subsystem(0, fake_subsystem_data.unparsed_data.len(), [
subsystem_id(2, 11, [
subvendor_id(2, 6),
subdevice_id(7, 11)
]),
subsystem_name(12, fake_subsystem_data.unparsed_data.len())
])
]
};
let mut parsed_data =
PciIdsParser::parse(Rule::subsystem_line, &fake_subsystem_data.unparsed_data)?;
let subsystem_id_pairs = parsed_data.next().ok_or(anyhow!("No subsystem ids."))?;
let mut subsystem_id_inners = match subsystem_id_pairs.as_rule() {
Rule::subsystem_id => Ok(subsystem_id_pairs.into_inner()),
x => Err(anyhow!(format!(
"Subsystem ids didn't parse as such. Parsed as {:?}",
x
))),
}?;
let subvendor_id_pair = subsystem_id_inners
.next()
.ok_or(anyhow!("No subvendor id."))?;
match subvendor_id_pair.as_rule() {
Rule::subvendor_id => Ok(()),
_ => Err(anyhow!(format!(
"Subvendor id didn't parse as such. Parsed as {:?}",
subvendor_id_pair.as_rule()
))),
}?;
let subdevice_id_pair = subsystem_id_inners
.next()
.ok_or(anyhow!("No subdevice id."))?;
match subdevice_id_pair.as_rule() {
Rule::subdevice_id => Ok(()),
_ => Err(anyhow!(format!(
"Subdevice id didn't parse as such. Parsed as {:?}",
subdevice_id_pair.as_rule()
))),
}?;
let end = subsystem_id_inners.next();
assert!(end.is_none(), "Something found after subsystem ids.");
let subsystem_name_pair = parsed_data.next().ok_or(anyhow!("No subsystem name."))?;
match subsystem_name_pair.as_rule() {
Rule::subsystem_name => Ok(()),
_ => Err(anyhow!(format!(
"Subvendor name didn't parse as such. Parsed as {:?}",
subsystem_name_pair.as_rule()
))),
}?;
let end = parsed_data.next();
assert!(end.is_none(), "Something found after subsystem name.");
assert_eq!(
subvendor_id_pair.as_str(),
fake_subsystem_data.expected_subvendor_id_hex_string,
"Subvendor id doesn't match."
);
assert_eq!(
subdevice_id_pair.as_str(),
fake_subsystem_data.expected_subdevice_id_hex_string,
"Subdevice id doesn't match."
);
assert_eq!(
subsystem_name_pair.as_str(),
fake_subsystem_data.expected_subsystem_name,
"Subsystem name doesn't match."
);
Ok(())
}
#[test]
fn test_subsystem_simple_add() -> Result<()> {
let fake_subsystem_data = FakeSubsystemData::new();
println!("Unparsed_data: {:?}", &fake_subsystem_data.unparsed_data);
let mut parsed_subsystem =
PciIdsParser::parse(Rule::subsystem, &fake_subsystem_data.unparsed_data)?;
println!("parsed_subsystem: {:#?}", &parsed_subsystem);
let subsystem_pair = parsed_subsystem.next().context("No parsed subsystem.")?;
println!("parsed_subsystem: {:#?}", &subsystem_pair);
let mut device = PciDevice::new(rand::random::<_>(), "Fake device");
device.add_subsystem_from_subsystem_pairs(&mut subsystem_pair.into_inner())?;
println!("{:#?}", &device);
let subsystem = &device.get_subsystem(&(
fake_subsystem_data.expected_subvendor_id,
fake_subsystem_data.expected_subdevice_id,
))?;
fake_subsystem_data.check(&subsystem)?;
Ok(())
}
struct FakeClassData {
expected_id: u8,
expected_id_hex_string: String,
expected_name: String,
unparsed_data: String,
simple_unparsed_data: String,
subclasses: Vec<FakeSubclassData>,
}
impl FakeClassData {
fn new_with_subclasses(subclasses: Vec<FakeSubclassData>) -> Self {
let expected_id = rand::random::<_>();
let expected_id_hex_string = as_max_len_hex_string(expected_id);
let expected_name = format!("Fake class ({})", as_max_len_hex_string(expected_id));
let simple_unparsed_data = format!("C {} {}", expected_id_hex_string, expected_name);
let full_unparsed_data = subclasses
.iter()
.map(|d| d.unparsed_data.clone())
.fold(simple_unparsed_data.clone(), |acc, x| {
format!("{}\n{}", acc, x)
});
FakeClassData {
expected_id: expected_id,
expected_id_hex_string: expected_id_hex_string.clone(),
expected_name: expected_name.clone(),
unparsed_data: full_unparsed_data,
simple_unparsed_data: simple_unparsed_data,
subclasses: subclasses,
}
}
fn new() -> Self {
Self::new_with_subclasses(Vec::<_>::new())
}
fn check(&self, class: &PciClass) -> Result<()> {
assert_eq!(class.id, self.expected_id);
assert_eq!(class.name, self.expected_name);
Ok(())
}
}
#[test]
fn test_class_simple_parse() -> Result<()> {
let fake_class_data = FakeClassData::new();
println!("Unparsed_data: {:?}", &fake_class_data.unparsed_data);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_class_data.unparsed_data,
rule: Rule::class,
tokens: [
class(0, fake_class_data.unparsed_data.len(), [
class_id(2, 4),
class_name(5, fake_class_data.unparsed_data.len())
])
]
};
let mut parsed_data = PciIdsParser::parse(Rule::class, &fake_class_data.unparsed_data)?;
let class_pair = parsed_data.next().ok_or(anyhow!("No class line."))?;
let mut class_inners = match class_pair.as_rule() {
Rule::class => Ok(class_pair.into_inner()),
x => Err(anyhow!(format!(
"Class line didn't parse as such. Parsed as {:?}",
x
))),
}?;
let end = parsed_data.next();
assert!(end.is_none(), "Something found after class line.");
let class_id_pair = class_inners.next().ok_or(anyhow!("No class id."))?;
assert_eq!(
class_id_pair.as_str(),
fake_class_data.expected_id_hex_string,
"Class id doesn't match."
);
let class_name_pair = class_inners.next().ok_or(anyhow!("No class name."))?;
assert_eq!(
class_name_pair.as_str(),
fake_class_data.expected_name,
"Class name doesn't match."
);
let end = class_inners.next();
assert!(end.is_none(), "Something found after class name.");
Ok(())
}
#[test]
fn test_class_simple_add() -> Result<()> {
let fake_class_data = FakeClassData::new();
println!("Unparsed_data: {:?}", &fake_class_data.unparsed_data);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_class_data.unparsed_data,
rule: Rule::class,
tokens: [
class(0, fake_class_data.unparsed_data.len(), [
class_id(2, 4),
class_name(5, fake_class_data.unparsed_data.len())
])
]
};
let mut parsed_class = PciIdsParser::parse(Rule::class, &fake_class_data.unparsed_data)?;
println!("parsed_class: {:#?}", &parsed_class);
let class_pair = parsed_class.next().context("No parsed class.")?;
println!("class_pair: {:#?}", &class_pair);
let mut pci_data = PciIdData::new();
pci_data.add_class_from_class_pairs(&mut class_pair.into_inner())?;
let class = &pci_data.get_class(&fake_class_data.expected_id)?;
fake_class_data.check(class)?;
Ok(())
}
#[test]
fn test_class_complex_add() -> Result<()> {
let fake_prog_if_data = FakeProgIfaceData::new();
let fake_subclass_data = FakeSubclassData::new_with_prog_ifs(vec![fake_prog_if_data]);
let fake_class_data = FakeClassData::new_with_subclasses(vec![fake_subclass_data]);
println!("Unparsed_data: {:?}", &fake_class_data.unparsed_data);
let class_end = fake_class_data.simple_unparsed_data.len();
let subclass_start = class_end + 1;
println!("{}", subclass_start);
let subclass_end =
subclass_start + fake_class_data.subclasses[0].simple_unparsed_data.len();
println!("{}", subclass_end);
let prog_if_start = subclass_end + 1;
pest::parses_to! {
parser: PciIdsParser,
input: &fake_class_data.unparsed_data,
rule: Rule::class,
tokens: [
class(0, fake_class_data.unparsed_data.len(), [
class_id(2, 4),
class_name(5, class_end),
subclass(subclass_start + 0, fake_class_data.unparsed_data.len(), [
subclass_id(subclass_start + 1, subclass_start + 3),
subclass_name(subclass_start + 4, subclass_end),
prog_if(prog_if_start, fake_class_data.unparsed_data.len(), [
prog_if_id(prog_if_start+2, prog_if_start+4),
prog_if_name(prog_if_start+5, fake_class_data.unparsed_data.len()),
])
])
])
]
};
let mut parsed_class = PciIdsParser::parse(Rule::class, &fake_class_data.unparsed_data)?;
println!("parsed_class: {:#?}", &parsed_class);
let class_pair = parsed_class.next().context("No parsed class.")?;
println!("class_pair: {:#?}", &class_pair);
let mut pci_data = PciIdData::new();
pci_data.add_class_from_class_pairs(&mut class_pair.into_inner())?;
println!("pci_data: {:#?}", pci_data);
let class = &pci_data.get_class(&fake_class_data.expected_id)?;
fake_class_data.check(&class)?;
let subclass = &class.get_subclass(&fake_class_data.subclasses[0].expected_id)?;
fake_class_data.subclasses[0].check(subclass)?;
let prog_if =
&subclass.get_prog_interface(&fake_class_data.subclasses[0].prog_ifs[0].expected_id)?;
fake_class_data.subclasses[0].prog_ifs[0].check(&prog_if)?;
Ok(())
}
struct FakeSubclassData {
expected_id: u8,
expected_id_hex_string: String,
expected_name: String,
unparsed_data: String,
simple_unparsed_data: String,
prog_ifs: Vec<FakeProgIfaceData>,
}
impl FakeSubclassData {
fn new_with_prog_ifs(prog_ifs: Vec<FakeProgIfaceData>) -> Self {
let expected_id = rand::random::<_>();
let expected_id_hex_string = as_max_len_hex_string(expected_id);
let expected_name = format!("Fake subclass ({})", as_max_len_hex_string(expected_id));
let simple_unparsed_data = format!("\t{} {}", expected_id_hex_string, expected_name);
let full_unparsed_data = prog_ifs
.iter()
.map(|d| d.unparsed_data.clone())
.fold(simple_unparsed_data.clone(), |acc, x| {
format!("{}\n{}", acc, x)
});
FakeSubclassData {
expected_id: expected_id,
expected_id_hex_string: expected_id_hex_string.clone(),
expected_name: expected_name.clone(),
unparsed_data: full_unparsed_data,
simple_unparsed_data: simple_unparsed_data,
prog_ifs: prog_ifs,
}
}
fn new() -> Self {
Self::new_with_prog_ifs(Vec::<_>::new())
}
fn check(&self, subclass: &PciSubclass) -> Result<()> {
assert_eq!(subclass.id, self.expected_id);
assert_eq!(subclass.name, self.expected_name);
Ok(())
}
}
#[test]
fn test_subclass_simple_parse() -> Result<()> {
let fake_subclass_data = FakeSubclassData::new();
println!("Unparsed_data: {:?}", &fake_subclass_data.unparsed_data);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_subclass_data.unparsed_data,
rule: Rule::subclass,
tokens: [
subclass(0, fake_subclass_data.unparsed_data.len(), [
subclass_id(1, 3),
subclass_name(4, fake_subclass_data.unparsed_data.len())
])
]
};
let mut parsed_data =
PciIdsParser::parse(Rule::subclass, &fake_subclass_data.unparsed_data)?;
let subclass_pair = parsed_data.next().ok_or(anyhow!("No subclass line."))?;
let mut subclass_inners = match subclass_pair.as_rule() {
Rule::subclass => Ok(subclass_pair.into_inner()),
x => Err(anyhow!(format!(
"Subclass line didn't parse as such. Parsed as {:?}",
x
))),
}?;
let end = parsed_data.next();
assert!(end.is_none(), "Something found after subclass line.");
let subclass_id_pair = subclass_inners.next().ok_or(anyhow!("No subclass id."))?;
assert_eq!(
subclass_id_pair.as_str(),
fake_subclass_data.expected_id_hex_string,
"Subclass id doesn't match."
);
let subclass_name_pair = subclass_inners.next().ok_or(anyhow!("No subclass name."))?;
assert_eq!(
subclass_name_pair.as_str(),
fake_subclass_data.expected_name,
"Subclass name doesn't match."
);
let end = subclass_inners.next();
assert!(end.is_none(), "Something found after subclass name.");
Ok(())
}
#[test]
fn test_subclass_simple_add() -> Result<()> {
let fake_subclass_data = FakeSubclassData::new();
println!("Unparsed_data: {:?}", &fake_subclass_data.unparsed_data);
let mut parsed_subclass =
PciIdsParser::parse(Rule::subclass, &fake_subclass_data.unparsed_data)?;
println!("parsed_subclass: {:#?}", &parsed_subclass);
let subclass_pair = parsed_subclass.next().context("No parsed class")?;
println!("parsed_subclass: {:#?}", &subclass_pair);
let mut class = PciClass::new(rand::random::<_>(), "Fake class");
class.add_subclass_from_subclass_pairs(&mut subclass_pair.into_inner())?;
println!("{:#?}", &class);
let subclass = &class.get_subclass(&fake_subclass_data.expected_id)?;
fake_subclass_data.check(&subclass)?;
Ok(())
}
#[test]
fn test_subclass_complex_add() -> Result<()> {
let fake_prog_if_data = FakeProgIfaceData::new();
let fake_subclass_data = FakeSubclassData::new_with_prog_ifs(vec![fake_prog_if_data]);
println!(
"Unparsed_data: {:?}",
&fake_subclass_data.simple_unparsed_data
);
let unparsed_subclass_string_len = fake_subclass_data.simple_unparsed_data.len();
println!("{}", unparsed_subclass_string_len);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_subclass_data.unparsed_data,
rule: Rule::subclass,
tokens: [
subclass(0, fake_subclass_data.unparsed_data.len(), [
subclass_id(1, 3),
subclass_name(4, unparsed_subclass_string_len),
prog_if(unparsed_subclass_string_len+1, fake_subclass_data.unparsed_data.len(), [
prog_if_id(unparsed_subclass_string_len+3, unparsed_subclass_string_len+5),
prog_if_name(unparsed_subclass_string_len+6, fake_subclass_data.unparsed_data.len()),
])
])
]
};
let mut parsed_subclass =
PciIdsParser::parse(Rule::subclass, &fake_subclass_data.unparsed_data)?;
println!("parsed_subclass: {:#?}", &parsed_subclass);
let subclass_pair = parsed_subclass.next().context("No parsed subclass.")?;
println!("subclass_pair: {:#?}", &subclass_pair);
let mut class = PciClass::new(rand::random::<_>(), "Fake class");
class.add_subclass_from_subclass_pairs(&mut subclass_pair.into_inner())?;
println!("class: {:#?}", class);
let subclass = &class.get_subclass(&fake_subclass_data.expected_id)?;
fake_subclass_data.check(subclass)?;
Ok(())
}
struct FakeProgIfaceData {
expected_id: u8,
expected_id_hex_string: String,
expected_name: String,
unparsed_data: String,
}
impl FakeProgIfaceData {
fn new() -> Self {
let expected_id = rand::random::<_>();
let expected_id_hex_string = as_max_len_hex_string(expected_id);
let expected_name = format!(
"Fake programming interface ({})",
as_max_len_hex_string(expected_id)
);
FakeProgIfaceData {
expected_id: expected_id,
expected_id_hex_string: expected_id_hex_string.clone(),
expected_name: expected_name.clone(),
unparsed_data: format!("\t\t{} {}", expected_id_hex_string, expected_name),
}
}
fn check(&self, class: &PciProgInterface) -> Result<()> {
assert_eq!(class.id, self.expected_id);
assert_eq!(class.name, self.expected_name);
Ok(())
}
}
#[test]
fn test_prog_if_simple_parse() -> Result<()> {
let fake_prog_if_data = FakeProgIfaceData::new();
println!("Unparsed_data: {:?}", &fake_prog_if_data.unparsed_data);
pest::parses_to! {
parser: PciIdsParser,
input: &fake_prog_if_data.unparsed_data,
rule: Rule::prog_if,
tokens: [
prog_if(0, fake_prog_if_data.unparsed_data.len(), [
prog_if_id(2, 4),
prog_if_name(5, fake_prog_if_data.unparsed_data.len())
])
]
};
let mut parsed_data = PciIdsParser::parse(Rule::prog_if, &fake_prog_if_data.unparsed_data)?;
let prog_if_pair = parsed_data.next().ok_or(anyhow!("No prog_if line."))?;
let mut prog_if_inners = match prog_if_pair.as_rule() {
Rule::prog_if => Ok(prog_if_pair.into_inner()),
x => Err(anyhow!(format!(
"Subclass line didn't parse as such. Parsed as {:?}",
x
))),
}?;
let end = parsed_data.next();
assert!(end.is_none(), "Something found after prog_if line.");
let prog_if_id_pair = prog_if_inners.next().ok_or(anyhow!("No prog_if id."))?;
assert_eq!(
prog_if_id_pair.as_str(),
fake_prog_if_data.expected_id_hex_string,
"Subclass id doesn't match."
);
let prog_if_name_pair = prog_if_inners.next().ok_or(anyhow!("No prog_if name."))?;
assert_eq!(
prog_if_name_pair.as_str(),
fake_prog_if_data.expected_name,
"Subclass name doesn't match."
);
let end = prog_if_inners.next();
assert!(end.is_none(), "Something found after prog_if name.");
Ok(())
}
#[test]
fn test_prog_if_simple_add() -> Result<()> {
let fake_prog_if_data = FakeProgIfaceData::new();
println!("Unparsed_data: {:?}", &fake_prog_if_data.unparsed_data);
let mut parsed_prog_if =
PciIdsParser::parse(Rule::prog_if, &fake_prog_if_data.unparsed_data)?;
println!("parsed_prog_if: {:#?}", &parsed_prog_if);
let prog_if_pair = parsed_prog_if
.next()
.context("No parsed programming interface")?;
println!("parsed_prog_if: {:#?}", &prog_if_pair);
let mut subclass = PciSubclass::new(rand::random::<_>(), "Fake subclass");
subclass.add_prog_if_from_prog_if_pairs(&mut prog_if_pair.into_inner())?;
println!("{:#?}", &subclass);
let prog_if = &subclass.get_prog_interface(&fake_prog_if_data.expected_id)?;
fake_prog_if_data.check(&prog_if)?;
Ok(())
}
#[test]
fn test_full_parse() -> Result<()> {
let vendors = vec![
FakeVendorData::new_with_devices(vec![FakeDeviceData::new_with_subsystems(vec![
FakeSubsystemData::new(),
FakeSubsystemData::new(),
])]),
FakeVendorData::new_with_devices(vec![FakeDeviceData::new()]),
FakeVendorData::new(),
];
let classes = vec![
FakeClassData::new_with_subclasses(vec![FakeSubclassData::new_with_prog_ifs(vec![
FakeProgIfaceData::new(),
FakeProgIfaceData::new(),
])]),
FakeClassData::new_with_subclasses(vec![FakeSubclassData::new()]),
FakeClassData::new(),
];
let vendor_data = vendors
.iter()
.map(|d| d.unparsed_data.clone())
.fold(String::new(), |acc, x| format!("{}\n{}", acc, x));
let class_data = classes
.iter()
.map(|d| d.unparsed_data.clone())
.fold(String::new(), |acc, x| format!("{}\n{}", acc, x));
let unparsed_data = vendor_data + &class_data;
println!("Unparsed_data: {:?}", unparsed_data);
let mut pci_data = PciIdData::new();
pci_data.add_pci_ids_data(&mut unparsed_data.as_bytes())?;
println!("{:#?}", &pci_data);
for vendor in vendors {
let pci_vendor = pci_data.get_vendor(&vendor.expected_id).context(format!(
"Vendor didn't parse correctly: {}",
vendor.simple_unparsed_data
))?;
for device in vendor.devices {
let pci_device = pci_vendor.get_device(&device.expected_id).context(format!(
"Device didn't parse correctly: {}",
device.simple_unparsed_data
))?;
for subsystem in device.subsystems {
let _pci_subsystem = pci_device
.get_subsystem(&(
subsystem.expected_subvendor_id,
subsystem.expected_subdevice_id,
))
.context(format!(
"Subsystem didn't parse correctly: {}",
subsystem.unparsed_data
))?;
}
}
}
for class in classes {
let pci_class = pci_data.get_class(&class.expected_id).context(format!(
"Class didn't parse correctly: {}",
class.simple_unparsed_data
))?;
for subclass in class.subclasses {
let pci_subclass =
pci_class
.get_subclass(&subclass.expected_id)
.context(format!(
"Subclass didn't parse correctly: {}",
subclass.simple_unparsed_data
))?;
for prog_if in subclass.prog_ifs {
let _pci_prog_interface = pci_subclass
.get_prog_interface(&prog_if.expected_id)
.context(format!(
"Programming interface didn't parse correctly: {}",
prog_if.unparsed_data
))?;
}
}
}
Ok(())
}
#[bench]
fn test_benchmark_complex_load(b: &mut test::Bencher) -> Result<()> {
let mut s = String::new();
let mut rng = rand::rngs::StdRng::seed_from_u64(0);
s.push_str("# preamble comment\n");
s.push('\n');
s.push_str("# subpreamble comment\n");
for i in 0..(u16::MAX / 5 - 1) {
s.push_str("# vendor comment\n");
s.push_str(format!("{:02$X} Vendor {:02$X}\n", i, i, 4).as_str());
let num_devices: u16 = rng.gen_range(0, 3);
for j in 0..num_devices {
let num_subsystems: u16 = rng.gen_range(0, 5);
s.push_str("# device comment\n");
s.push_str(format!("\t{:02$X} Device {:02$X}\n", j, j, 4).as_str());
for k in 0..num_subsystems {
s.push_str("# subsystem comment\n");
s.push_str(
format!(
"\t\t{:04$X} {:04$X} Subsystem {:04$X}:{:04$X}\n",
k, k, k, k, 4
)
.as_str(),
);
}
}
}
s.push_str("FFFF Invalid Vendor\n");
s.push('\n');
for i in 0..(u8::MAX - 1) {
s.push_str("# class comment\n");
s.push_str(format!("C {:02$X} Class {:02$X}\n", i, i, 2).as_str());
let num_subclasses: u8 = rng.gen_range(1, 3);
for j in 0..num_subclasses {
let num_prog_ifs: u8 = rng.gen_range(0, 5);
s.push_str("# subclass comment\n");
s.push_str(format!("\t{:02$X} Subclass {:02$X}\n", j, j, 2).as_str());
for k in 0..num_prog_ifs {
s.push_str("# Programming interface comment\n");
s.push_str(
format!("\t\t{:02$X} Programming interfaces {:02$X}\n", k, k, 2).as_str(),
);
}
}
}
s.push_str("FFFF Unassigned class\n");
b.iter(|| {
let mut pci_data = PciIdData::new();
pci_data.add_pci_ids_data(&mut s.as_bytes()).unwrap()
});
Ok(())
}
}
| true |
3121bc7414f6655c35be05eb232f30f91668abf5
|
Rust
|
dip-proto/boring
|
/boring/src/base64.rs
|
UTF-8
| 4,066 | 3.203125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! Base64 encoding support.
use cvt_n;
use error::ErrorStack;
use ffi;
use libc::c_int;
/// Encodes a slice of bytes to a base64 string.
///
/// This corresponds to [`EVP_EncodeBlock`].
///
/// # Panics
///
/// Panics if the input length or computed output length overflow a signed C integer.
///
/// [`EVP_EncodeBlock`]: https://www.openssl.org/docs/man1.1.1/man3/EVP_DecodeBlock.html
pub fn encode_block(src: &[u8]) -> String {
assert!(src.len() <= c_int::max_value() as usize);
let src_len = src.len();
let len = encoded_len(src_len).unwrap();
let mut out = Vec::with_capacity(len as usize);
// SAFETY: `encoded_len` ensures space for 4 output characters
// for every 3 input bytes including padding and nul terminator.
// `EVP_EncodeBlock` will write only single byte ASCII characters.
// `EVP_EncodeBlock` will only write to not read from `out`.
unsafe {
let out_len = ffi::EVP_EncodeBlock(out.as_mut_ptr(), src.as_ptr(), src_len);
out.set_len(out_len as usize);
String::from_utf8_unchecked(out)
}
}
/// Decodes a base64-encoded string to bytes.
///
/// This corresponds to [`EVP_DecodeBlock`].
///
/// # Panics
///
/// Panics if the input length or computed output length overflow a signed C integer.
///
/// [`EVP_DecodeBlock`]: https://www.openssl.org/docs/man1.1.1/man3/EVP_DecodeBlock.html
pub fn decode_block(src: &str) -> Result<Vec<u8>, ErrorStack> {
let src = src.trim();
// https://github.com/openssl/openssl/issues/12143
if src.is_empty() {
return Ok(vec![]);
}
assert!(src.len() <= c_int::max_value() as usize);
let src_len = src.len();
let len = decoded_len(src_len).unwrap();
let mut out = Vec::with_capacity(len as usize);
// SAFETY: `decoded_len` ensures space for 3 output bytes
// for every 4 input characters including padding.
// `EVP_DecodeBlock` can write fewer bytes after stripping
// leading and trailing whitespace, but never more.
// `EVP_DecodeBlock` will only write to not read from `out`.
unsafe {
let out_len = cvt_n(ffi::EVP_DecodeBlock(
out.as_mut_ptr(),
src.as_ptr(),
src_len,
))?;
out.set_len(out_len as usize);
}
if src.ends_with('=') {
out.pop();
if src.ends_with("==") {
out.pop();
}
}
Ok(out)
}
fn encoded_len(src_len: usize) -> Option<usize> {
let mut len = (src_len / 3).checked_mul(4)?;
if src_len % 3 != 0 {
len = len.checked_add(4)?;
}
len = len.checked_add(1)?;
Some(len)
}
fn decoded_len(src_len: usize) -> Option<usize> {
let mut len = (src_len / 4).checked_mul(3)?;
if src_len % 4 != 0 {
len = len.checked_add(3)?;
}
Some(len)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encode_block() {
assert_eq!("".to_string(), encode_block(b""));
assert_eq!("Zg==".to_string(), encode_block(b"f"));
assert_eq!("Zm8=".to_string(), encode_block(b"fo"));
assert_eq!("Zm9v".to_string(), encode_block(b"foo"));
assert_eq!("Zm9vYg==".to_string(), encode_block(b"foob"));
assert_eq!("Zm9vYmE=".to_string(), encode_block(b"fooba"));
assert_eq!("Zm9vYmFy".to_string(), encode_block(b"foobar"));
}
#[test]
fn test_decode_block() {
assert_eq!(b"".to_vec(), decode_block("").unwrap());
assert_eq!(b"f".to_vec(), decode_block("Zg==").unwrap());
assert_eq!(b"fo".to_vec(), decode_block("Zm8=").unwrap());
assert_eq!(b"foo".to_vec(), decode_block("Zm9v").unwrap());
assert_eq!(b"foob".to_vec(), decode_block("Zm9vYg==").unwrap());
assert_eq!(b"fooba".to_vec(), decode_block("Zm9vYmE=").unwrap());
assert_eq!(b"foobar".to_vec(), decode_block("Zm9vYmFy").unwrap());
}
#[test]
fn test_strip_whitespace() {
assert_eq!(b"foobar".to_vec(), decode_block(" Zm9vYmFy\n").unwrap());
assert_eq!(b"foob".to_vec(), decode_block(" Zm9vYg==\n").unwrap());
}
}
| true |
9a4661ee26f4e9732ea686ffee9c5ae3a69aa3d3
|
Rust
|
frjonsen/aoc2020
|
/src/day6.rs
|
UTF-8
| 2,156 | 3.25 | 3 |
[] |
no_license
|
use std::collections::HashSet;
use regex::Regex;
#[aoc_generator(day6)]
pub fn input_generator(input: &str) -> Vec<String> {
let group_separator = Regex::new(r"\n\n+").unwrap();
group_separator.split(input).map(|g| g.to_owned()).collect()
}
#[aoc(day6, part1)]
pub fn day6_part1(input: &Vec<String>) -> u32 {
input
.into_iter()
.map(|g| g.replace('\n', "").chars().collect::<HashSet<char>>().len() as u32)
.sum()
}
#[aoc(day6, part2)]
pub fn day6_part2(input: &Vec<String>) -> u32 {
input
.into_iter()
.map(|g| {
g.lines()
.map(|l| l.chars().collect::<HashSet<char>>())
.collect::<Vec<_>>()
})
.map(|p| {
let first = p.first().unwrap().clone();
p.into_iter()
.skip(1)
.fold(first, |set1, set2| &set1 & &set2)
.len() as u32
})
.sum()
}
#[cfg(test)]
mod tests {
use super::{day6_part1, day6_part2, input_generator};
#[test]
fn test_generator() {
let given = concat!(
"abc\n\n",
"a\nb\nc\n\n",
"ab\nac\n\n",
"a\na\na\na\n\n",
"b"
);
let res = input_generator(given);
let groups = vec![
"abc".to_owned(),
"a\nb\nc".to_owned(),
"ab\nac".to_owned(),
"a\na\na\na".to_owned(),
"b".to_owned(),
];
assert_eq!(&res[..], &groups[..])
}
#[test]
fn test_given_part1() {
let groups = vec![
"abc".to_owned(),
"ab\nac".to_owned(),
"ab\nac".to_owned(),
"a\na\na\na\na".to_owned(),
"b".to_owned(),
];
let res = day6_part1(&groups);
assert_eq!(res, 11)
}
#[test]
fn test_given_part2() {
let groups = vec![
"abc".to_owned(),
"a\nb\nc".to_owned(),
"ab\nac".to_owned(),
"a\na\na\na\na".to_owned(),
"b".to_owned(),
];
let res = day6_part2(&groups);
assert_eq!(res, 6)
}
}
| true |
9732609bb00837ed9629d08b3ee1537f8d195523
|
Rust
|
libcala/devout
|
/src/lib.rs
|
UTF-8
| 2,994 | 2.828125 | 3 |
[
"Zlib",
"Apache-2.0"
] |
permissive
|
// DevOut
//
// Copyright (c) 2019-2020 Jeron Aldaron Lau
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// https://apache.org/licenses/LICENSE-2.0>, or the Zlib License, <LICENSE-ZLIB
// or http://opensource.org/licenses/Zlib>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! # Getting Started
//! Add the following to your `Cargo.toml`:
//! ```toml
//! [dependencies.devout]
//! version = "0.1.0"
//! ```
//!
//! ```rust
//! use devout::{log, Tag};
//!
//! const INFO: Tag = Tag::new("Info").show(true);
//!
//! log!(INFO, "Result: {}", 4.4);
//! ```
#![doc(
html_logo_url = "https://libcala.github.io/logo.svg",
html_favicon_url = "https://libcala.github.io/icon.svg",
html_root_url = "https://docs.rs/devout"
)]
#![deny(unsafe_code)]
#![warn(
anonymous_parameters,
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
nonstandard_style,
rust_2018_idioms,
single_use_lifetimes,
trivial_casts,
trivial_numeric_casts,
unreachable_pub,
unused_extern_crates,
unused_qualifications,
variant_size_differences
)]
/// A tag to identify a log.
#[derive(Copy, Clone, Debug)]
pub struct Tag(Option<&'static str>);
impl Tag {
/// Create a new tag by passing a textual identifier.
#[inline(always)]
pub const fn new(ident: &'static str) -> Self {
Tag(Some(ident))
}
/// Hide logs using this tag.
#[inline(always)]
pub const fn hide(self) -> Self {
Tag(None)
}
/// Choose whether or not to show this tag based on a boolean value.
/// `true` is show, and `false` is hide.
#[inline(always)]
pub const fn show(self, log: bool) -> Self {
if log {
self
} else {
self.hide()
}
}
/// Returns true if logs using this tag are shown.
#[inline(always)]
pub const fn is_shown(self) -> bool {
self.0.is_some()
}
/// Get tag as optional identifier.
#[inline(always)]
const fn as_option(&self) -> Option<&'static str> {
self.0
}
/// Print out a log message with this tag. Prefer `log!()` instead.
#[inline(always)]
pub fn log(&self, args: std::fmt::Arguments<'_>) {
if let Some(tag) = self.as_option() {
#[cfg(not(target_arch = "wasm32"))]
let _ = <std::io::Stdout as std::io::Write>::write_fmt(
&mut std::io::stdout(),
format_args!("[{}] {}\n", tag, args),
);
#[cfg(target_arch = "wasm32")]
web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
"[{}] {}",
tag, args
)));
}
}
}
/// Write a message to the log.
#[macro_export]
macro_rules! log {
($tag:ident) => {{
$tag.log(format_args!(""));
}};
($tag:ident, $($arg:tt)*) => {{
$tag.log(format_args!($($arg)*));
}};
}
| true |
0372cf352db21150609ad843a9265c75f3ce5c56
|
Rust
|
bluk/advent_of_code
|
/aoc_2022_05/src/main.rs
|
UTF-8
| 2,719 | 3.171875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use itertools::Itertools as _;
use std::io;
type Cargo = char;
type CargoStacks = Vec<Vec<Cargo>>;
#[derive(Debug)]
struct MoveCmd {
count: usize,
from: usize,
to: usize,
}
fn parse_crate_line(s: &str, stacks: &mut CargoStacks) {
for (pos, mut chunk) in s.chars().chunks(4).into_iter().enumerate() {
if let Some('[') = chunk.next() {
let item = chunk.next().expect("item identifier does not exist");
if let Some(stack) = stacks.get_mut(pos) {
stack.push(item);
} else {
stacks.resize(pos + 1, Vec::default());
stacks[pos].push(item);
}
assert_eq!(chunk.next(), Some(']'));
}
}
}
fn parse_cmd(s: &str) -> io::Result<MoveCmd> {
let mut words = s.split_whitespace();
match (
words.next(),
words.next(),
words.next(),
words.next(),
words.next(),
words.next(),
) {
(Some("move"), Some(count), Some("from"), Some(from), Some("to"), Some(to)) => {
let count = count
.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
let from = from
.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
let to = to
.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
Ok(MoveCmd { count, from, to })
}
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid command",
)),
}
}
fn main() -> io::Result<()> {
let mut lines = io::stdin().lines();
let mut stacks = itertools::process_results(&mut lines, |it| {
let mut stacks = CargoStacks::default();
for line in it.take_while(|l| !l.is_empty()) {
parse_crate_line(&line, &mut stacks);
}
stacks
})?;
for stack in &mut stacks {
stack.reverse();
}
itertools::process_results(&mut lines, |it| {
for line in it {
let cmd = parse_cmd(&line)?;
let from = &mut stacks[cmd.from - 1];
let to_copy = from
.iter()
.rev()
.take(cmd.count)
.copied()
.rev()
.collect::<Vec<_>>();
from.truncate(from.len() - cmd.count);
let to = &mut stacks[cmd.to - 1];
to.extend(to_copy);
}
Ok::<_, io::Error>(())
})??;
let tops = stacks
.iter()
.map(|stack| stack.last().unwrap_or(&' '))
.join("");
println!("{tops}");
Ok(())
}
| true |
3b97bc906ff5ada6bd9697707dc21d63d14988fd
|
Rust
|
frankhart2018/rust-learn
|
/ch-6-enums-and-pattern-matching/ip_enum/src/main.rs
|
UTF-8
| 1,912 | 3.5625 | 4 |
[] |
no_license
|
#[derive(Debug)]
enum IpAddrKind {
V4,
V6
}
#[derive(Debug)]
struct IpAddr {
kind: IpAddrKind,
address: String,
}
#[derive(Debug)]
enum IpAddress {
V4(String),
V6(String),
}
#[derive(Debug)]
enum IpAddress1 {
V4(u8, u8, u8, u8),
V6(String),
}
// An even better approach is to make different structs and use them as type for enum
#[derive(Debug)]
struct Ipv4Addr {
part_1: u8,
part_2: u8,
part_3: u8,
part_4: u8,
}
#[derive(Debug)]
struct Ipv6Addr {
part_1: String,
}
#[derive(Debug)]
enum BestIpAddr {
V4(Ipv4Addr),
V6(Ipv6Addr),
}
fn main() {
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
route(four);
route(six);
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
println!("{:#?}", home);
println!("{:#?}", loopback);
let home = IpAddress::V4(String::from("127.0.0.1"));
let loopback = IpAddress::V6(String::from("::1"));
println!("{:#?}", home);
println!("{:#?}", loopback);
// Another advantage of using an enum with attached value over struct is every entry can have different values
let home = IpAddress1::V4(127, 0, 0, 1);
let loopback = IpAddress1::V6(String::from("::1"));
println!("{:#?}", home);
println!("{:#?}", loopback);
// Best way - use structs for representing individual types
let ipv4_addr = Ipv4Addr {
part_1: 127,
part_2: 0,
part_3: 0,
part_4: 1,
};
let ipv6_addr = Ipv6Addr {
part_1: String::from("::1"),
};
let home = BestIpAddr::V4(ipv4_addr);
let loopback = BestIpAddr::V6(ipv6_addr);
println!("{:#?}", home);
println!("{:#?}", loopback);
}
fn route(ip_kind: IpAddrKind) {
println!("{:?}", ip_kind);
}
| true |
65da8d1be25305c064b38d8a2b5b9e447d89f587
|
Rust
|
lo48576/priconne-fankit-dl
|
/src/fankit.rs
|
UTF-8
| 2,224 | 2.890625 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Fankit-related stuff.
use std::{
collections::{HashSet, VecDeque},
time::Duration,
};
pub use self::{
id::{FankitId, FankitIdParseError},
info::FankitInfo,
list_page_index::{FankitListPageIndex, FankitListPageIndexParseError},
};
mod id;
mod info;
mod list_page_index;
/// Common URL prefix for fankit-related pages.
const URL_FANKIT_TOP: &str = "https://priconne-redive.jp/fankit02/";
/// URL prefix for fankit items.
const URL_FANKIT_ITEM_BASE: &str = URL_FANKIT_TOP;
/// URL prefix for fankit list pages.
const URL_FANKIT_LIST_BASE: &str = "https://priconne-redive.jp/fankit02/page/";
/// Returns fankits if new fankit is detected.
pub fn get_fankits_if_new_fankit_found(
known_fankits: impl IntoIterator<Item = FankitId>,
crawl_delay: Duration,
) -> Result<Option<HashSet<FankitId>>, Box<dyn std::error::Error + Send + Sync + 'static>> {
use std::iter::FromIterator;
const FIRST_PAGE_INDEX: FankitListPageIndex = FankitListPageIndex::new(1);
let (new_fankits, other_lists) = FIRST_PAGE_INDEX.load()?;
let new_fankits = HashSet::from_iter(new_fankits);
let known_fankits = HashSet::from_iter(known_fankits);
if new_fankits.is_subset(&known_fankits) {
// There are no new fankits.
return Ok(None);
}
// Wanted to pop from `HashSet` but it is not in std hashset.
// Using `VecDeque` instead.
let mut list_undone = VecDeque::from_iter(other_lists);
let mut fankits = new_fankits;
let mut list_done = std::iter::once(FIRST_PAGE_INDEX).collect::<HashSet<_>>();
// Load the index pages.
while let Some(list_page) = list_undone.pop_front() {
if !list_done.insert(list_page) {
// `list_page` is already checked.
continue;
}
let (new_fankits, other_lists) = list_page.load()?;
list_undone.extend(other_lists.into_iter().filter(|v| !list_done.contains(v)));
fankits.extend(new_fankits);
log::debug!(
"List pages done = {:?}, undone = {:?}",
list_done,
list_undone
);
log::debug!("Sleeping for {:?}", crawl_delay);
std::thread::sleep(crawl_delay);
}
Ok(Some(fankits))
}
| true |
c9f662f7e8c90e933670548a6791355d40dec585
|
Rust
|
crlf0710/mdTranslation-legacy
|
/src/bin/mdtranslation-extract.rs
|
UTF-8
| 1,650 | 2.75 | 3 |
[] |
no_license
|
use std::fmt;
use std::fs;
use std::io::{self, Read, Write};
use std::path::PathBuf;
use structopt::StructOpt;
use thiserror::Error;
#[derive(Error, Debug)]
enum Error {
#[error("io error: {0}")]
IO(#[from] io::Error),
#[error("format error: {0}")]
Fmt(#[from] fmt::Error),
#[error("from tokens error: {0}")]
FromTokens(#[from] mdtranslation::from_tokens::FromTokensError),
}
#[derive(Debug, StructOpt)]
struct Opt {
/// Input file
#[structopt(parse(from_os_str))]
input: PathBuf,
/// Output file, stdout if not present
#[structopt(parse(from_os_str))]
output: Option<PathBuf>,
}
fn main() -> Result<(), Error> {
let opt = Opt::from_args();
let mut input = fs::File::open(opt.input)?;
let stdout;
let mut output_file: Box<dyn io::Write + '_> = if let Some(output_path) = opt.output.as_ref() {
let file = fs::File::create(output_path)?;
Box::new(file) as _
} else {
stdout = Some(io::stdout());
let stdout_lock = stdout.as_ref().unwrap().lock();
Box::new(stdout_lock) as _
};
let mut input_text = String::new();
let _ = input.read_to_string(&mut input_text)?;
let reader = pulldown_cmark::Parser::new(&input_text);
let mut ast = mdtranslation::from_tokens::cmark_ast_from_tokens(reader)?;
ast.perform_sentence_segment();
let clause_list = ast.extract_clause_list(&pulldown_cmark::CowStr::Borrowed("en-US"));
let mut output_text = String::new();
let _ = pulldown_cmark_to_cmark::cmark(clause_list.into_tokens(), &mut output_text, None)?;
output_file.write_all(output_text.as_bytes())?;
Ok(())
}
| true |
1fb52005de245dd9f3d7e1a72c4f44c44b524b3c
|
Rust
|
Xardvor/nonsense
|
/src/main.rs
|
UTF-8
| 1,781 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
mod stories;
mod modifiers;
use std::string::*;
use std::vec::Vec;
use std::collections::HashMap;
fn main() {
let origin: Vec<String> = vec![String::from("#mood.capitalize and #mood, the #path was #mood with #substance.ed"), String::from("#nearby.capitalize #path #amove through the #path, filling me with #substance.ed")];
let nearby = vec![String::from("far away"), String::from("ahead"), String::from("behind me")];
let substance = vec![String::from("light"), String::from("reflections"), String::from("mist"), String::from("shadow"), String::from("darkness"), String::from("brightness"), String::from("gaiety"), String::from("merriment")];
let mood = vec![String::from("overcast"), String::from("alight"), String::from("clear"), String::from("darkened"), String::from("blue"), String::from("shadowed"), String::from("illuminated"), String::from("silver"), String::from("cool"), String::from("warm"), String::from("summer-warmed")];
let path = vec![String::from("stream"), String::from("brook"), String::from("path"), String::from("ravine"), String::from("forest"), String::from("fence"), String::from("stone wall")];
let amove = vec![String::from("spiral"), String::from("twirl"), String::from("curl"), String::from("dance"), String::from("twine"), String::from("weave"), String::from("meander"), String::from("wander"), String::from("flow")];
let story: HashMap<String, Vec<String>> = [(String::from("origin"), origin),
(String::from("nearby"), nearby),
(String::from("substance"), substance),
(String::from("mood"), mood),
(String::from("path"), path),
(String::from("amove"), amove)].iter().cloned().collect();
let generator = stories::Storyteller::create(&story);
let generated_story = generator.generate("origin");
println!("{}",generated_story);
}
| true |
de9a5f6ddb10a5ae1a48e9b23743a45244925050
|
Rust
|
reem/rust-membuf
|
/src/alloc.rs
|
UTF-8
| 2,072 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
//! Typed Allocation Utilities
//!
//! Unlike std::rt::heap these check for zero-sized types, capacity overflow,
//! oom etc. and calculate the appropriate size and alignment themselves.
extern crate alloc;
use core::nonzero::NonZero;
use std::rt::heap;
use std::mem;
/// Allocate a new pointer to the heap with space for `cap` `T`s.
pub unsafe fn allocate<T>(cap: NonZero<usize>) -> NonZero<*mut T> {
if mem::size_of::<T>() == 0 { return empty() }
// Allocate
let ptr = heap::allocate(allocation_size::<T>(cap), mem::align_of::<T>());
// Check for allocation failure
if ptr.is_null() { alloc::oom() }
NonZero::new(ptr as *mut T)
}
/// Reallocate an allocation allocated with `allocate` or a previous call to
/// `reallocate` to be a larger or smaller size.
pub unsafe fn reallocate<T>(ptr: NonZero<*mut T>,
old_cap: NonZero<usize>,
new_cap: NonZero<usize>) -> NonZero<*mut T> {
if mem::size_of::<T>() == 0 { return empty() }
let old_size = unchecked_allocation_size::<T>(old_cap);
let new_size = allocation_size::<T>(new_cap);
// Reallocate
let new = heap::reallocate(*ptr as *mut u8, old_size, new_size, mem::align_of::<T>());
// Check for allocation failure
if new.is_null() {
alloc::oom()
}
NonZero::new(new as *mut T)
}
/// A zero-sized allocation, appropriate for use with zero sized types.
pub fn empty<T>() -> NonZero<*mut T> {
unsafe { NonZero::new(heap::EMPTY as *mut T) }
}
/// Deallocate an allocation allocated with `allocate` or `reallocate`.
pub unsafe fn deallocate<T>(ptr: NonZero<*mut T>, cap: NonZero<usize>) {
if mem::size_of::<T>() == 0 { return }
let old_size = unchecked_allocation_size::<T>(cap);
heap::deallocate(*ptr as *mut u8, old_size, mem::align_of::<T>())
}
fn allocation_size<T>(cap: NonZero<usize>) -> usize {
mem::size_of::<T>().checked_mul(*cap).expect("Capacity overflow")
}
fn unchecked_allocation_size<T>(cap: NonZero<usize>) -> usize {
mem::size_of::<T>() * (*cap)
}
| true |
2fba4d611a27f1665cb9a1222b7f4fcf7a187036
|
Rust
|
0rvar/advent-of-code-2017
|
/day17/src/main.rs
|
UTF-8
| 1,227 | 3.28125 | 3 |
[] |
no_license
|
fn main() {
const STEP_SIZE: usize = 377;
{
let mut memory: Vec<usize> = Vec::new();
memory.push(0);
let mut position = 0;
let mut size = 1;
for i in 1.. {
position = (position + STEP_SIZE) % size;
memory.insert(position + 1, i);
position = position + 1;
size = size + 1;
if i == 2017 {
println!("memory[pos]: {}", memory[(position + 0) % size]);
println!("memory[pos+1]: {}", memory[(position + 1) % size]);
break;
}
}
}
{
let mut zero_position = 0;
let mut value_after_zero = 0;
let mut position = 0;
let mut size = 1;
for i in 1.. {
position = (position + STEP_SIZE) % size;
if position == zero_position {
value_after_zero = i;
} else if position < zero_position {
zero_position += 1;
}
position = position + 1;
size = size + 1;
if i == 50_000_000 {
println!("value_after_zero: {}", value_after_zero);
break;
}
}
}
}
| true |
18a5ba4faac16aff7e5a49bd7638ca783a53e2e6
|
Rust
|
sakamt/da-lab
|
/src/weight.rs
|
UTF-8
| 3,292 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
use ndarray::*;
use rand::*;
use rand::distributions::*;
use linalg::outer;
use types::*;
#[derive(Clone, Debug)]
pub struct Weight {
weight: Vec<f64>,
}
impl From<Vec<f64>> for Weight {
fn from(w: Vec<f64>) -> Weight {
Weight { weight: w }
}
}
impl Weight {
pub fn uniform(n: usize) -> Self {
vec![1.0 / n as f64; n].into()
}
pub fn random(n: usize) -> Self {
let dist = Range::new(0.0, 1.0);
let mut rng = thread_rng();
let w = Weight { weight: (0..n).map(|_| dist.ind_sample(&mut rng)).collect() };
w.normalized()
}
pub fn get_raw_weight(&self) -> &Vec<f64> {
&self.weight
}
pub fn normalize(&mut self) {
let sum: f64 = self.weight.iter().sum();
for x in self.weight.iter_mut() {
*x /= sum;
}
}
pub fn normalized(mut self) -> Self {
self.normalize();
self
}
pub fn mean(&self, xs: &Ensemble) -> V {
let n = xs[0].len();
xs.iter().zip(self.weight.iter()).fold(Array::zeros(n), |a,
(b, w)| {
a + b * *w
})
}
pub fn stat2(&self, xs: &Ensemble) -> (V, M) {
let n = xs[0].len();
let xm = self.mean(xs);
let cov = xs.iter().zip(self.weight.iter()).fold(
Array::zeros((n, n)),
|a, (b, w)| {
let dx = b - &xm;
a + *w * outer(&dx, &dx)
},
);
(xm, cov)
}
pub fn to_dist(&self) -> DiscreteDist {
DiscreteDist {
cumprob: self.weight
.iter()
.scan(0.0, |st, &x| {
*st = *st + x;
Some(*st)
})
.collect(),
}
}
}
#[derive(Clone, Debug)]
pub struct LogWeight {
logweight: Vec<f64>,
}
impl From<Vec<f64>> for LogWeight {
fn from(w: Vec<f64>) -> LogWeight {
LogWeight { logweight: w }
}
}
impl LogWeight {
pub fn get_raw_logweight(&self) -> &Vec<f64> {
&self.logweight
}
pub fn drop_mean(&mut self) {
let n = self.logweight.len();
let mean = self.logweight.iter().sum::<f64>() / n as f64;
for x in self.logweight.iter_mut() {
*x -= mean;
}
}
}
impl Into<LogWeight> for Weight {
fn into(self) -> LogWeight {
let mut lw = LogWeight { logweight: self.weight.into_iter().map(|x| x.ln()).collect() };
lw.drop_mean();
lw
}
}
impl Into<Weight> for LogWeight {
fn into(self) -> Weight {
let w = Weight { weight: self.logweight.into_iter().map(|x| x.exp()).collect() };
w.normalized()
}
}
#[derive(Clone, Debug)]
pub struct DiscreteDist {
cumprob: Vec<f64>,
}
fn searchsorted(a: f64, cumprob: &Vec<f64>) -> usize {
match cumprob.binary_search_by(|v| v.partial_cmp(&a).expect("Couldn't compare values")) {
Ok(idx) => idx,
Err(idx) => idx,
}
}
impl Sample<usize> for DiscreteDist {
fn sample<R: Rng>(&mut self, rng: &mut R) -> usize {
searchsorted(rng.next_f64(), &self.cumprob)
}
}
impl IndependentSample<usize> for DiscreteDist {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> usize {
searchsorted(rng.next_f64(), &self.cumprob)
}
}
| true |
e89dcf0f9bb4f7565c5697768de707388db611ac
|
Rust
|
youknowone/artichoke
|
/artichoke-backend/src/extn/core/integer/div.rs
|
UTF-8
| 3,552 | 3.25 | 3 |
[
"MIT",
"BSD-2-Clause"
] |
permissive
|
use crate::extn::core::float::Float;
use crate::extn::prelude::*;
use crate::types;
pub fn method(interp: &Artichoke, value: Value, other: Value) -> Result<Value, Exception> {
let x = value.try_into::<Int>().map_err(|_| {
Fatal::new(
interp,
"Unable to extract Rust Integer from Ruby Integer receiver",
)
})?;
let pretty_name = other.pretty_name();
if let Ok(y) = other.clone().try_into::<Int>() {
if y == 0 {
Err(Exception::from(ZeroDivisionError::new(
interp,
"divided by 0",
)))
} else {
Ok(interp.convert(x / y))
}
} else if let Ok(y) = other.try_into::<types::Float>() {
if y == 0.0 {
match x {
x if x > 0 => Ok(interp.convert(Float::INFINITY)),
x if x < 0 => Ok(interp.convert(Float::NEG_INFINITY)),
_ => Ok(interp.convert(Float::NAN)),
}
} else {
#[allow(clippy::cast_precision_loss)]
Ok(interp.convert(x as types::Float / y))
}
} else {
Err(Exception::from(TypeError::new(
interp,
format!("{} can't be coerced into Integer", pretty_name),
)))
}
}
#[cfg(test)]
mod tests {
use quickcheck_macros::quickcheck;
use crate::test::prelude::*;
#[quickcheck]
fn integer_division_vm_opcode(x: Int, y: Int) -> bool {
let interp = crate::interpreter().expect("init");
let mut result = true;
match (x, y) {
(0, 0) => result &= interp.eval(b"0 / 0").is_err(),
(x, 0) | (0, x) => {
let expr = format!("{} / 0", x).into_bytes();
result &= interp.eval(expr.as_slice()).is_err();
let expr = format!("0 / {}", x).into_bytes();
let division = interp
.eval(expr.as_slice())
.unwrap()
.try_into::<Int>()
.unwrap();
result &= division == 0
}
(x, y) => {
let expr = format!("{} / {}", x, y).into_bytes();
let division = interp
.eval(expr.as_slice())
.unwrap()
.try_into::<Int>()
.unwrap();
result &= division == x / y
}
}
result
}
#[quickcheck]
fn integer_division_send(x: Int, y: Int) -> bool {
let interp = crate::interpreter().expect("init");
let mut result = true;
match (x, y) {
(0, 0) => result &= interp.eval(b"0.send('/', 0)").is_err(),
(x, 0) | (0, x) => {
let expr = format!("{}.send('/', 0)", x).into_bytes();
result &= interp.eval(expr.as_slice()).is_err();
let expr = format!("0.send('/', {})", x).into_bytes();
let division = interp
.eval(expr.as_slice())
.unwrap()
.try_into::<Int>()
.unwrap();
result &= division == 0
}
(x, y) => {
let expr = format!("{}.send('/', {})", x, y).into_bytes();
let division = interp
.eval(expr.as_slice())
.unwrap()
.try_into::<Int>()
.unwrap();
result &= division == x / y
}
}
result
}
}
| true |
acf9bbc13447045cabc2eda8555bc5c8a2d70128
|
Rust
|
WCollier/Interpreter
|
/src/ast.rs
|
UTF-8
| 291 | 2.671875 | 3 |
[] |
no_license
|
#[derive(Copy, Clone, Debug)]
pub(crate) enum BinopKind {
Plus,
Minus,
Times,
Divide,
}
#[derive(Clone, Debug)]
pub(crate) enum Stmt {
Binding(String, Expr)
}
#[derive(Clone, Debug)]
pub(crate) enum Expr {
Number(i32),
Binop(BinopKind, Box<Expr>, Box<Expr>),
}
| true |
ad16b1498dcbd42fb57fb1e8cea8c1fa86b48448
|
Rust
|
Razaekel/noise-rs
|
/examples/textureslime.rs
|
UTF-8
| 2,549 | 2.75 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
extern crate noise;
use noise::{utils::*, *};
mod utils;
fn main() {
// Large slime bubble texture.
let large_slime = Billow::<Perlin>::new(0)
.set_frequency(4.0)
.set_lacunarity(2.12109375)
.set_octaves(1);
// Base of the small slime bubble texture. This texture will eventually
// appear inside cracks in the large slime bubble texture.
let small_slime_base = Billow::<Perlin>::new(1)
.set_frequency(24.0)
.set_lacunarity(2.14453125)
.set_octaves(1);
// Scale and lower the small slime bubble values.
let small_slime = ScaleBias::new(small_slime_base)
.set_scale(0.5)
.set_bias(-0.5);
// Create a map that specifies where the large and small slime bubble
// textures will appear in the final texture map.
let slime_map = RidgedMulti::<Perlin>::new(2)
.set_frequency(2.0)
.set_lacunarity(2.20703125)
.set_octaves(3);
// Choose between the large or small slime bubble textures depending on
// the corresponding value from the slime map. Choose the small slime
// bubble texture if the slime map value is within a narrow range of
// values, otherwise choose the large slime bubble texture. The edge
// falloff is non-zero so that there is a smooth transition between the
// two textures.
let slime_chooser = Select::new(large_slime, small_slime, slime_map)
.set_bounds(-0.375, 0.375)
.set_falloff(0.5);
// Finally, perturb the slime texture to add realism.
let final_slime = Turbulence::<_, Perlin>::new(slime_chooser)
.set_seed(3)
.set_frequency(8.0)
.set_power(1.0 / 32.0)
.set_roughness(2);
let planar_texture = PlaneMapBuilder::new(&final_slime)
.set_size(1024, 1024)
.build();
let seamless_texture = PlaneMapBuilder::new(final_slime)
.set_size(1024, 1024)
.set_is_seamless(true)
.build();
// Create a slime palette.
let slime_gradient = ColorGradient::new()
.clear_gradient()
.add_gradient_point(-1.0, [160, 64, 42, 255])
.add_gradient_point(0.0, [64, 192, 64, 255])
.add_gradient_point(1.0, [128, 255, 128, 255]);
let mut renderer = ImageRenderer::new().set_gradient(slime_gradient);
utils::write_image_to_file(
&renderer.render(&planar_texture),
"texture_slime_planar.png",
);
utils::write_image_to_file(
&renderer.render(&seamless_texture),
"texture_slime_seamless.png",
);
}
| true |
32c5e3d0b91755cea90cebb3ff3280ceec02164c
|
Rust
|
pimeys/blocking_test
|
/src/postgresql/conversion.rs
|
UTF-8
| 8,600 | 2.703125 | 3 |
[] |
no_license
|
use crate::IntoJson;
use chrono::{DateTime, NaiveDateTime, Utc};
use postgres::{types::Type, Row};
use rust_decimal::Decimal;
use serde_json::{Map, Number, Value};
use uuid::Uuid;
impl IntoJson for Vec<Row> {
fn into_json(self) -> crate::Result<Value> {
let mut result = Vec::new();
for row in self.into_iter() {
result.push(row.into_json()?);
}
Ok(Value::Array(result))
}
}
impl IntoJson for Row {
fn into_json(self) -> crate::Result<Value> {
let mut object = Map::new();
for (idx, column) in self.columns().iter().enumerate() {
let column_name: String = column.name().into();
let value = match *column.type_() {
Type::VOID => Value::Null,
Type::BOOL => match self.try_get(idx)? {
Some(val) => Value::Bool(val),
None => Value::Null,
},
Type::INT2 => match self.try_get(idx)? {
Some(val) => {
let val: i16 = val;
Value::Number(Number::from(val))
}
None => Value::Null,
},
Type::INT4 => match self.try_get(idx)? {
Some(val) => {
let val: i32 = val;
Value::Number(Number::from(val))
}
None => Value::Null,
},
Type::INT8 => match self.try_get(idx)? {
Some(val) => {
let val: i64 = val;
Value::Number(Number::from(val))
}
None => Value::Null,
},
Type::NUMERIC => match self.try_get(idx)? {
Some(val) => {
let val: Decimal = val;
let val: f64 = val.to_string().parse().unwrap();
Value::Number(Number::from_f64(val).unwrap())
}
None => Value::Null,
},
Type::FLOAT4 => match self.try_get(idx)? {
Some(val) => {
let val: f32 = val;
let val = f64::from(val);
Value::Number(Number::from_f64(val).unwrap())
}
None => Value::Null,
},
Type::FLOAT8 => match self.try_get(idx)? {
Some(val) => {
let val: f64 = val;
Value::Number(Number::from_f64(val).unwrap())
}
None => Value::Null,
},
Type::TIMESTAMP => match self.try_get(idx)? {
Some(val) => {
let ts: NaiveDateTime = val;
let dt = DateTime::<Utc>::from_utc(ts, Utc);
Value::String(dt.to_rfc3339())
}
None => Value::Null,
},
Type::UUID => match self.try_get(idx)? {
Some(val) => {
let val: Uuid = val;
Value::String(val.to_hyphenated().to_string())
}
None => Value::Null,
},
Type::INT2_ARRAY => match self.try_get(idx)? {
Some(val) => {
let val: Vec<i16> = val;
Value::Array(
val.into_iter()
.map(|x| Value::Number(Number::from(x)))
.collect(),
)
}
None => Value::Null,
},
Type::INT4_ARRAY => match self.try_get(idx)? {
Some(val) => {
let val: Vec<i32> = val;
Value::Array(
val.into_iter()
.map(|x| Value::Number(Number::from(x)))
.collect(),
)
}
None => Value::Null,
},
Type::INT8_ARRAY => match self.try_get(idx)? {
Some(val) => {
let val: Vec<i64> = val;
Value::Array(
val.into_iter()
.map(|x| Value::Number(Number::from(x)))
.collect(),
)
}
None => Value::Null,
},
Type::FLOAT4_ARRAY => match self.try_get(idx)? {
Some(val) => {
let val: Vec<f32> = val;
Value::Array(
val.into_iter()
.map(|x| Value::Number(Number::from_f64(f64::from(x)).unwrap()))
.collect(),
)
}
None => Value::Null,
},
Type::FLOAT8_ARRAY => match self.try_get(idx)? {
Some(val) => {
let val: Vec<f64> = val;
Value::Array(
val.into_iter()
.map(|x| Value::Number(Number::from_f64(x).unwrap()))
.collect(),
)
}
None => Value::Null,
},
Type::BOOL_ARRAY => match self.try_get(idx)? {
Some(val) => {
let val: Vec<bool> = val;
Value::Array(val.into_iter().map(|x| Value::Bool(x)).collect())
}
None => Value::Null,
},
Type::TIMESTAMP_ARRAY => match self.try_get(idx)? {
Some(val) => {
let val: Vec<NaiveDateTime> = val;
Value::Array(
val.into_iter()
.map(|x| {
let dt = DateTime::<Utc>::from_utc(x, Utc);
Value::String(dt.to_rfc3339())
})
.collect(),
)
}
None => Value::Null,
},
Type::NUMERIC_ARRAY => match self.try_get(idx)? {
Some(val) => {
let val: Vec<Decimal> = val;
Value::Array(
val.into_iter()
.map(|x| {
let val: f64 = x.to_string().parse().unwrap();
Value::Number(Number::from_f64(val).unwrap())
})
.collect(),
)
}
None => Value::Null,
},
Type::TEXT_ARRAY | Type::NAME_ARRAY | Type::VARCHAR_ARRAY => {
match self.try_get(idx)? {
Some(val) => {
let val: Vec<String> = val;
Value::Array(val.into_iter().map(|x| Value::String(x)).collect())
}
None => Value::Null,
}
}
Type::OID => match self.try_get(idx)? {
Some(val) => {
let val: u32 = val;
Value::Number(Number::from(val))
}
None => Value::Null,
},
Type::CHAR => match self.try_get(idx)? {
Some(val) => {
let val: i8 = val;
Value::String(val.to_string())
}
None => Value::Null,
},
_ => match self.try_get(idx)? {
Some(val) => {
let val: String = val;
Value::String(val)
}
None => Value::Null,
},
};
object.insert(column_name, value);
}
Ok(Value::Object(object))
}
}
| true |
00b7df0792039b5d89c01eba27eb62fe037c3cf3
|
Rust
|
muffix/exercism-rust
|
/acronym/src/lib.rs
|
UTF-8
| 703 | 3.609375 | 4 |
[] |
no_license
|
pub fn abbreviate(phrase: &str) -> String {
phrase
.chars()
.map(|c| if c.is_alphabetic() { c } else { ' ' })
.collect::<String>()
.split_whitespace()
.map(|word| abbreviate_word(word))
.collect()
}
fn abbreviate_word(word: &str) -> String {
let uppercase_chars: String = word.chars().filter(|c| c.is_uppercase()).collect();
return match uppercase_chars.len() {
0 => first_char_uppercase(word).to_string(),
n if n == word.len() => first_char_uppercase(&uppercase_chars).to_string(),
_ => uppercase_chars,
};
}
fn first_char_uppercase(word: &str) -> char {
word.chars().next().unwrap().to_ascii_uppercase()
}
| true |
f721b3d75d6ff915e9daa8e8bef3f3929126aa91
|
Rust
|
ajunlonglive/coroutine-benchmarks
|
/src/atomic_spin.rs
|
UTF-8
| 4,242 | 2.828125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::ffi::c_void;
use std::sync::atomic::{AtomicU64, Ordering};
use std::os::raw::c_int;
/// A common utility class for client and server.
/// the contract is the client will only write to
/// the client atomic, and the server only to
/// the server atomic.
pub struct MappedAtomics {
pub client_write: &'static AtomicU64,
pub server_write: &'static AtomicU64,
mmap_ptr: *mut c_void,
}
impl MappedAtomics {
/// this is only called from the server_loop.
/// The compilers seem to like this better
/// in a separate function than in-line by hand.
#[inline(always)]
pub fn server_spin_until_change(&self, last_value: u64) -> u64 {
let mut new_value = last_value;
while new_value == last_value {
core::hint::spin_loop();
new_value = self.client_write.load(Ordering::Relaxed);
}
new_value
}
pub fn do_server_loop(&self) {
let mut last_value: u64 = 0;
loop {
last_value = self.server_spin_until_change(last_value);
self.server_write.store(last_value, Ordering::Relaxed);
}
}
#[inline(always)]
pub fn client_run_once(&self, value: u64) {
self.client_write.store(value, Ordering::Relaxed);
let mut last_read = !value;
while value != last_read {
core::hint::spin_loop();
last_read = self.server_write.load(Ordering::Relaxed);
}
}
/// open or create the shared memory atomics.
/// whichever is the first to start should
/// create, the second should pass 'false' and fail
/// if the expected named memory doesn't exist.
pub fn new(do_create: bool) -> MappedAtomics {
unsafe {
let mem_fd = MappedAtomics::shm_open(do_create);
if libc::ftruncate(mem_fd, page_size::get() as i64) < 0 {
panic!(
"can't truncate shared memory FD. error num : {}. page size = {}",
*libc::__errno_location(),
page_size::get()
);
}
let mem_ptr = MappedAtomics::mmap( mem_fd );
let first_ptr = mem_ptr as *mut u64;
// set the second atomic a few cache lines down.
let second_ptr = (mem_ptr as *mut u8).add(2048) as *mut u64;
assert_ne!(first_ptr, second_ptr);
let mapped_atomics = MappedAtomics {
client_write: &*(first_ptr as *const AtomicU64),
// scooch down a cache line or two.
server_write: &*(second_ptr as *const AtomicU64),
mmap_ptr: mem_ptr,
};
// only zero out on creation, lest we romp on the values
// when the server starts up, after the client has been running.
if do_create {
mapped_atomics.client_write.store(0, Ordering::Relaxed);
mapped_atomics.server_write.store(0, Ordering::Relaxed);
}
mapped_atomics
}
}
unsafe fn shm_open(do_create:bool) -> c_int {
let mem_fd = libc::shm_open(
crate::SH_MEM_NAME.as_ptr(),
if do_create {
libc::O_CREAT | libc::O_RDWR
} else {
libc::O_RDWR
},
libc::S_IRUSR | libc::S_IWUSR | libc::S_IRGRP | libc::S_IWGRP,
);
if mem_fd < 0 {
panic!(
"can't create shared memory. error num : {}",
*libc::__errno_location()
);
}
mem_fd
}
unsafe fn mmap(shm_fd:c_int) -> *mut c_void {
let mem_ptr = libc::mmap(
std::ptr::null_mut(),
page_size::get(),
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED,
shm_fd,
0,
);
if mem_ptr == libc::MAP_FAILED {
panic!(
"mmap shared memory failed. error code : {}",
*libc::__errno_location()
);
}
mem_ptr
}
pub fn close(&self) {
unsafe {
libc::munmap(self.mmap_ptr, page_size::get());
libc::shm_unlink(crate::SH_MEM_NAME.as_ptr());
}
}
}
| true |
db3dada465bd0a972ebfe5105e4019c0767ba804
|
Rust
|
sjoshid/sapling
|
/src/editor/keystroke_log.rs
|
UTF-8
| 6,359 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
//! A utility datastructure to store and render a log of keystrokes. This is mostly used to give
//! the viewers of my streams feedback for what I'm typing.
use crate::core::keystrokes_to_string;
#[allow(unused_imports)] // Only used by doc-comments, which rustc can't see
use super::normal_mode::Action;
use tuikit::prelude::*;
/// A category grouping similar actions
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Category {
/// An [`Action`] that moves the cursor
Move,
/// Either [`Action::Undo`] or [`Action::Redo`]
History,
/// An [`Action`] that inserts extra nodes into the tree
Insert,
/// An [`Action`] that replaces some nodes in the tree
Replace,
/// An [`Action`] that causes nodes to be deleted from the tree
Delete,
/// The action of the keystrokes is that Sapling should quit
Quit,
/// An [`Action`] that handles reading and writing from disk
IO,
/// The keystrokes did not correspond to a well-defined action
Undefined,
}
/// Returns the [`Color`] that all [`Action`]s of a given [`Category`] should be
/// displayed. This is not implemented as a method on [`Category`], because doing so
/// would require [`Category`] to rely on the specific terminal backend used. This way,
/// we keep the terminal backend as encapsulated as possible.
impl Category {
fn term_color(self) -> Color {
match self {
Category::Move => Color::LIGHT_BLUE,
Category::History => Color::LIGHT_YELLOW,
Category::Insert => Color::LIGHT_GREEN,
Category::Replace => Color::CYAN,
Category::Delete => Color::RED,
Category::Quit => Color::MAGENTA,
Category::IO => Color::GREEN,
Category::Undefined => Color::LIGHT_RED,
}
}
}
/// One entry in the log. This usually represts a single keystroke, but could represent an
/// accumulation of many identical keystrokes that are executed consecutively.
struct Entry {
count: usize,
keystrokes: Vec<Key>,
description: String,
color: Color,
}
impl Entry {
fn keystroke_string(&self) -> String {
keystrokes_to_string(&self.keystrokes)
}
}
/// A utility struct to store and display a log of which keystrokes have been executed recently.
/// This is mostly used to give the viewers of my streams feedback for what I'm typing.
pub struct KeyStrokeLog {
/// A list of keystrokes that have been run
keystrokes: Vec<Entry>,
/// The maximum number of entries that should be displayed at once
max_entries: usize,
/// The keystrokes that will be included in the next log entry
unlogged_keystrokes: Vec<Key>,
}
impl KeyStrokeLog {
/// Create a new (empty) keystroke log
pub fn new(max_entries: usize) -> KeyStrokeLog {
KeyStrokeLog {
keystrokes: vec![],
max_entries,
unlogged_keystrokes: vec![],
}
}
/// Sets and enforces the max entry limit
pub fn set_max_entries(&mut self, max_entries: usize) {
self.max_entries = max_entries;
self.enforce_entry_limit();
}
/// Draw a log of recent keystrokes to a given terminal at a given location
pub fn render(&self, term: &Term, row: usize, col: usize) {
// Calculate how wide the numbers column should be, enforcing that it is at least two
// chars wide.
let count_col_width = self
.keystrokes
.iter()
.map(|e| match e.count {
1 => 0,
c => format!("{}x", c).len(),
})
.max()
.unwrap_or(0)
.max(2);
// Calculate the width of the keystroke column, and make sure that it is at least two
// chars wide.
let cmd_col_width = self
.keystrokes
.iter()
.map(|e| e.keystroke_string().len())
.max()
.unwrap_or(0)
.max(2);
// Render the keystrokes
for (i, e) in self.keystrokes.iter().enumerate() {
// Print the count if greater than 1
if e.count > 1 {
term.print(row + i, col, &format!("{}x", e.count)).unwrap();
}
// Print the keystrokes in one column
term.print_with_attr(
row + i,
col + count_col_width + 1,
&e.keystroke_string(),
Attr::default().fg(Color::WHITE),
)
.unwrap();
// Print a `=>`
term.print(row + i, col + count_col_width + 1 + cmd_col_width + 1, "=>")
.unwrap();
// Print the meanings in another column
term.print_with_attr(
row + i,
col + count_col_width + 1 + cmd_col_width + 4,
&e.description,
Attr::default().fg(e.color),
)
.unwrap();
}
}
/// Repeatedly remove keystrokes until the entry limit is satisfied
fn enforce_entry_limit(&mut self) {
while self.keystrokes.len() > self.max_entries {
self.keystrokes.remove(0);
}
}
/// Log a new [`Key`] that should be added to the next log entry.
pub fn push_key(&mut self, key: Key) {
self.unlogged_keystrokes.push(key);
}
/// Creates a new entry in the log, which occured as a result of the [`Key`]s already
/// [`push_key`](Self::push_key)ed.
pub fn log_entry(&mut self, description: String, category: Category) {
// If the keystroke is identical to the last log entry, incrememnt that counter by one
if Some(&self.unlogged_keystrokes) == self.keystrokes.last().map(|e| &e.keystrokes) {
// We can safely unwrap here, because the guard of the `if` statement guaruntees
// that `self.keystroke.last()` is `Some(_)`
self.keystrokes.last_mut().unwrap().count += 1;
} else {
self.keystrokes.push(Entry {
count: 1,
keystrokes: self.unlogged_keystrokes.clone(),
description,
color: category.term_color(),
});
// Since we added an item, we should enforce the entry limit
self.enforce_entry_limit();
}
self.unlogged_keystrokes.clear();
}
}
| true |
396c8f24d88d79f70d752fa983c288054bac2f29
|
Rust
|
hgentry/euler
|
/src/problems/p32.rs
|
UTF-8
| 1,808 | 3.5 | 4 |
[] |
no_license
|
/*
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
*/
pub fn solve() -> i64 {
let mut sum = 0;
let mut list = vec![];
let perms = generate_permutations();
for i in perms {
for j in 0..i {
let n = i * j;
let mut digits = vec![];
let parse = vec![i, j, n];
let mut failure = false;
let mut len = 0;
for k in parse {
let mut k_p = k;
while k_p > 0 {
let digit = k_p % 10;
k_p = k_p / 10;
if digit != 0 && !digits.contains(&digit) {
digits.push(digit);
len += 1;
} else {
failure = true;
break;
}
}
if failure {
break;
}
}
if len != 9 {
failure = true;
}
if failure {
continue;
} else {
if !list.contains(&n) {
sum += n;
list.push(n);
}
}
}
}
sum
}
pub fn generate_permutations() -> Vec<i64> {
let mut perms = vec![];
for i in 0..1970 {
let mut i_p = i;
let mut digits = vec![];
let mut failure = false;
while i_p != 0 {
let digit = i_p % 10;
i_p = i_p / 10;
if !digits.contains(&digit) && digit != 0 {
digits.push(digit);
} else {
failure = true;
break;
}
}
if failure {
continue;
} else {
perms.push(i);
}
}
perms
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correct() {
assert_eq!(solve(), 45228);
}
}
| true |
5e63383e1dc303fcf37c7656459966d5f52f5953
|
Rust
|
wsdjeg/stunnel
|
/src/tcp.rs
|
UTF-8
| 3,200 | 3.078125 | 3 |
[] |
no_license
|
use std::net::TcpStream;
use std::net::Shutdown;
use std::io::Read;
use std::io::Write;
use std::io::Error;
use std::io::ErrorKind;
use std::vec::Vec;
pub struct Tcp {
stream: TcpStream
}
impl Tcp {
pub fn new(stream: TcpStream) -> Tcp {
Tcp { stream: stream }
}
pub fn shutdown(&self) {
let _ = self.stream.shutdown(Shutdown::Both);
}
pub fn read_u8(&mut self) -> Result<u8, Error> {
let mut buf = [0u8];
try!(self.read_exact_buf(&mut buf));
Ok(buf[0])
}
pub fn read_u16(&mut self) -> Result<u16, Error> {
let mut buf = [0u8; 2];
try!(self.read_exact_buf(&mut buf));
let result = unsafe { *(buf.as_ptr() as *const u16) };
Ok(u16::from_be(result))
}
pub fn read_u32(&mut self) -> Result<u32, Error> {
let mut buf = [0u8; 4];
try!(self.read_exact_buf(&mut buf));
let result = unsafe { *(buf.as_ptr() as *const u32) };
Ok(u32::from_be(result))
}
pub fn read_u64(&mut self) -> Result<u64, Error> {
let mut buf = [0u8; 8];
try!(self.read_exact_buf(&mut buf));
let result = unsafe { *(buf.as_ptr() as *const u64) };
Ok(u64::from_be(result))
}
pub fn read_exact(&mut self, size: usize) -> Result<Vec<u8>, Error> {
let mut buf = Vec::with_capacity(size);
unsafe { buf.set_len(size); }
try!(self.read_exact_buf(&mut buf[..]));
Ok(buf)
}
pub fn read_exact_buf(&mut self, buf: &mut [u8]) -> Result<(), Error> {
let size = buf.len();
let mut length = 0;
while length < size {
let len = try!(self.stream.read(&mut buf[length..]));
if len == 0 {
return Err(Error::new(ErrorKind::Other, "eof"));
} else {
length += len;
}
}
Ok(())
}
pub fn read_at_most(&mut self, size: usize) -> Result<Vec<u8>, Error> {
let mut buf = Vec::with_capacity(size);
unsafe { buf.set_len(size); }
let len = try!(self.stream.read(&mut buf[..]));
if len == 0 {
return Err(Error::new(ErrorKind::Other, "eof"));
} else {
unsafe { buf.set_len(len); }
}
Ok(buf)
}
pub fn write_u8(&mut self, v: u8) -> Result<(), Error> {
let buf = [v];
self.write(&buf)
}
pub fn write_u16(&mut self, v: u16) -> Result<(), Error> {
let buf = [0u8; 2];
unsafe { *(buf.as_ptr() as *mut u16) = v.to_be(); }
self.write(&buf)
}
pub fn write_u32(&mut self, v: u32) -> Result<(), Error> {
let buf = [0u8; 4];
unsafe { *(buf.as_ptr() as *mut u32) = v.to_be(); }
self.write(&buf)
}
pub fn write_u64(&mut self, v: u64) -> Result<(), Error> {
let buf = [0u8; 8];
unsafe { *(buf.as_ptr() as *mut u64) = v.to_be(); }
self.write(&buf)
}
pub fn write(&mut self, buf: &[u8]) -> Result<(), Error> {
let size = buf.len();
let mut length = 0;
while length < size {
length += try!(self.stream.write(&buf[length..]));
}
Ok(())
}
}
| true |
c7de21fe0524d90607317084534f3eabcd43844b
|
Rust
|
zaki-yama/leetcode
|
/459.repeated-substring-pattern.rs
|
UTF-8
| 353 | 2.703125 | 3 |
[] |
no_license
|
/*
* @lc app=leetcode id=459 lang=rust
*
* [459] Repeated Substring Pattern
*/
// @lc code=start
impl Solution {
pub fn repeated_substring_pattern(s: String) -> bool {
let a = String::from(&s) + &s;
println!("{}", a);
println!("{}", &a[1..a.len()]);
a[1..a.len() - 1].find(&s).is_some()
}
}
// @lc code=end
| true |
040f1950ad792dea02ebf8af61f7752d52ae0b41
|
Rust
|
magistrser/sequential-integration
|
/src/engine/quadrature/simpson/utils/simpson_points.rs
|
UTF-8
| 715 | 2.640625 | 3 |
[] |
no_license
|
use crate::engine::{Bounds, CalculationStep};
pub struct SimpsonPoints {
pub v0: f64,
pub v1: f64,
pub v2: f64,
pub h: f64,
}
impl SimpsonPoints {
pub fn generate(
step: CalculationStep,
bounds: Bounds,
step_size: f64,
is_last_step: &mut bool,
) -> Self {
let v0 = *step;
let (v1, v2, h) = if step.is_last() {
*is_last_step = true;
let v2 = bounds.end;
let h = (v2 - v0) / 2.;
let v1 = v0 + h;
(v1, v2, h)
} else {
let v1 = v0 + step_size;
let v2 = v1 + step_size;
(v1, v2, step_size)
};
Self { v0, v1, v2, h }
}
}
| true |
fa937c7d481bacb55c901b08ceb57721c5a54cf4
|
Rust
|
kumabook/uenc
|
/src/udec.rs
|
UTF-8
| 747 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
extern crate url;
use url::percent_encoding::{lossy_utf8_percent_decode};
use std::env;
use std::io::{self};
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
let stdin = io::stdin();
loop {
let mut buffer = String::new();
match stdin.read_line(&mut buffer) {
Ok(len) => {
if len > 0 {
print!("{}", decode(&buffer))
} else {
return
}
}
Err(_) => return,
}
}
}
println!("{}", decode(&args[1]));
}
fn decode(str: &String) -> String {
return lossy_utf8_percent_decode(str.as_bytes());
}
| true |
75cfb270f7226250aa697cf0bb093684746e66ee
|
Rust
|
kevindragon/leetcode-rust
|
/src/problem62.rs
|
UTF-8
| 594 | 3.453125 | 3 |
[] |
no_license
|
//! 面试题62. 圆圈中最后剩下的数字
//! https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/
pub struct Solution;
impl Solution {
pub fn last_remaining(n: i32, m: i32) -> i32 {
let mut p = 0;
for i in 2..=n {
p = (p + m) % i;
}
p
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_last_remaining() {
assert_eq!(Solution::last_remaining(5, 3), 3);
assert_eq!(Solution::last_remaining(10, 17), 2);
assert_eq!(Solution::last_remaining(10, 2), 4);
}
}
| true |
628e58bce8089fc56b68162886fd0f4706ee196a
|
Rust
|
hiroshi-maybe/atcoder
|
/solutions/lrud_instructions.rs
|
UTF-8
| 6,590 | 2.515625 | 3 |
[] |
no_license
|
#![allow(unused_macros, unused_imports)]
use std::cmp::*;
use std::collections::*;
// $ cp-batch lrud_instructions | diff lrud_instructions.out -
// $ cargo run --bin lrud_instructions
///
/// 10/15/2022
///
/// 23:58-24:06 pause
///
/// 10/16/2022
///
/// 8:53-9:20 RE
/// 9:22 bug fix and AC
///
/// https://atcoder.jp/contests/abc273/editorial/5022
///
fn solve() -> Vec<(isize, isize)> {
let (h, w, rs, cs) = readln!(isize, isize, isize, isize);
let n = readln!(usize);
let (mut mapr, mut mapc) = (BTreeMap::new(), BTreeMap::new());
for (r, c) in readlns!(isize, isize; n) {
let e = mapr.entry(r).or_insert(vec![]);
e.push(c);
let e = mapc.entry(c).or_insert(vec![]);
e.push(r);
}
for (_, vec) in &mut mapr {
vec.push(0);
vec.push(w + 1);
vec.sort_unstable();
}
for (_, vec) in &mut mapc {
vec.push(0);
vec.push(h + 1);
vec.sort_unstable();
}
let q = readln!(usize);
let (mut i, mut j) = (rs, cs);
let mut res = vec![];
for (d, l) in readlns!(char, isize; q) {
// dbgln!(d, l, i, j);
match d {
'L' | 'R' => {
let delta = if d == 'L' { -1isize } else { 1 };
let (lb, hb) = if let Some(cs) = mapr.get(&i) {
let ub_pos = cs.upper_bound(&j);
(cs[ub_pos - 1] + 1, cs[ub_pos] - 1)
} else {
(1, w)
};
j = j + l * delta;
j.setmin(hb);
j.setmax(lb);
}
'U' | 'D' => {
let delta = if d == 'U' { -1isize } else { 1 };
let (lb, hb) = if let Some(rs) = mapc.get(&j) {
let ub_pos = rs.upper_bound(&i);
(rs[ub_pos - 1] + 1, rs[ub_pos] - 1)
} else {
(1, h)
};
i = i + l * delta;
i.setmin(hb);
i.setmax(lb);
}
_ => unreachable!(),
}
// dbgln!(d, l, i, j);
res.push((i, j));
}
res
}
fn main() {
setup_out!(put, puts);
let res = solve();
for (r, c) in res {
puts!("{} {}", r, c);
}
}
// region: partition
#[rustfmt::skip]
#[allow(dead_code)]
mod partition {
use std::cmp::Ordering;
pub trait PartitionSlice {
type Item;
/// Find the partition point for which left segment satisifies the predicate
/// [pred(item)] = [true, true, true, false, false]
/// ^ res
fn _partition_point<P>(&self, pred: P) -> usize where P: FnMut(&Self::Item) -> bool;
/// Find the smallest index which satisfies key <= a[i]
fn lower_bound(&self, key: &Self::Item) -> usize where Self::Item: Ord {
self._partition_point(|item| item < key)
}
/// Find the smallest index which satisfies key < a[i]
fn upper_bound(&self, key: &Self::Item) -> usize where Self::Item: Ord {
self._partition_point(|item| item <= key)
}
}
impl<T> PartitionSlice for [T] {
type Item = T;
fn _partition_point<P>(&self, mut pred: P) -> usize where P: FnMut(&T) -> bool {
self.binary_search_by(|x| { if pred(x) { Ordering::Less } else { Ordering::Greater }})
.unwrap_or_else(std::convert::identity)
}
}
}
pub use partition::PartitionSlice;
// endregion: partition
use crate::cplib::io::*;
use crate::cplib::minmax::*;
use crate::cplib::vec::*;
// region: cplib
#[rustfmt::skip]
#[allow(dead_code)]
pub mod cplib {
pub mod io {
macro_rules! _with_dollar_sign { ($($body:tt)*) => { macro_rules! __with_dollar_sign { $($body)* } __with_dollar_sign!($); }}
macro_rules! setup_out {
($fn:ident,$fn_s:ident) => {
use std::io::Write;
let out = std::io::stdout();
let mut out = ::std::io::BufWriter::new(out.lock());
_with_dollar_sign! { ($d:tt) => {
macro_rules! $fn { ($d($format:tt)*) => { let _ = write!(out,$d($format)*); } }
macro_rules! $fn_s { ($d($format:tt)*) => { let _ = writeln!(out,$d($format)*); } }
}}
};
}
macro_rules! _epr { ($v:expr $(,)?) => {eprint!("{} = {:?}, ", stringify!($v), $v)}; }
macro_rules! dbgln { ($($val:expr),*) => {{ eprint!("[{}:{}] ", file!(), line!()); ($(_epr!($val)),*); eprintln!(); }}; }
pub fn readln_str() -> String {
let mut line = String::new();
::std::io::stdin().read_line(&mut line).unwrap_or_else(|e| panic!("{}", e));
line
}
macro_rules! _read {
($it:ident; [char]) => { _read!($it; String).chars().collect::<Vec<_>>() };
($it:ident; [u8]) => { Vec::from(_read!($it; String).into_bytes()) };
($it:ident; usize1) => { $it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1 };
($it:ident; [usize1]) => { $it.map(|s| s.parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1).collect::<Vec<_>>() };
($it:ident; [$t:ty]) => { $it.map(|s| s.parse::<$t>().unwrap_or_else(|e| panic!("{}", e))).collect::<Vec<_>>() };
($it:ident; $t:ty) => { $it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<$t>().unwrap_or_else(|e| panic!("{}", e)) };
($it:ident; $($t:tt),+) => { ($(_read!($it; $t)),*) };
}
macro_rules! readlns {
($($t:tt),*; $n:expr) => {{ let stdin = ::std::io::stdin();
::std::io::BufRead::lines(stdin.lock()).take($n).map(|line| {
let line = line.unwrap(); #[allow(unused_mut)]let mut it = line.split_whitespace(); _read!(it; $($t),*)
}).collect::<Vec<_>>()
}};
}
macro_rules! readln {
($($t:tt),*) => {{ let line = cplib::io::readln_str(); #[allow(unused_mut)]let mut it = line.split_whitespace(); _read!(it; $($t),*) }};
}
pub(crate) use {readlns, readln, setup_out, dbgln, _with_dollar_sign, _epr, _read};
}
pub mod minmax {
pub trait SetMinMax {
fn setmin(&mut self, other: Self) -> bool;
fn setmax(&mut self, other: Self) -> bool;
}
macro_rules! _set { ($self:ident, $cmp:tt, $other:ident) => {{
let update = $other $cmp *$self;
if update { *$self = $other; }
update
}}; }
impl<T> SetMinMax for T where T: PartialOrd {
fn setmin(&mut self, other: T) -> bool { _set!(self, <, other) }
fn setmax(&mut self, other: T) -> bool { _set!(self, >, other) }
}
}
pub mod vec {
pub trait CollectVec: Iterator { fn collect_vec(self) -> Vec<Self::Item> where Self: Sized { self.collect() } }
impl<T> CollectVec for T where T: Iterator {}
macro_rules! vvec {
($v:expr; $n:expr) => { Vec::from(vec![$v; $n]) };
($v:expr; $n:expr $(; $ns:expr)+) => { Vec::from(vec![vvec![$v $(; $ns)*]; $n]) };
}
pub(crate) use vvec;
}
}
// endregion: cplib
| true |
72379aacb828e941a6eb9bd15d826a63cf7ee371
|
Rust
|
facebookexperimental/rust-shed
|
/shed/borrowed/src/lib.rs
|
UTF-8
| 8,295 | 2.78125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
#![deny(warnings, missing_docs, clippy::all, rustdoc::broken_intra_doc_links)]
//! See examples for what code you can write with borrowed macro.
//!
//! # Examples
//!
//! ```
//! # use borrowed::borrowed;
//! struct A {
//! x: u32,
//! y: u32,
//! z: u32,
//! }
//! impl A {
//! fn foo(&self) {
//! borrowed!(self.x, self.y, self.z);
//! (move || {
//! println!("{} {} {}", x, y, z);
//! })();
//! }
//! }
//! # fn main () {}
//! ```
//!
//! It also supports setting the borrow type if its ambiguous:
//! ```
//! # use borrowed::borrowed;
//! # fn main () {
//! let foo = "foo".to_string();
//! borrowed!(foo as bar: &str);
//! assert!(&foo == bar);
//! # }
//! ```
//!
//! It also supports setting a local alias:
//! ```
//! # use borrowed::borrowed;
//! # fn main () {
//! let foo = 42;
//! borrowed!(foo as bar);
//! assert!(&foo == bar);
//! # }
//! ```
//!
//! And the two can be combined:
//! ```
//! # use borrowed::borrowed;
//! # fn main () {
//! let foo = "foo".to_string();
//! borrowed!(foo as bar: &str);
//! assert!(&foo == bar);
//! # }
//! ```
/// See crate's documentation
#[macro_export]
macro_rules! borrowed {
// Ambigous, so need to specify type
($i:ident as $alias:ident : $borrow:ty) => {
let $alias: $borrow = {
use std::borrow::Borrow;
$i.borrow()
};
};
// If borrow is unambigous
($i:ident as $alias:ident) => {
let $alias = {
use std::borrow::Borrow;
$i.borrow()
};
};
(mut $i:ident as $alias:ident : $borrow:ty) => {
let mut $alias: $borrow = {
use std::borrow::Borrow;
$i.borrow()
};
};
(mut $i:ident as $alias:ident) => {
let mut $alias = {
use std::borrow::Borrow;
$i.borrow()
};
};
($i:ident as $alias:ident : $borrow:ty, $($tt:tt)*) => {
borrowed!($i as $alias: $borrow);
borrowed!($($tt)*);
};
($i:ident as $alias:ident, $($tt:tt)*) => {
borrowed!($i as $alias);
borrowed!($($tt)*);
};
(mut $i:ident as $alias:ident : $borrow:ty, $($tt:tt)*) => {
borrowed!(mut $i as $alias: $borrow);
borrowed!($($tt)*);
};
(mut $i:ident as $alias:ident, $($tt:tt)*) => {
borrowed!(mut $i as $alias);
borrowed!($($tt)*);
};
($this:ident . $i:ident as $alias:ident) => {
let $alias = {
use std::borrow::Borrow;
$this.$i.borrow()
};
};
($this:ident . $i:ident as $alias:ident : $borrow:ty) => {
let $alias: $borrow = {
use std::borrow::Borrow;
$this.$i.borrow()
};
};
(mut $this:ident . $i:ident as $alias:ident : $borrow:ty) => {
let mut $alias: $borrow = {
use std::borrow::Borrow;
$this.$i.borrow()
};
};
(mut $this:ident . $i:ident as $alias:ident) => {
let mut $alias = {
use std::borrow::Borrow;
$this.$i.borrow()
};
};
($this:ident . $i:ident as $alias:ident : $borrow:ty, $($tt:tt)*) => {
borrowed!($this . $i as $alias: $borrow);
borrowed!($($tt)*);
};
($this:ident . $i:ident as $alias:ident, $($tt:tt)*) => {
borrowed!($this . $i as $alias);
borrowed!($($tt)*);
};
(mut $this:ident . $i:ident as $alias:ident : $borrow:ty, $($tt:tt)*) => {
borrowed!(mut $this . $i as $alias: $borrow);
borrowed!($($tt)*);
};
(mut $this:ident . $i:ident as $alias:ident, $($tt:tt)*) => {
borrowed!(mut $this . $i as $alias);
borrowed!($($tt)*);
};
($i:ident : $borrow:ty) => {
borrowed!($i as $i: $borrow)
};
($i:ident) => {
borrowed!($i as $i)
};
(mut $i:ident : $borrow:ty) => {
borrowed!(mut $i as $i: $borrow)
};
(mut $i:ident) => {
borrowed!(mut $i as $i)
};
($i:ident : $borrow:ty, $($tt:tt)*) => {
borrowed!($i as $i: $borrow);
borrowed!($($tt)*);
};
($i:ident, $($tt:tt)*) => {
borrowed!($i as $i);
borrowed!($($tt)*);
};
(mut $i:ident, $($tt:tt)*) => {
borrowed!(mut $i);
borrowed!($($tt)*);
};
($this:ident . $i:ident : $borrow:ty) => {
borrowed!($this.$i as $i: $borrow)
};
($this:ident . $i:ident) => {
borrowed!($this.$i as $i)
};
(mut $this:ident . $i:ident : $borrow:ty) => {
let mut $i: $borrow = {
use std::borrow::Borrow;
$this.$i.borrow()
};
};
(mut $this:ident . $i:ident) => {
let mut $i = {
use std::borrow::Borrow;
$this.$i.borrow()
};
};
($this:ident . $i:ident : $borrow:ty, $($tt:tt)*) => {
borrowed!($this . $i as $i: $borrow);
borrowed!($($tt)*);
};
($this:ident . $i:ident, $($tt:tt)*) => {
borrowed!($this . $i as $i);
borrowed!($($tt)*);
};
(mut $this:ident . $i:ident : $borrow:ty, $($tt:tt)*) => {
borrowed!(mut $this . $i: $borrow);
borrowed!($($tt)*);
};
(mut $this:ident . $i:ident, $($tt:tt)*) => {
borrowed!(mut $this . $i);
borrowed!($($tt)*);
};
// Handle trailing ','
() => {};
}
#[cfg(test)]
mod tests {
struct A {
x: String,
}
impl A {
#[allow(clippy::let_and_return)]
fn foo(&self) -> &str {
borrowed!(self.x);
x
}
}
#[test]
fn test() {
let a = A {
x: "I am a struct".into(),
};
let y: String = "that can".into();
let z: String = "talk a lot".into();
{
borrowed!(a.x: &str, y: &str, mut z: &str);
let _ = a.foo();
assert_eq!(&format!("{x} {y} {z}"), "I am a struct that can talk a lot");
z = "";
assert_eq!(z, "");
}
}
#[test]
#[allow(unused_variables, unused_assignments)]
fn test_mut() {
let a = 1;
let b = 2;
let c = A {
x: "foo".to_string(),
};
{
borrowed!(mut a);
a = &1;
}
{
borrowed!(mut a, b);
a = &1;
}
{
borrowed!(a, mut b);
b = &1;
}
{
borrowed!(mut c.x: &str);
x = "bar";
}
{
borrowed!(c.x: &str, mut a);
a = &1
}
{
borrowed!(a, mut c.x: &str);
x = "bar";
}
}
#[test]
fn trailing_comma() {
let a = 1;
let b = 2;
borrowed!(a, b,);
assert_eq!((*a, *b), (1, 2))
}
#[test]
fn trailing_comma_mut() {
let a = 1;
let b = 2;
borrowed!(a, mut b,);
assert_eq!(b, &2);
b = &3;
assert_eq!((a, b), (&1, &3))
}
#[test]
#[allow(unused_variables, unused_mut)]
fn aliases() {
let mut a = 1;
let mut c = A {
x: "foo".to_string(),
};
{
borrowed!(a as a2);
borrowed!(a as a2,);
}
{
borrowed!(mut a as a2);
borrowed!(mut a as a2,);
}
{
borrowed!(c.x as x2: &str);
borrowed!(c.x as x2: &str,);
}
{
borrowed!(mut c.x as x2:&str);
borrowed!(mut c.x as x2:&str,);
}
{
borrowed!(a, a as a2);
borrowed!(a, a as a2,);
}
{
borrowed!(a, mut a as a2);
borrowed!(a, mut a as a2,);
}
{
borrowed!(a, c.x as x2: &str);
borrowed!(a, c.x as x2: &str,);
}
{
borrowed!(a, mut c.x as x2: &String);
borrowed!(a, mut c.x as x2: &String,);
}
}
}
| true |
ba19a4ba5a48ec94fd7e341fcac94ee81c0577e0
|
Rust
|
adamnemecek/asprite
|
/src/ui/context.rs
|
UTF-8
| 6,745 | 2.875 | 3 |
[] |
no_license
|
use super::*;
use math::*;
use std::rc::Rc;
pub struct ContextBuilder<'a, 'b, D: ?Sized + Graphics + 'a>
where 'a: 'b
{
root: &'b Context<'a, D>,
rect: Rect<f32>,
range: Option<usize>,
}
impl<'a, 'b, D: ?Sized + Graphics + 'a> ContextBuilder<'a, 'b, D> {
fn new(root: &'b Context<'a, D>) -> Self {
Self {
root,
rect: root.rect,
range: None,
}
}
pub fn with_rect(mut self, rect: Rect<f32>) -> Self {
self.rect = rect;
self
}
pub fn align(mut self, align: Vector2<f32>, size: Vector2<f32>) -> Self {
let rect = self.root.rect;
let p = rect_align(rect, align, size);
self.rect = Rect::from_min_dim(p, size);
self
}
pub fn align_x(self, align: f32, size: f32) -> Self {
let mut dim = self.root.rect.dim();
dim.x = size;
let align = Vector2::new(align, 0.0);
self.align(align, dim)
}
pub fn align_y(self, align: f32, size: f32) -> Self {
let mut dim = self.root.rect.dim();
dim.y = size;
let align = Vector2::new(0.0, align);
self.align(align, dim)
}
pub fn transform(mut self, anchor: Rect<f32>, offset: Rect<f32>) -> Self {
let rect = self.root.rect;
self.rect = rect_transform(rect, anchor, offset);
self
}
pub fn with_range(mut self, count: usize) -> Self {
self.range = Some(count);
self
}
pub fn build(self) -> Context<'a, D> {
let Self { root, rect, range } = self;
let generator = range
.and_then(|range| root.generator.range(range))
.map(|gen| Rc::new(gen))
.unwrap_or_else(|| root.generator.clone());
Context { generator, rect, .. *root }
}
}
pub struct Context<'a, D: ?Sized + Graphics + 'a> {
draw: &'a D,
generator: Rc<Generator>,
rect: Rect<f32>,
mouse: Mouse,
}
impl<'a, D: ?Sized + Graphics + 'a> Clone for Context<'a, D> {
fn clone(&self) -> Self {
ContextBuilder::new(self).build()
}
}
impl<'a, D: ?Sized + Graphics + 'a> Context<'a, D> {
pub fn new(draw: &'a D, rect: Rect<f32>, mouse: Mouse) -> Self {
Self {
rect,
draw,
mouse,
generator: Rc::new(Generator::new()),
}
}
pub fn in_range(&self, id: Id) -> bool {
self.generator.in_range(id)
}
pub fn sub<'b>(&'b self) -> ContextBuilder<'a, 'b, D> {
ContextBuilder::new(self)
}
pub fn sub_range(&self, range: usize) -> Self {
self.sub().with_range(range).build()
}
pub fn align(&self, align: Vector2<f32>, size: Vector2<f32>) -> Self {
self.sub().align(align, size).build()
}
pub fn align_x(&self, align: f32, size: f32) -> Self {
self.sub().align_x(align, size).build()
}
pub fn align_y(&self, align: f32, size: f32) -> Self {
self.sub().align_y(align, size).build()
}
pub fn transform(&self, anchor: Rect<f32>, offset: Rect<f32>) -> Self {
self.sub().transform(anchor, offset).build()
}
pub fn sub_rect(&self, rect: Rect<f32>) -> Self {
Self {
rect,
generator: self.generator.clone(),
.. *self
}
}
pub fn split_x(&self, x: f32) -> (Self, Self) {
let (a, b) = self.rect.split_x(x);
let a = self.sub_rect(a);
let b = self.sub_rect(b);
(a, b)
}
pub fn split_y(&self, y: f32) -> (Self, Self) {
let (a, b) = self.rect.split_y(y);
let a = self.sub_rect(a);
let b = self.sub_rect(b);
(a, b)
}
pub fn horizontal_flow(&self, x: f32, y: f32, widgets: &'a [Flow]) -> impl Iterator<Item=Context<'a, D>> {
self.layout(Axis::Horizontal, x, y, widgets)
}
pub fn vertical_flow(&self, x: f32, y: f32, widgets: &'a [Flow]) -> impl Iterator<Item=Context<'a, D>> {
self.layout(Axis::Vertical, x, y, widgets)
}
pub fn label(&self, x: f32, y: f32, color: D::Color, text: &str) {
self.label_rect(self.rect(), Vector2::new(x, y), color, text);
}
pub fn label_rect(&self, rect: Rect<f32>, align: Vector2<f32>, color: D::Color, text: &str) {
let size = self.draw.measure_text(&text);
let p = rect_align(rect, align, size);
self.draw.text(p, color, &text);
}
fn layout(&self, axis: Axis, x: f32, y: f32, widgets: &'a [Flow]) -> impl Iterator<Item=Context<'a, D>> + 'a {
let size = measure(axis, widgets);
//let offset = ctx.rect().min.to_vec();
let offset = rect_align(self.rect(), Vector2::new(x, y), size);
let offset = Vector2::new(offset.x, offset.y);
let draw = self.draw;
let generator = self.generator.clone();
let size = Vector2::new(self.rect().dx(), self.rect().dy());
let mouse = self.mouse;
layout(axis, size, widgets)
.map(move |rect| rect.shift_xy(offset))
.map(move |rect| Self {
rect,
draw,
generator: generator.clone(),
mouse,
})
}
pub fn draw(&self) -> &'a D {
self.draw
}
pub fn reserve_widget_id(&self) -> Id {
self.generator.next().unwrap()
}
pub fn is_cursor_hovering(&self) -> bool {
self.is_cursor_in_rect(self.rect)
}
}
impl<'a, D: ?Sized + Graphics + 'a> Events for Context<'a, D> {
fn rect(&self) -> Rect<f32> {
self.rect
}
fn cursor(&self) -> Point2<f32> { self.mouse.cursor }
fn was_pressed(&self) -> bool { self.mouse.pressed }
fn was_released(&self) -> bool { self.mouse.released }
}
impl<'a, D: ?Sized + Graphics + 'a> Graphics for Context<'a, D> {
type Texture = D::Texture;
type Color = D::Color;
fn texture_dimensions(&self, texture: Self::Texture) -> Vector2<f32> {
self.draw.texture_dimensions(texture)
}
fn quad(&self, color: Self::Color, rect: Rect<f32>) {
self.draw.quad(color, rect)
}
fn texture(&self, texture: Self::Texture, rect: Rect<f32>) {
self.draw.texture(texture, rect)
}
fn texture_frame(&self, texture: Self::Texture, rect: Rect<f32>, frame: Rect<f32>) {
self.draw.texture_frame(texture, rect, frame)
}
fn measure_text(&self, text: &str) -> Vector2<f32> {
self.draw.measure_text(text)
}
fn text(&self, base: Point2<f32>, color: Self::Color, text: &str) {
self.draw.text(base, color, text)
}
fn set_hovered(&self) {
self.draw.set_hovered()
}
fn clip(&self, r: Rect<i16>) {
self.draw.clip(r)
}
fn unclip(&self) {
self.draw.unclip()
}
}
| true |
dd81f58f4becc3dcc2347e1f185f988959664198
|
Rust
|
caiqingfeng/rustguru
|
/prime-rust/src/cardhelper.rs
|
UTF-8
| 3,133 | 2.875 | 3 |
[] |
no_license
|
use crate::scoremap::primes; //for rust 2018 https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-clarity.html
use std::collections::HashMap;
#[derive(Debug, PartialEq)]
pub enum LYSuit {
Nosuit = 0, Clubs = 1, Diamonds = 2, Hearts = 3, Spades = 4
}
// impl PartialEq for LYSuit {
// fn eq(&self, other: &LYSuit) -> bool {
// self == other
// }
// }
enum LYFace {
NOFACE = 0,
ACE = 14,
TWO = 2,
THREE = 3,
FOUR = 4,
FIVE = 5,
SIX = 6,
SEVEN = 7,
EIGHT = 8,
NINE = 9,
TEN = 10,
JACK = 11,
QUEEN = 12,
KING = 13,
SMALL_GHOST = 24,
BIG_GHOST = 25
}
lazy_static! {
static ref PrimesMap: HashMap<char, u64> = {
let mut m = HashMap::new();
m.insert('X', 43);
m.insert('A', 41);
m.insert('K', 37);
m.insert('Q', 31);
m.insert('J', 29);
m.insert('T', 23);
m.insert('9', 19);
m.insert('8', 17);
m.insert('7', 13);
m.insert('6', 11);
m.insert('5', 7);
m.insert('4', 5);
m.insert('3', 3);
m.insert('2', 2);
m
};
}
pub fn scan_hand_string(cs: &String, key: &mut u64, suitKey: &mut u64, suit: &mut LYSuit) ->u64 {
let l = cs.len();
*key = 1u64;
*suitKey = 1u64;
let mut hasGhost = false;
let mut clubKey = 1u64;
let mut club = 0u64;
let mut diamondKey = 1u64;
let mut diamond = 0u64;
let mut heartKey = 1u64;
let mut heart = 0u64;
let mut spadeKey = 1u64;
let mut spade = 0u64;
for i in 0..l/2 {
let mut p = PrimesMap[&(cs.as_bytes()[2*i] as char)];
*key *= p;
match cs.as_bytes()[2*i+1] as char {
'c' => {
clubKey *= p;
club += 1;
},
'd' => {
diamondKey *= p;
diamond += 1;
},
'h' => {
heartKey *= p;
heart += 1;
},
's' => {
spadeKey *= p;
spade += 1;
},
_ => {
hasGhost = true;
club += 1;
diamond += 1;
heart += 1;
spade += 1;
},
}
}
if club >= 5 {
*suit = LYSuit::Clubs;
*suitKey = clubKey;
if hasGhost {
*suitKey *= 43u64;
}
} else if diamond >= 5 {
*suit = LYSuit::Diamonds;
*suitKey = diamondKey;
if hasGhost {
*suitKey *= 43u64;
}
} else if heart >= 5 {
*suit = LYSuit::Hearts;
*suitKey = heartKey;
if hasGhost {
*suitKey *= 43u64;
}
} else if spade >= 5 {
*suit = LYSuit::Spades;
*suitKey = spadeKey;
if hasGhost {
*suitKey *= 43u64;
}
}
key.clone()
}
#[cfg(test)]
mod tests {
#[test]
fn scan_hand_string() {
let mut key=0u64;
let mut suitKey=0u64;
let mut suit = super::LYSuit::Clubs;
let _ = super::scan_hand_string(&String::from("AsXnQsJs9s"), &mut key, &mut suitKey, &mut suit);
assert_eq!(suit, super::LYSuit::Spades);
assert_eq!(suitKey, 41u64*43u64*31u64*29u64*19u64);
let _ = super::scan_hand_string(&String::from("5c2d5dXnKd7d6d"), &mut key, &mut suitKey, &mut suit);
assert_eq!(suit, super::LYSuit::Diamonds);
assert_eq!(suitKey, 43u64*37u64*13u64*11u64*7u64*2u64);
}
}
| true |
6b2b28ce839e363df42e2f4ac8ce07a5ea3d04e5
|
Rust
|
Walters-Kuo/book-tw
|
/listings/ch08-common-collections/listing-08-04/src/main.rs
|
UTF-8
| 179 | 2.9375 | 3 |
[
"Apache-2.0",
"BSD-3-Clause",
"NCSA",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MIT",
"Unlicense",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
fn main() {
// ANCHOR: here
{
let v = vec![1, 2, 3, 4];
// 使用 v 做些事情
} // <- v 在此離開作用域並釋放
// ANCHOR_END: here
}
| true |
0955e8d5acf7c6031a67bdaa6c6a03b8a6deccdb
|
Rust
|
maarten-vos/bungie-rs
|
/src/destiny2/mod.rs
|
UTF-8
| 2,641 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
use BungieClient;
use self::models::*;
use std::fmt::Write;
pub mod models;
fn push_components(
out: &mut String,
mut components: Vec<DestinyComponentType>,
default_component: DestinyComponentType
) {
if components.is_empty() {
components.push(default_component);
}
for item in &components {
write!(out, "{},", *item as i64).unwrap();
}
out.pop();
}
pub struct Destiny2<'a> {
pub bungie: &'a BungieClient
}
impl<'a> Destiny2<'a> {
pub fn get_destiny_manifest(&self) -> Result<Response<DestinyManifest>, ::failure::Error> {
self.bungie.send_request("/Destiny2/Manifest", None)
}
pub fn search_destiny_player(&self, membership_type: MembershipType, name: &str) -> Result<Response<Vec<UserInfoCard>>, ::failure::Error> {
let path = &format!("/Destiny2/SearchDestinyPlayer/{}/{}", membership_type as i64, name);
self.bungie.send_request(path, None)
}
pub fn equip_item(&self, destiny_item_action_request: DestinyItemActionRequest) -> Result<Response<i32>, ::failure::Error> {
self.bungie.send_request("/Destiny2/Actions/Items/EquipItem", Some(::serde_json::to_string(&destiny_item_action_request)?))
}
pub fn get_character(&self, membership_type: MembershipType, destiny_membership_id: &str, character_id: i64, components: Vec<DestinyComponentType>) -> Result<Response<DestinyCharacterResponse>, ::failure::Error> {
let mut path = format!("/Destiny2/{}/Profile/{}/Character/{}?components=", membership_type as i64, destiny_membership_id, character_id);
push_components(&mut path, components, DestinyComponentType::Profiles);
self.bungie.send_request(&path, None)
}
pub fn get_item(&self, membership_type: MembershipType, destiny_membership_id: &str, item_instance_id: i64, components: Vec<DestinyComponentType>) -> Result<Response<DestinyItemResponse>, ::failure::Error> {
let mut path = format!("/Destiny2/{}/Profile/{}/Item/{}?components=", membership_type as i64, destiny_membership_id, item_instance_id);
push_components(&mut path, components, DestinyComponentType::None);
self.bungie.send_request(&path, None)
}
pub fn get_profile(&self, membership_type: MembershipType, destiny_membership_id: &str, components: Vec<DestinyComponentType>) -> Result<Response<DestinyProfileResponse>, ::failure::Error> {
let mut path = format!("/Destiny2/{}/Profile/{}?components=", membership_type as i64, destiny_membership_id);
push_components(&mut path, components, DestinyComponentType::Profiles);
self.bungie.send_request(&path, None)
}
}
| true |
8c85a91b1acab4544e5a7e85677e94da82940c13
|
Rust
|
nicholasyager/advent-of-code-2017
|
/day_12/src/main.rs
|
UTF-8
| 3,236 | 3.453125 | 3 |
[] |
no_license
|
use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
use std::collections::HashSet;
use std::collections::HashMap;
fn find_graph_groups(graph: HashMap<u32, Vec<u32>>) -> Vec<HashSet<u32>> {
let mut groups: Vec<HashSet<u32 >> = Vec::new();
let mut indices: Vec<u32> = Vec::new();
for index in graph.keys() {
indices.push(*index);
}
for index in indices {
// Check if the index belongs in a group. If not, process it.
let mut skip = false;
for group in groups.clone() {
if group.contains(&index) {
skip = true;
break;
}
}
if skip {
continue;
}
let mut stack: HashSet<u32> = HashSet::new();
stack.insert(index);
let group = traverse_graph(index, &graph, stack);
groups.push(group);
}
groups
}
fn traverse_graph(index: u32, graph: &HashMap<u32, Vec<u32>>, stack: HashSet<u32>) -> HashSet<u32> {
let mut new_stack = stack.clone();
for child in graph.get(&index).unwrap() {
if !new_stack.contains(&child.clone()) {
new_stack.insert(*child);
let output = traverse_graph(*child, graph, new_stack.clone());
for value in output {
new_stack.insert(value);
}
}
}
new_stack
}
fn main() {
let args: Vec<String> = env::args().collect();
let filename: String = match args.get(1) {
None => panic!("You must supply a file to evaluate."),
Some(filename) => filename.clone()
};
println!("Processing file {:?}", filename);
let f = File::open(filename).expect("file not found");
let file = BufReader::new(&f);
let mut edges: HashSet<(u32, u32)> = HashSet::new();
for wrapped_line in file.lines() {
let line = wrapped_line.unwrap();
let line_parts = line.split_whitespace().collect::<Vec<&str>>();
let parent: u32 = line_parts[0].to_string().parse().unwrap();
let mut children: Vec<String> = Vec::new();
for part in &line_parts[2..] {
let node: u32 = part.to_string().replace(",", "").parse().unwrap();
let edge: (u32, u32);
edge = (parent, node);
edges.insert(edge);
}
}
let mut edge_map: HashMap<u32, Vec<u32>> = HashMap::new();
for edge in &edges {
// Check if the map is already present. If so, add the target to the
// id list.
if edge_map.contains_key(&edge.0) {
let mut new_edge: Vec<u32> = edge_map.get(&edge.0).unwrap().clone();
new_edge.push(edge.1);
edge_map.insert(edge.0, new_edge);
} else {
let mut edge_list: Vec<u32> = Vec::new();
edge_list.push(edge.1);
edge_map.insert(edge.0, edge_list);
}
}
println!("{:?}", edge_map);
let mut stack: HashSet<u32> = HashSet::new();
stack.insert(0_u32);
let set = traverse_graph(0, &edge_map, stack);
println!("Group 0 has {:?} elements.", set.len());
let groups = find_graph_groups(edge_map);
println!("There are {:?} groups in the graph.", groups.len());
}
| true |
b385993898ced2f79d14181c46f110a30f64b547
|
Rust
|
spebern/custom_error
|
/src/lib.rs
|
UTF-8
| 22,852 | 3.765625 | 4 |
[
"BSD-2-Clause"
] |
permissive
|
/// Constructs a custom error type.
///
/// # Examples
///
/// ### Simple error
///
/// For an error with multiple cases you can generate an enum:
/// ```
/// use custom_error::custom_error;
///
/// custom_error!{ pub MyError
/// Bad = "Something bad happened",
/// Terrible = "This is a very serious error!!!"
/// }
/// assert_eq!("Something bad happened", MyError::Bad.to_string());
/// assert_eq!("This is a very serious error!!!", MyError::Terrible.to_string());
/// ```
///
/// For an error with a single case you can generate a struct:
/// ```
/// use custom_error::custom_error;
///
/// custom_error!{ pub MyError{} = "Something bad happened" }
/// assert_eq!("Something bad happened", MyError{}.to_string());
/// ```
///
/// ### Custom error with parameters
/// ```
/// use custom_error::custom_error;
///
/// custom_error!{SantaError
/// BadChild{name:String, foolishness:u8} = "{name} has been bad {foolishness} times this year",
/// TooFar = "The location you indicated is too far from the north pole",
/// InvalidReindeer{legs:u8} = "The reindeer has {legs} legs"
/// }
///
/// assert_eq!(
/// "Thomas has been bad 108 times this year",
/// SantaError::BadChild{
/// name: "Thomas".into(),
/// foolishness: 108
/// }.to_string());
///
/// assert_eq!(
/// "The location you indicated is too far from the north pole",
/// SantaError::TooFar.to_string()
/// );
///
/// assert_eq!(
/// "The reindeer has 8 legs",
/// SantaError::InvalidReindeer{legs:8}.to_string()
/// );
/// ```
///
/// ### Automatic conversion from other error types
///
/// You can add a special field named `source` to your error types.
///
/// Use this field to include the lower-level source of the error.
/// It will be used in the error
/// [`source()`](https://doc.rust-lang.org/std/error/trait.Error.html#method.source)
/// method, and automatic conversion from the source error type to your custom error type will be possible
/// (your error type will implement `From<SourceErrorType>`).
///
/// #### limitations
/// * You cannot have several error cases that contain a single *source* field of the same type:
/// `custom_error!(E A{source:X} B{source:Y})` is allowed, but
/// `custom_error!(E A{source:X} B{source:X})` is forbidden.
/// * If the source field is not the only one, then the automatic conversion
/// will not be implemented.
///
/// ```
/// use custom_error::custom_error;
/// use std::{io, io::Read, fs::File, result::Result};
///
/// custom_error!{MyError
/// IO{source: io::Error} = "input/output error",
/// Unknown = "unknown error"
/// }
///
/// fn read_file(filename: &str) -> Result<String, MyError> {
/// let mut res = String::new();
/// File::open(filename)?.read_to_string(&mut res)?;
/// Ok(res)
/// }
///
/// assert_eq!(
/// "input/output error",
/// read_file("/i'm not a file/").unwrap_err().to_string()
/// )
/// ```
///
/// ### Custom formatting function for error messages
///
/// If the format string syntax is not enough to express your complex error formatting needs,
/// you can use custom code to generate your error description.
///
/// ```
/// use custom_error::custom_error;
///
/// static lang : &'static str = "FR";
///
/// # fn localize(_:&str, _:&str) -> &'static str { "Un problème est survenu" }
///
/// custom_error!{ pub MyError
/// Problem = @{ localize(lang, "A problem occurred") },
/// }
///
/// assert_eq!("Un problème est survenu", MyError::Problem.to_string());
/// ```
///
/// ```
/// use custom_error::custom_error;
/// use std::io::Error;
/// use std::io::ErrorKind::*;
///
/// custom_error!{ pub MyError
/// Io{source: Error} = @{
/// match source.kind() {
/// NotFound => "The file does not exist",
/// TimedOut => "The operation timed out",
/// _ => "unknown error",
/// }
/// },
/// }
///
/// assert_eq!("The operation timed out", MyError::Io{source: TimedOut.into()}.to_string());
/// ```
#[macro_export]
macro_rules! custom_error {
(pub $($tt:tt)*) => { $crate::custom_error!{ (pub) $($tt)* } };
(
$( ($prefix:tt) )* // `pub` marker
$errtype:ident // Name of the error type to generate
$( < $(
$type_param:tt // Optional type parameters for generic error types
),*
> )*
$(
$field:ident // Name of an error variant
$( { $(
$attr_name:ident // Name of an attribute of the error variant
:
$($attr_type:ident)::* // type of the attribute
$(< $($attr_type_param:tt),* >)* // Generic (lifetime & type) parameters for the attribute's type
),* } )*
=
$( @{ $($msg_fun:tt)* } )*
$($msg:expr)* // The human-readable error message
),*
$(,)* // Trailing comma
) => {
#[derive(Debug)]
$($prefix)* enum $errtype $( < $($type_param),* > )* {
$(
$field
$( { $( $attr_name : $($attr_type)::* $(< $($attr_type_param),* >)* ),* } )*
),*
}
$crate::add_type_bounds! {
( $($($type_param),*)* )
(std::fmt::Debug + std::fmt::Display)
{ impl <} {> std::error::Error
for $errtype $( < $($type_param),* > )*
{
fn source(&self) -> Option<&(dyn std::error::Error + 'static)>
{
#[allow(unused_variables, unreachable_code)]
match self {$(
$errtype::$field $( { $( $attr_name ),* } )* => {
$( $(
$crate::return_if_source!($attr_name, $attr_name $(<$($attr_type_param),*>)* )
);* )*;
None
}
),*}
}
}
}}
$crate::impl_error_conversion!{
( $errtype $(< $($type_param),* >)* )
$([
$field,
$($(
$attr_name,
$attr_name,
$($attr_type)::* $(< $($attr_type_param),* >)*
),*),*
])*
}
$crate::add_type_bounds! {
( $($($type_param),*)* )
(std::string::ToString)
{ impl <} {> std::fmt::Display
for $errtype $( < $($type_param),* > )*
{
fn fmt(&self, formatter: &mut std::fmt::Formatter)
-> std::fmt::Result
{
match self {$(
$errtype::$field $( { $( $attr_name ),* } )* => {
$(write!(formatter, "{}", ($($msg_fun)*) )?;)*
$crate::display_message!(formatter, $($($attr_name),*),* | $($msg)*);
Ok(())
}
),*}
}
}
}}
};
(
$( ($prefix:tt) )* // `pub` marker
$errtype:ident // Name of the error type to generate
$( < $(
$type_param:tt // Optional type parameters for generic error types
),*
> )*
{ $(
$field_name:ident // Name of an attribute of the error variant
:
$($field_type:ident)::* // type of the attribute
$(< $($field_type_param:tt),* >)* // Generic (lifetime & type) parameters for the attribute's type
),* }
=
$( @{ $($msg_fun:tt)* } )*
$($msg:expr)* // The human-readable error message
$(,)* // Trailing comma
) => {
#[derive(Debug)]
$($prefix)* struct $errtype $( < $($type_param),* > )* {
$( $field_name : $($field_type)::* $(< $($field_type_param),* >)* ),*
}
$crate::add_type_bounds! {
( $($($type_param),*)* )
(std::fmt::Debug + std::fmt::Display)
{ impl <} {> std::error::Error
for $errtype $( < $($type_param),* > )*
{
#[allow(unused_variables, unreachable_code)]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)>
{
$(
$crate::return_if_source!(self, $field_name, $field_name $(<$($field_type_param),*>)* );
);*
None
}
}
}}
$crate::impl_error_conversion_for_struct!{
$errtype $(< $($type_param),* >)*,
$( $field_name: $($field_type)::* $(< $($field_type_param),* >)* ),*
}
$crate::add_type_bounds! {
( $($($type_param),*)* )
(std::string::ToString)
{ impl <} {> std::fmt::Display
for $errtype $( < $($type_param),* > )*
{
fn fmt(&self, formatter: &mut std::fmt::Formatter)
-> std::fmt::Result
{
// make fields accessible with variables, so that we can
// use them in custom error msg blocks without self
$(
let $field_name = &self.$field_name;
);*
$(write!(formatter, "{}", ($($msg_fun)*) )?;)*
$crate::display_message!(formatter, $($field_name),* | $($msg)*);
Ok(())
}
}
}}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! return_if_source {
// Return the source if the attribute is called 'source'
(source, $attr_name:ident) => { {return Some($attr_name)} };
($self:ident, source, $attr_name:ident) => { {return Some(&$self.$attr_name)} };
// If the attribute has a different name or has type parameters, return nothing
($_attr_name:ident, $_repeat:ident $(<$($_type:tt),*>)* ) => { };
($self:ident, $_attr_name:ident, $_repeat:ident $(<$($_type:tt),*>)* ) => { };
}
#[doc(hidden)]
#[macro_export]
macro_rules! impl_error_conversion {
( ( $($prefix:tt)* ) [ $($field_data:tt)* ] $($rest:tt)* ) => {
$crate::impl_error_conversion!{$($prefix)*, $($field_data)*}
$crate::impl_error_conversion!{ ($($prefix)*) $($rest)*}
};
( ( $($prefix:tt)* ) ) => {};
// implement From<Source> only when there is a single attribute and it is named 'source'
(
$errtype:ident $( < $($type_param:tt),* > )*,
$field:ident,
source,
$source:ident,
$($source_type:ident)::* $( < $($source_type_param:tt),* > )*
) => {
impl $( < $($type_param),* > )*
From<$($source_type)::* $( < $($source_type_param),* > )*>
for $errtype $( < $($type_param),* > )* {
fn from(source: $($source_type)::* $( < $($source_type_param),* > )*) -> Self {
$errtype::$field { source }
}
}
};
(
$_errtype:ident $( < $($_errtype_type_param:tt),* > )*,
$_field:ident,
$(
$_:ident,
$_repeated:ident,
$($_type:ident)::* $( < $($_type_param:tt),* > )*
),*
) => {}; // If the list of fields is not a single field named 'source', do nothing
}
#[doc(hidden)]
#[macro_export]
macro_rules! impl_error_conversion_for_struct {
( ( $($prefix:tt)* ) ) => {};
// implement From<Source> only when there is a single field and it is named 'source'
(
$errtype:ident $( < $($type_param:tt),* > )*,
source: $($source_type:ident)::* $( < $($source_type_param:tt),* > )*
) => {
impl $( < $($type_param),* > )*
From<$($source_type)::* $( < $($source_type_param),* > )*>
for $errtype $( < $($type_param),* > )* {
fn from(source: $($source_type)::* $( < $($source_type_param),* > )*) -> Self {
$errtype { source }
}
}
};
(
$_errtype:ident $( < $($_errtype_type_param:tt),* > )*,
$( $_field:ident: $($_type:ident)::* $( < $($_type_param:tt),* > )* ),*
) => {}; // If the list of fields is not a single field named 'source', do nothing
}
#[doc(hidden)]
#[macro_export]
macro_rules! display_message {
($formatter:expr, $($attr:ident),* | $msg:expr) => {
write!(
$formatter,
concat!($msg $(, "{", stringify!($attr), ":.0}" )*)
$( , $attr = $attr.to_string() )*
)?;
};
($formatter:expr, $($attr:ident),* | ) => {};
}
/* This macro, given a list of generic parameters and type
bounds, adds the type bounds to all generic type parameters
(and leaves the generic lifetime parameters unchanged) */
#[doc(hidden)]
#[macro_export]
macro_rules! add_type_bounds {
(
( $typ:ident $(, $rest:tt)* ) // type parameter
( $($bounds:tt)* )
{ $($prefix:tt)* }
{ $($suffix:tt)* }
) => {
add_type_bounds!{
( $(, $rest)* )
( $($bounds)* )
{ $($prefix)* $typ : $($bounds)*}
{ $($suffix)* }
}
};
(
( $lifetime:tt $(, $rest:tt)* ) // lifetime parameter
( $($bounds:tt)* )
{ $($prefix:tt)* }
{ $($suffix:tt)* }
) => {
add_type_bounds!{
( $(, $rest)* )
( $($bounds)* )
{ $($prefix)* $lifetime }
{ $($suffix)* }
}
};
(
( , $($rest:tt)* ) // add the comma to the prefix
( $($bounds:tt)* )
{ $($prefix:tt)* }
{ $($suffix:tt)* }
) => {
add_type_bounds!{
( $($rest)* )
( $($bounds)* )
{ $($prefix)* , }
{ $($suffix)* }
}
};
(
( ) // no more generic params to consume
( $($bounds:tt)* )
{ $($prefix:tt)* }
{ $($suffix:tt)* }
) => {
$($prefix)* $($suffix)*
}
}
#[cfg(test)]
mod tests {
#[test]
fn single_error_case() {
custom_error!(MyError Bad="bad");
assert_eq!("bad", MyError::Bad.to_string());
}
#[test]
fn single_error_struct_case() {
custom_error!(MyError{} ="bad");
assert_eq!("bad", MyError{}.to_string());
}
#[test]
#[allow(dead_code)]
fn three_error_cases() {
custom_error!(MyError NotPerfect=":/", Bad="bad", Awfull="arghhh");
assert_eq!("arghhh", MyError::Awfull.to_string())
}
#[test]
fn with_error_data() {
custom_error!(MyError
Bad = "bad",
Catastrophic{broken_things:u8} = "{broken_things} things are broken"
);
assert_eq!("bad", MyError::Bad.to_string());
assert_eq!(
"9 things are broken",
MyError::Catastrophic { broken_things: 9 }.to_string()
);
}
#[test]
fn struct_with_error_data() {
custom_error!(MyError{broken_things:u8} = "{broken_things} things are broken");
assert_eq!("9 things are broken", MyError{ broken_things: 9 }.to_string());
}
#[test]
fn with_multiple_error_data() {
custom_error!(E X{a:u8, b:u8, c:u8} = "{c} {b} {a}");
assert_eq!("3 2 1", E::X { a: 1, b: 2, c: 3 }.to_string());
}
#[test]
fn struct_with_multiple_error_data() {
custom_error!(E{a:u8, b:u8, c:u8} = "{c} {b} {a}");
assert_eq!("3 2 1", E{ a: 1, b: 2, c: 3 }.to_string());
}
#[test]
fn source() {
use std::{io, error::Error};
custom_error!(E A{source: io::Error}="");
let source: io::Error = io::ErrorKind::InvalidData.into();
assert_eq!(
source.to_string(),
E::A { source }.source().unwrap().to_string()
);
}
#[test]
fn struct_source() {
use std::{io, error::Error};
custom_error!(E{source: io::Error}="");
let source: io::Error = io::ErrorKind::InvalidData.into();
assert_eq!(
source.to_string(),
E{ source }.source().unwrap().to_string()
);
}
#[test]
fn from_source() {
use std::io;
custom_error!(E A{source: io::Error}="bella vita");
let source = io::Error::from(io::ErrorKind::InvalidData);
assert_eq!("bella vita", E::from(source).to_string());
}
#[test]
fn struct_from_source() {
use std::io;
custom_error!(E{source: io::Error}="bella vita");
let source = io::Error::from(io::ErrorKind::InvalidData);
assert_eq!("bella vita", E::from(source).to_string());
}
#[test]
#[allow(dead_code)]
fn with_source_and_others() {
use std::{io, error::Error};
custom_error!(MyError Zero="", One{x:u8}="", Two{x:u8, source:io::Error}="{x}");
fn source() -> io::Error { io::ErrorKind::AlreadyExists.into() };
let my_err = MyError::Two { x: 42, source: source() };
assert_eq!("42", my_err.to_string());
assert_eq!(source().to_string(), my_err.source().unwrap().to_string());
}
#[test]
#[allow(dead_code)]
fn struct_with_source_and_others() {
use std::{io, error::Error};
custom_error!(MyError{x:u8, source:io::Error}="{x}");
fn source() -> io::Error { io::ErrorKind::AlreadyExists.into() };
let my_err = MyError{ x: 42, source: source() };
assert_eq!("42", my_err.to_string());
assert_eq!(source().to_string(), my_err.source().unwrap().to_string());
}
#[test]
fn pub_error() {
mod my_mod {
custom_error! {pub MyError Case1="case1"}
}
assert_eq!("case1", my_mod::MyError::Case1.to_string());
}
#[test]
fn pub_error_struct() {
mod my_mod {
custom_error! {pub MyError{} = "case1"}
}
assert_eq!("case1", my_mod::MyError{}.to_string());
}
#[test]
fn generic_error() {
custom_error! {MyError<X,Y> E1{x:X,y:Y}="x={x} y={y}", E2="e2"}
assert_eq!("x=42 y=42", MyError::E1 { x: 42u8, y: 42u8 }.to_string());
assert_eq!("e2", MyError::E2::<u8, u8>.to_string());
}
#[test]
fn generic_error_struct() {
custom_error! {MyError<X,Y>{x:X,y:Y}="x={x} y={y}"}
assert_eq!("x=42 y=42", MyError{ x: 42u8, y: 42u8 }.to_string());
}
#[test]
fn single_error_case_with_braces() {
custom_error! {MyError Bad="bad"}
assert_eq!("bad", MyError::Bad.to_string());
}
#[test]
fn single_error_struct_case_with_braces() {
custom_error! {MyError{} ="bad"}
assert_eq!("bad", MyError{}.to_string())
}
#[test]
fn trailing_comma() {
custom_error! {MyError1 A="a",}
custom_error! {MyError2 A="a", B="b",}
assert_eq!("a", MyError1::A.to_string());
assert_eq!("a", MyError2::A.to_string());
assert_eq!("b", MyError2::B.to_string());
}
#[test]
fn with_custom_formatting() {
custom_error! {MyError
Complex{a:u8, b:u8} = @{
if a+b == 0 {
"zero".to_string()
} else {
(a+b).to_string()
}
},
Simple = "simple"
}
assert_eq!("zero", MyError::Complex { a: 0, b: 0 }.to_string());
assert_eq!("3", MyError::Complex { a: 2, b: 1 }.to_string());
assert_eq!("simple", MyError::Simple.to_string());
}
#[test]
fn struct_with_custom_formatting() {
custom_error! {MyError{a:u8, b:u8} = @{
if a+b == 0 {
"zero".to_string()
} else {
(a+b).to_string()
}
}
}
assert_eq!("zero", MyError { a: 0, b: 0 }.to_string());
assert_eq!("3", MyError { a: 2, b: 1 }.to_string());
}
#[test]
fn custom_format_source() {
use std::io;
custom_error! {MyError
Io{source:io::Error} = @{format!("IO Error occurred: {:?}", source.kind())}
}
assert_eq!(
"IO Error occurred: Interrupted",
MyError::Io { source: io::ErrorKind::Interrupted.into() }.to_string()
)
}
#[test]
fn struct_custom_format_source() {
use std::io;
custom_error! {MyError{source:io::Error} = @{format!("IO Error occurred: {:?}", source.kind())} }
assert_eq!(
"IO Error occurred: Interrupted",
MyError { source: io::ErrorKind::Interrupted.into() }.to_string()
)
}
#[test]
fn lifetime_source_param() {
#[derive(Debug)]
struct SourceError<'my_lifetime> { x : &'my_lifetime str }
impl<'a> std::fmt::Display for SourceError<'a> {
fn fmt(&self, _: &mut std::fmt::Formatter) -> std::fmt::Result {
Ok(())
}
}
impl<'a> std::error::Error for SourceError<'a> {}
custom_error! { MyError<'source_lifetime>
Sourced { source : SourceError<'source_lifetime> } = @{ source.x },
Other { source: std::fmt::Error } = "other error"
}
let sourced = MyError::Sourced { source : SourceError { x: "I am the source"} };
assert_eq!("I am the source", sourced.to_string());
let other_err : MyError = std::fmt::Error.into();
assert_eq!("other error", other_err.to_string());
}
#[test]
fn struct_lifetime_source_param() {
#[derive(Debug)]
struct SourceError<'my_lifetime> { x : &'my_lifetime str }
impl<'a> std::fmt::Display for SourceError<'a> {
fn fmt(&self, _: &mut std::fmt::Formatter) -> std::fmt::Result {
Ok(())
}
}
impl<'a> std::error::Error for SourceError<'a> {}
custom_error! { MyError<'source_lifetime>{
source : SourceError<'source_lifetime>
} = @{ source.x },}
let sourced = MyError{ source : SourceError { x: "I am the source"} };
assert_eq!("I am the source", sourced.to_string());
}
#[test]
fn lifetime_param_and_type_param() {
#[derive(Debug)]
struct MyType<'a,T> {data: &'a str, _y: T}
custom_error! { MyError<'a,T>
X { d: MyType<'a,T> } = @{ format!("error x: {}", d.data) },
Y { d: T } = "error y"
}
let err = MyError::X { d : MyType { data: "hello", _y:42i8 } };
assert_eq!("error x: hello", err.to_string());
let err_y = MyError::Y { d : String::from("my string") };
assert_eq!("error y", err_y.to_string());
}
#[test]
fn struct_lifetime_param_and_type_param() {
#[derive(Debug)]
struct MyType<'a,T> {data: &'a str, _y: T}
custom_error! { MyError<'a,T> {
d: MyType<'a,T>
} = @{ format!("error x: {}", d.data) } }
let err = MyError { d : MyType { data: "hello", _y:42i8 } };
assert_eq!("error x: hello", err.to_string());
}
}
| true |
e240986fc6c32778fe2b5d0d81dbd8015a3b01c1
|
Rust
|
lowellmower/pm
|
/src/lib.rs
|
UTF-8
| 906 | 2.546875 | 3 |
[] |
no_license
|
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::*;
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_get_id(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
// create an arbitrary public function on the AST
// derived name and tokenize for return
let result = quote! {
impl #name {
pub fn get_id() -> u8 { 9 }
}
};
result.into()
}
#[proc_macro_derive(HelloFields)]
pub fn hello_fields_print_fields(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let ident_name = &input.ident;
// let data = &input.data;
let result = quote! {
impl #ident_name {
fn print_name(&self) -> String {
self.name.clone()
}
}
};
result.into()
}
| true |
4ba16001438b31655b79f8c51ddab785744ba0b6
|
Rust
|
dallonf/advent-of-code-2019
|
/src/days/day08.rs
|
UTF-8
| 5,457 | 2.8125 | 3 |
[] |
no_license
|
// Day NN: Description
use crate::prelude::*;
fn flatten_results<'a, T, E>(results: impl Iterator<Item = Result<T, E>>) -> Result<Vec<T>, Vec<E>>
where
E: std::fmt::Debug,
{
results.fold(Ok(vec![]), |prev, next| match prev {
Ok(mut results) => match next {
Ok(next_result) => {
results.push(next_result);
Ok(results)
}
Err(next_err) => Err(vec![next_err]), // Start tracking errors instead
},
Err(mut errs) => match next {
Ok(_next_result) => Err(errs), // ignore OK results
Err(next_err) => {
errs.push(next_err);
Err(errs)
}
},
})
}
#[derive(Debug, PartialEq)]
pub struct SpaceImage {
pub layers: Vec<Layer>,
}
impl SpaceImage {
pub fn parse(input: &str, width: usize, height: usize) -> Result<SpaceImage, String> {
let layer_size = width * height;
if input.len() % layer_size != 0 {
return Err(format!(
"Input must contain layers sized width:{} and height:{}",
width, height
)
.into());
}
let layers = SpaceImageParseIterator {
remaining_str: input,
layer_size,
};
let layers = flatten_results(layers.map(|x| Layer::parse(x, width, height)));
match layers {
Ok(layers) => Ok(SpaceImage { layers }),
Err(errs) => Err(errs.join("\n")),
}
}
pub fn checksum(&self) -> usize {
let fewest_zeroes_layer = self
.layers
.iter()
.map(|x| (x, x.all_pixels().filter(|px| *px == 0).count()))
.min_by(|x, y| x.1.cmp(&y.1))
.unwrap()
.0;
let one_digits = fewest_zeroes_layer
.all_pixels()
.filter(|px| *px == 1)
.count();
let two_digits = fewest_zeroes_layer
.all_pixels()
.filter(|px| *px == 2)
.count();
one_digits * two_digits
}
}
struct SpaceImageParseIterator<'a> {
remaining_str: &'a str,
layer_size: usize,
}
impl<'a> Iterator for SpaceImageParseIterator<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining_str.len() >= self.layer_size {
let (next_layer, remaining_str) = self.remaining_str.split_at(self.layer_size);
self.remaining_str = remaining_str;
Some(next_layer)
} else {
None
}
}
}
#[derive(Debug, PartialEq)]
pub struct Layer {
pub rows: Vec<Vec<u8>>,
}
impl Layer {
fn parse(input: &str, width: usize, height: usize) -> Result<Layer, String> {
if input.len() != width * height {
return Err(
format!("Layer must be sized width:{} and height:{}", width, height).into(),
);
}
let rows = (0..height).map(|y| {
(0..width)
.map(move |x| input.bytes().nth(y * width + x).unwrap())
.map(move |b| {
let c = char::from(b);
u8::from_str_radix(&c.to_string(), 10).map_err(|err| err.to_string())
})
.collect()
});
let rows = flatten_results(rows);
match rows {
Ok(rows) => Ok(Layer { rows }),
Err(errs) => Err(errs.join("\n")),
}
}
pub fn all_pixels(&self) -> impl Iterator<Item = u8> + '_ {
self.rows.iter().flatten().cloned()
}
}
lazy_static! {
static ref PUZZLE_INPUT: String = puzzle_input::string_for_day("08");
}
#[cfg(test)]
mod part_one {
use super::*;
#[test]
fn flatten_result_success() {
let input: Vec<Result<_, ()>> = vec![Ok("hello"), Ok("world")];
let expected = Ok(vec!["hello", "world"]);
assert_eq!(flatten_results(input.into_iter()), expected);
}
#[test]
fn flatten_result_error() {
let input: Vec<Result<(), _>> = vec![Err("error"), Err("world")];
let expected = Err(vec!["error", "world"]);
assert_eq!(flatten_results(input.into_iter()), expected);
}
#[test]
fn flatten_result_mixed() {
let input: Vec<Result<_, _>> =
vec![Ok("hello"), Err("error"), Ok("universe"), Err("world")];
let expected = Err(vec!["error", "world"]);
assert_eq!(flatten_results(input.into_iter()), expected);
}
#[test]
fn parse() {
let input = "123456789012";
let image = SpaceImage::parse(input, 3, 2).unwrap();
assert_eq!(
image,
SpaceImage {
layers: vec![
Layer {
rows: vec![vec![1, 2, 3], vec![4, 5, 6]]
},
Layer {
rows: vec![vec![7, 8, 9], vec![0, 1, 2]]
}
]
}
)
}
#[test]
fn checksum() {
let input = "123456789012";
let image = SpaceImage::parse(input, 3, 2).unwrap();
assert_eq!(image.checksum(), 1);
}
#[test]
fn answer() {
let image = SpaceImage::parse(&PUZZLE_INPUT, 25, 6).unwrap();
assert_eq!(image.checksum(), 1596);
}
}
// #[cfg(test)]
// mod part_two {
// use super::*;
// #[test]
// fn test_cases() {}
// #[test]
// fn answer() {}
// }
| true |
1c9cccc91debd0f0e4a4c5170308af8549eefb22
|
Rust
|
zwhitchcox/leetcode_rs
|
/src/_1005_maximize_sum_of_array_after_k_negations.rs
|
UTF-8
| 851 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
struct Solution;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
fn largest_sum_after_k_negations(a: Vec<i32>, mut k: i32) -> i32 {
let reverse: Vec<Reverse<i32>> = a.into_iter().map(Reverse).collect();
let mut pq = BinaryHeap::from(reverse);
while k > 0 {
if let Some(min) = pq.pop() {
pq.push(Reverse(-min.0));
}
k -= 1;
}
pq.into_iter().map(|x| x.0).sum()
}
}
#[test]
fn test() {
let a = vec![4, 2, 3];
let k = 1;
assert_eq!(Solution::largest_sum_after_k_negations(a, k), 5);
let a = vec![3, -1, 0, 2];
let k = 3;
assert_eq!(Solution::largest_sum_after_k_negations(a, k), 6);
let a = vec![2, -3, -1, 5, -4];
let k = 2;
assert_eq!(Solution::largest_sum_after_k_negations(a, k), 13);
}
| true |
fbc3d8dbd57b286e945c87c8a156abb6614d8cf6
|
Rust
|
putchom/yew-suzuri
|
/nachiguro/src/button.rs
|
UTF-8
| 3,441 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
#![allow(unused_variables)]
use crate::types::size::Size;
use yew::prelude::*;
pub struct Button {
props: Props,
}
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
#[prop_or_default]
pub children: Children,
#[prop_or_default]
pub class: Classes,
#[prop_or_default]
pub element: String,
#[prop_or_default]
pub href: String,
#[prop_or_default]
pub is_active: Option<bool>,
#[prop_or_default]
pub is_complete: Option<bool>,
#[prop_or_default]
pub is_disabled: Option<bool>,
#[prop_or_default]
pub is_fluid: Option<bool>,
#[prop_or_default]
pub is_light: Option<bool>,
#[prop_or_default]
pub is_loading: Option<bool>,
#[prop_or_default]
pub size: Option<Size>,
#[prop_or_default]
pub target: Option<String>,
#[prop_or_default]
pub intention: Option<String>,
}
impl Component for Button {
type Message = ();
type Properties = Props;
fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self {
Self { props }
}
fn update(&mut self, _: Self::Message) -> ShouldRender {
false
}
fn change(&mut self, props: Self::Properties) -> bool {
if self.props != props {
self.props = props;
true
} else {
false
}
}
fn view(&self) -> Html {
let Props {
children,
class,
element,
href,
is_active,
is_complete,
is_disabled,
is_fluid,
is_light,
is_loading,
size,
target,
intention,
} = &self.props;
let classes: Vec<String> = vec![
"ncgr-button".to_string(),
match is_active {
Some(_) => "ncgr-button--active".to_string(),
None => "".to_string(),
},
match is_complete {
Some(_) => "ncgr-button--complete".to_string(),
None => "".to_string(),
},
match is_disabled {
Some(_) => "ncgr-button--disabled".to_string(),
None => "".to_string(),
},
match is_fluid {
Some(_) => "ncgr-button--fluid".to_string(),
None => "".to_string(),
},
match is_light {
Some(_) => "ncgr-button--light".to_string(),
None => "".to_string(),
},
match is_loading {
Some(_) => "ncgr-button--loading".to_string(),
None => "".to_string(),
},
match size {
Some(size) => format!("ncgr-button--{}", size),
None => "".to_string(),
},
match intention {
Some(intention) => format!("ncgr-button--{}", intention),
None => "".to_string(),
},
];
html! {
<@{self.props.element.clone()}
class=classes!(classes, class.clone())
href=href.to_string()
target={
match self.props.target.clone() {
Some(target) => target.to_string(),
None => "".to_string()
}
}
>
{ children.clone() }
</@>
}
}
}
| true |
8e2c0f6ff27fb0d1c39694f7ca5622350b84ec5c
|
Rust
|
immunant/c2rust
|
/c2rust-refactor/src/rewrite/files.rs
|
UTF-8
| 9,266 | 2.90625 | 3 |
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
//! Code for applying `TextRewrite`s to the actual source files.
use diff;
use std::collections::{HashMap, VecDeque};
use std::io;
use syntax::source_map::{SourceFile, SourceMap};
use syntax_pos::{BytePos, FileName};
use crate::file_io::FileIO;
use crate::rewrite::cleanup::cleanup_rewrites;
use crate::rewrite::{TextAdjust, TextRewrite};
/// Apply a sequence of rewrites to the source code, handling the results by passing the new text
/// to `callback` along with the `SourceFile` describing the original source file.
pub fn rewrite_files_with(cm: &SourceMap, rw: &TextRewrite, io: &dyn FileIO) -> io::Result<()> {
let mut by_file = HashMap::new();
for rw in &rw.rewrites {
let sf = cm.lookup_byte_offset(rw.old_span.lo()).sf;
let ptr = (&sf as &SourceFile) as *const _;
by_file
.entry(ptr)
.or_insert_with(|| (Vec::new(), Vec::new(), sf))
.0
.push(rw.clone());
}
for &(span, id) in &rw.nodes {
let sf = cm.lookup_byte_offset(span.lo()).sf;
let ptr = (&sf as &SourceFile) as *const _;
by_file
.entry(ptr)
.or_insert_with(|| (Vec::new(), Vec::new(), sf))
.1
.push((span, id));
}
for (_, (rewrites, nodes, sf)) in by_file {
let path = match sf.name {
FileName::Real(ref path) => path,
_ => {
warn!("can't rewrite virtual file {:?}", sf.name);
continue;
}
};
// TODO: do something with nodes
io.save_rewrites(cm, &sf, &rewrites, &nodes)?;
let mut buf = String::new();
let rewrites = cleanup_rewrites(cm, rewrites);
rewrite_range(cm, sf.start_pos, sf.end_pos, &rewrites, &mut |s| {
buf.push_str(s)
});
io.write_file(path, &buf)?;
}
io.end_rewrite(cm)?;
Ok(())
}
#[allow(dead_code)] // Helper function for debugging
fn print_rewrite(rw: &TextRewrite, depth: usize) {
for _ in 0..depth {
print!(" ");
}
info!("{:?} -> {:?}", rw.old_span, rw.new_span);
for rw in &rw.rewrites {
print_rewrite(rw, depth + 1);
}
}
#[allow(dead_code)] // Helper function for debugging
fn print_rewrites(rws: &[TextRewrite]) {
info!("{} rewrites:", rws.len());
for rw in rws {
info!(
" {:?} -> {:?} (+{} children)",
rw.old_span,
rw.new_span,
rw.rewrites.len()
);
}
}
/// Apply a sequence of rewrites to the source text between source_map positions `start` and `end`.
/// Runs `callback` on each contiguous block of text in the rewritten version.
///
/// All rewrites must be in order, and must lie between `start` and `end`. Otherwise a panic may
/// occur.
fn rewrite_range(
cm: &SourceMap,
start: BytePos,
end: BytePos,
rewrites: &[TextRewrite],
callback: &mut dyn FnMut(&str),
) {
let mut cur = start;
for rw in rewrites {
if rw.old_span.lo() != cur {
emit_chunk(cm, cur, rw.old_span.lo(), |s| callback(s));
}
match rw.adjust {
TextAdjust::None => {}
TextAdjust::Parenthesize => callback("("),
}
if rw.rewrites.is_empty() {
emit_chunk(cm, rw.new_span.lo(), rw.new_span.hi(), |s| callback(s));
} else {
rewrite_range(
cm,
rw.new_span.lo(),
rw.new_span.hi(),
&rw.rewrites,
callback,
);
}
match rw.adjust {
TextAdjust::None => {}
TextAdjust::Parenthesize => callback(")"),
}
cur = rw.old_span.hi();
}
if cur != end {
emit_chunk(cm, cur, end, |s| callback(s));
}
}
/// Runs `callback` on the source text between `lo` and `hi`.
fn emit_chunk<F: FnMut(&str)>(cm: &SourceMap, lo: BytePos, hi: BytePos, mut callback: F) {
let lo = cm.lookup_byte_offset(lo);
let hi = cm.lookup_byte_offset(hi);
let src = lo
.sf
.src
.as_ref()
.unwrap_or_else(|| panic!("source of file {} is not available", lo.sf.name));
callback(&src[lo.pos.0 as usize..hi.pos.0 as usize]);
}
/// Print a unified diff between lines of `s1` and lines of `s2`.
pub fn print_diff(s1: &str, s2: &str) {
enum State {
/// We're not in a hunk, just keeping `buf` populated with `CONTEXT` lines of history.
History,
/// We're inside a hunk containing at least one changed line.
Hunk {
/// Number of unchanged lines we need to see to end this hunk.
unchanged_limit: usize,
l_start: usize,
r_start: usize,
},
}
const CONTEXT: usize = 3;
let mut buf = VecDeque::new();
let mut state = State::History;
let mut l_line = 1;
let mut r_line = 1;
for r in diff::lines(s1, s2) {
let changed = match r {
diff::Result::Both(l, r) => l != r,
_ => true,
};
// We need to update l/r_line before we move `r`, but after we move it, we may need access
// to the old l/r_line values to initialize state.l/r_start.
let (l_line_old, r_line_old) = (l_line, r_line);
match r {
diff::Result::Left(..) => {
l_line += 1;
}
diff::Result::Right(..) => {
r_line += 1;
}
diff::Result::Both(..) => {
l_line += 1;
r_line += 1;
}
}
buf.push_back(r);
if !changed {
match state {
State::History => {
while buf.len() > CONTEXT {
buf.pop_front();
}
}
State::Hunk {
unchanged_limit,
l_start,
r_start,
} => {
if unchanged_limit == 1 {
// End of the hunk
let end = buf.len() - CONTEXT;
let suffix = buf.split_off(end);
print_hunk(&buf, l_start, r_start);
buf = suffix;
state = State::History;
} else {
state = State::Hunk {
unchanged_limit: unchanged_limit - 1,
l_start,
r_start,
};
}
}
}
} else {
match state {
State::History => {
state = State::Hunk {
unchanged_limit: 2 * CONTEXT,
// Adjust start lines for context already stored in `buf`.
l_start: l_line_old - (buf.len() - 1),
r_start: r_line_old - (buf.len() - 1),
};
}
State::Hunk {
l_start, r_start, ..
} => {
state = State::Hunk {
unchanged_limit: 2 * CONTEXT,
l_start,
r_start,
};
}
}
}
}
match state {
State::Hunk {
unchanged_limit,
l_start,
r_start,
} => {
if unchanged_limit < CONTEXT {
let end = buf.len() - (CONTEXT - unchanged_limit);
buf.truncate(end);
}
print_hunk(&buf, l_start, r_start);
}
_ => {}
}
}
/// Print a single diff hunk, starting at line `l_start` in the left file and `r_start` in the
/// right file.
fn print_hunk(buf: &VecDeque<diff::Result<&str>>, l_start: usize, r_start: usize) {
let l_size = buf
.iter()
.filter(|r| match r {
diff::Result::Right(_) => false,
_ => true,
})
.count();
let r_size = buf
.iter()
.filter(|r| match r {
diff::Result::Left(_) => false,
_ => true,
})
.count();
println!("@@ -{},{} +{},{} @@", l_start, l_size, r_start, r_size);
// Print all "left" lines immediately. Keep all "right" lines and print them just before the
// next unchanged line. This way we get the usual output, with separate old and new blocks:
// unchanged
// -old1
// -old2
// +new1
// +new2
// unchanged
let mut right_buf = Vec::new();
for r in buf {
match r {
diff::Result::Left(s) => {
println!("-{}", s);
}
diff::Result::Right(s) => {
right_buf.push(s);
}
diff::Result::Both(s1, s2) => {
if s1 != s2 {
println!("-{}", s1);
right_buf.push(s2);
} else {
for s in right_buf.drain(..) {
println!("+{}", s);
}
println!(" {}", s1);
}
}
}
}
}
| true |
129cddb4deb72e918f91f67165f9931eef59e737
|
Rust
|
hstarorg/learning-rust
|
/rust-study-base/src/bin/13.rs
|
UTF-8
| 595 | 3.734375 | 4 |
[
"MIT"
] |
permissive
|
// 特性:所有权(悬垂引用:悬垂指针是其指向的内存可能已经被分配给其它持有者)
fn main() {
// 如下调用会报错,返回的引用指向的内存区域已经被释放了
// let reference_to_nothing = dangle();
let safe_str = safe();
println!("safe_str={}", safe_str);
}
// 需要先注释,避免编译错误
// fn dangle() -> &String {
// let s = String::from("hello");
// &s // 返回字符串 s 的引用,s 离开函数就被释放,引用是无效的
// }
fn safe() -> String {
let s = String::from("hello");
s
}
| true |
d53fcca4c7299eeabe9be6df176467e7729f17be
|
Rust
|
rozaliev/monkeys
|
/src/stack.rs
|
UTF-8
| 1,478 | 2.703125 | 3 |
[] |
no_license
|
use std::ops::Deref;
use std::cell::RefCell;
use context::stack::{ProtectedFixedSizeStack, Stack};
thread_local!(static STACK_POOL: StackPool = StackPool::new());
pub struct PooledStack(Option<ProtectedFixedSizeStack>);
struct StackPool {
pool: RefCell<Vec<ProtectedFixedSizeStack>>,
}
impl StackPool {
fn new() -> StackPool {
let mut v = Vec::with_capacity(500);
for _ in 0..500 {
v.push(ProtectedFixedSizeStack::default());
}
StackPool { pool: RefCell::new(v) }
}
fn give(&self, stack: ProtectedFixedSizeStack) {
self.pool.borrow_mut().push(stack);
}
fn get(&self) -> ProtectedFixedSizeStack {
let mut stack_opt = self.pool.borrow_mut().pop();
if stack_opt.is_none() {
self.grow();
stack_opt = self.pool.borrow_mut().pop();
}
stack_opt.unwrap()
}
fn grow(&self) {
let mut p = self.pool.borrow_mut();
for _ in 0..p.capacity() * 2 {
p.push(ProtectedFixedSizeStack::default())
}
}
}
impl PooledStack {
pub fn new() -> PooledStack {
STACK_POOL.with(|p| PooledStack(Some(p.get())))
}
}
impl Drop for PooledStack {
fn drop(&mut self) {
let stack = self.0.take().unwrap();
STACK_POOL.with(|p| p.give(stack))
}
}
impl Deref for PooledStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&*self.0.as_ref().unwrap()
}
}
| true |
57f1aa20efcc9f4bb80d9e53f22e0e85abd85c00
|
Rust
|
SimonPersson/librespot
|
/src/main_helper.rs
|
UTF-8
| 4,474 | 2.546875 | 3 |
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
use getopts;
use rpassword;
use std::io::{stdout, Write};
use std::path::PathBuf;
use std::process::exit;
use audio_backend::{BACKENDS, Sink};
use authentication::{Credentials, facebook_login, discovery_login};
use cache::{Cache, DefaultCache, NoCache};
use player::Player;
use session::{Bitrate, Config, Session};
use version;
pub fn find_backend(name: Option<&str>) -> &'static (Fn(Option<&str>) -> Box<Sink> + Send + Sync) {
match name {
Some("?") => {
println!("Available Backends : ");
for (&(name, _), idx) in BACKENDS.iter().zip(0..) {
if idx == 0 {
println!("- {} (default)", name);
} else {
println!("- {}", name);
}
}
exit(0);
},
Some(name) => {
BACKENDS.iter().find(|backend| name == backend.0).expect("Unknown backend").1
},
None => {
BACKENDS.first().expect("No backends were enabled at build time").1
}
}
}
pub fn add_session_arguments(opts: &mut getopts::Options) {
opts.optopt("c", "cache", "Path to a directory where files will be cached.", "CACHE")
.reqopt("n", "name", "Device name", "NAME")
.optopt("b", "bitrate", "Bitrate (96, 160 or 320). Defaults to 160", "BITRATE");
}
pub fn add_authentication_arguments(opts: &mut getopts::Options) {
opts.optopt("u", "username", "Username to sign in with", "USERNAME")
.optopt("p", "password", "Password", "PASSWORD");
if cfg!(feature = "facebook") {
opts.optflag("", "facebook", "Login with a Facebook account");
}
}
pub fn add_player_arguments(opts: &mut getopts::Options) {
opts.optopt("", "backend", "Audio backend to use. Use '?' to list options", "BACKEND");
opts.optopt("", "device", "Audio device to use. Use '?' to list options", "DEVICE");
}
pub fn create_session(matches: &getopts::Matches) -> Session {
info!("librespot {} ({}). Built on {}.",
version::short_sha(),
version::commit_date(),
version::short_now());
let name = matches.opt_str("n").unwrap();
let bitrate = match matches.opt_str("b").as_ref().map(String::as_ref) {
None => Bitrate::Bitrate160, // default value
Some("96") => Bitrate::Bitrate96,
Some("160") => Bitrate::Bitrate160,
Some("320") => Bitrate::Bitrate320,
Some(b) => {
error!("Invalid bitrate {}", b);
exit(1)
}
};
let cache = matches.opt_str("c").map(|cache_location| {
Box::new(DefaultCache::new(PathBuf::from(cache_location)).unwrap()) as Box<Cache + Send + Sync>
}).unwrap_or_else(|| Box::new(NoCache) as Box<Cache + Send + Sync>);
let config = Config {
user_agent: version::version_string(),
device_name: name,
bitrate: bitrate,
};
Session::new(config, cache)
}
pub fn get_credentials(session: &Session, matches: &getopts::Matches) -> Credentials {
let credentials = session.cache().get_credentials();
match (matches.opt_str("username"),
matches.opt_str("password"),
credentials) {
(Some(username), Some(password), _)
=> Credentials::with_password(username, password),
(Some(ref username), _, Some(ref credentials)) if *username == credentials.username
=> credentials.clone(),
(Some(username), None, _) => {
print!("Password for {}: ", username);
stdout().flush().unwrap();
let password = rpassword::read_password().unwrap();
Credentials::with_password(username.clone(), password)
}
(None, _, _) if cfg!(feature = "facebook") && matches.opt_present("facebook")
=> facebook_login().unwrap(),
(None, _, Some(credentials))
=> credentials,
(None, _, None) => {
info!("No username provided and no stored credentials, starting discovery ...");
discovery_login(&session.config().device_name, session.device_id()).unwrap()
}
}
}
pub fn create_player(session: &Session, matches: &getopts::Matches) -> Player {
let backend_name = matches.opt_str("backend");
let device_name = matches.opt_str("device");
let make_backend = find_backend(backend_name.as_ref().map(AsRef::as_ref));
Player::new(session.clone(), move || {
make_backend(device_name.as_ref().map(AsRef::as_ref))
})
}
| true |
d685ebdba41d4d1d3c7984ea165933cf36f70965
|
Rust
|
sireliah/huffman_encoding
|
/src/huffman.rs
|
UTF-8
| 4,329 | 3.5625 | 4 |
[] |
no_license
|
use std::collections::HashMap;
#[derive(Debug)]
pub struct Node<'z> {
pub symbol: &'z str,
pub prob: f32,
/// Box reallocates the node from stack to heap.
/// Otherwise, the compiler will complain that "recursive type `Node` has infinite size"
pub left: Option<Box<Node<'z>>>,
pub right: Option<Box<Node<'z>>>,
}
impl<'z> Node<'z> {
pub fn build_dictionary(&self, result_list: Vec<(&Node, Vec<i32>)>) -> HashMap<String, Vec<i32>> {
/// Create dictionary based on nodes in the vector.
/// TODO: create this using map()
let mut dictionary = HashMap::new();
for tuple in &result_list {
if tuple.0.symbol != "*" {
/// Symbol of the node.
let symbol = tuple.0.symbol.to_string().clone();
/// Vector of codes.
let codes = tuple.1.clone();
dictionary.insert(symbol, codes);
}
}
return dictionary;
}
pub fn generate_codes(&self) -> Vec<(&Node, Vec<i32>)> {
/// Traverse the tree using a simple queue algorithm.
/// Store results in pair (Node, turned) where "turned" determines
/// if we descended left or right.
let mut stack = Vec::<(&Node, Vec<i32>)>::new();
let mut result = Vec::<(&Node, Vec<i32>)>::new();
stack.push((self, vec![]));
/// Loop until you reach all nodes that don't have left or right children.
while !stack.is_empty() {
let (node, codes) = stack.pop().unwrap();
let copied_node = node.clone();
let copied_codes = codes.clone();
/// Push left or right child if node has reference to it.
/// Add copied vector of codes with 1 or 0 at the end for right/left.
result.push((copied_node, copied_codes));
if let Some(box ref nod) = node.right {
let mut new_codes = codes.clone();
new_codes.push(1);
stack.push((nod, new_codes));
}
if let Some(box ref nod) = node.left {
let mut new_codes = codes.clone();
new_codes.push(0);
stack.push((nod, new_codes));
}
}
return result;
}
pub fn create_branch(nodes: &mut Vec<Node>) {
/// Create new branch whit two lowest nodes as (left and right) children.
/// Sort by probability and pop two lowest.
nodes.sort_by(|a, b| b.prob.partial_cmp(&a.prob).unwrap());
let first = match nodes.pop() {
Some(i) => i,
None => return,
};
let second: Node = match nodes.pop() {
Some(i) => i,
None => return,
};
/// Create new node and push it to the vector.
let new_node = Node {
symbol: "*",
prob: first.prob + second.prob,
left: Some(Box::new(first)),
right: Some(Box::new(second)),
};
nodes.push(new_node);
}
}
#[cfg(test)]
mod test {
use huffman::Node;
use std::collections::HashMap;
#[test]
fn test_build_dictionary_success() {
let node_a = Node {symbol: "A", prob: 0.5, left: None, right: None};
let node_b = Node {symbol: "B", prob: 0.5, left: None, right: None};
let node_root = Node {symbol: "*", prob: 1.0, left: None, right: None};
let result_list = vec![(&node_root, vec![1]), (&node_a, vec![0]), (&node_b, vec![1])];
let dictionary = node_root.build_dictionary(result_list);
let mut expected_dict = HashMap::new();
expected_dict.insert("A".to_string(), vec![0]);
expected_dict.insert("B".to_string(), vec![1]);
assert_eq!(expected_dict, dictionary);
}
#[test]
fn test_create_branch_success() {
let mut nodes = vec![
Node {symbol: "A", prob: 0.5, left: None, right: None},
Node {symbol: "B", prob: 0.5, left: None, right: None},
];
Node::create_branch(&mut nodes);
assert_eq!(nodes.len(), 1);
assert_eq!(nodes[0].symbol, "*");
assert_eq!(nodes[0].prob, 1.0);
assert_eq!(nodes[0].left.is_none(), false);
assert_eq!(nodes[0].right.is_none(), false);
}
}
| true |
241d9915a7a80b908c52bb034f63dd6e46e9f1fd
|
Rust
|
iulyaav/advent-of-code
|
/2021/2.day_two/two.rs
|
UTF-8
| 897 | 3.3125 | 3 |
[] |
no_license
|
use std::env;
use std::fs;
use std::collections::VecDeque;
fn main() {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
println!("Opening file {}", filename);
let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file");
let mut horizontal: i32 = 0;
let mut depth: i32 = 0;
let mut aim: i32 = 0;
for line in contents.lines() {
let vec: Vec<&str> = line.split(' ').collect();
let command : String = vec[0].to_string();
let value : i32 = vec[1].parse().unwrap();
if command.eq("forward") {
horizontal += value;
depth += (aim * value);
} else if command.eq("up") {
aim -= value;
} else if command.eq("down") {
aim += value;
}
}
println!("Result: {}", horizontal * depth);
}
| true |
e635bf63e047e9dac338ba7aef62e107eff5d119
|
Rust
|
tommady/leetcode
|
/rust/src/p1827_minimum_operations_to_make_the_array_increasing.rs
|
UTF-8
| 1,902 | 3.96875 | 4 |
[] |
no_license
|
// You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.
For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].
Return the minimum number of operations needed to make nums strictly increasing.
An array nums is strictly increasing if nums[i] nums[i+1] for all 0 = i nums.length - 1. An array of length 1 is trivially strictly increasing.
Example 1:
Input: nums = [1,1,1]
Output: 3
Explanation: You can do the following operations:
1) Increment nums[2], so nums becomes [1,1,2].
2) Increment nums[1], so nums becomes [1,2,2].
3) Increment nums[2], so nums becomes [1,2,3].
Example 2:
Input: nums = [1,5,2,4,1]
Output: 14
Example 3:
Input: nums = [8]
Output: 0
Constraints:
1 = nums.length = 5000
1 = nums[i] = 104
//
//
// [1,1,1]
// [1,5,2,4,1]
// [8]
//
#![allow(dead_code)]
pub struct Solution {}
impl Solution {
pub fn min_operations(mut nums: Vec<i32>) -> i32 {
let mut counter = 0;
fn abs(v: i32) -> i32 {
if v < 0 {
return -v;
}
v
}
let mut i = 1;
while i < nums.len() {
if nums[i - 1] >= nums[i] {
let ops = abs(nums[i] - nums[i - 1]) + 1;
nums[i] += ops;
counter += ops;
}
i += 1;
}
counter
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1827_solution() {
assert_eq!(3, Solution::min_operations(vec![1, 1, 1]));
// [1, 5, 2, 4, 1]
// [1, 5, 6, 4, 1] + 4
// [1, 5, 6, 7, 1] + 4 + 3
// [1, 5, 6, 7, 8] + 4 + 3 + 7
assert_eq!(14, Solution::min_operations(vec![1, 5, 2, 4, 1]));
assert_eq!(0, Solution::min_operations(vec![8]));
}
}
| true |
b1476fe1e2595685b72f53d554e46ad754c9218f
|
Rust
|
ddboline/movie_collection_rust
|
/movie_collection_lib/src/timezone.rs
|
UTF-8
| 1,319 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
use anyhow::{format_err, Error};
use derive_more::Into;
use serde::{Deserialize, Serialize};
use stack_string::StackString;
use std::{convert::TryFrom, ops::Deref, str::FromStr};
use time_tz::{timezones::get_by_name, TimeZone as TzTimeZone, Tz};
/// Direction in degrees
#[derive(Into, Debug, PartialEq, Copy, Clone, Eq, Serialize, Deserialize)]
#[serde(into = "StackString", try_from = "StackString")]
pub struct TimeZone(&'static Tz);
impl Deref for TimeZone {
type Target = Tz;
fn deref(&self) -> &Self::Target {
self.0
}
}
impl From<TimeZone> for String {
fn from(item: TimeZone) -> Self {
item.0.name().into()
}
}
impl From<TimeZone> for StackString {
fn from(item: TimeZone) -> Self {
item.0.name().into()
}
}
impl FromStr for TimeZone {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
get_by_name(s)
.map(Self)
.ok_or_else(|| format_err!("{s} is not a valid timezone"))
}
}
impl TryFrom<&str> for TimeZone {
type Error = Error;
fn try_from(item: &str) -> Result<Self, Self::Error> {
item.parse()
}
}
impl TryFrom<StackString> for TimeZone {
type Error = Error;
fn try_from(item: StackString) -> Result<Self, Self::Error> {
item.as_str().parse()
}
}
| true |
07ad11fe99554596b6d432625bcbf49ce59dfb69
|
Rust
|
portablejim/adventofcode
|
/2018/rust/src/bin/day3.rs
|
UTF-8
| 2,822 | 3.234375 | 3 |
[] |
no_license
|
extern crate regex;
use regex::Regex;
use std::io::{self, BufRead};
use std::collections::HashMap;
use std::clone::Clone;
#[derive(PartialEq, Eq, Hash, Clone)]
struct Claim {
number: i32,
x: i32,
y: i32,
width: i32,
height: i32
}
#[derive(PartialEq, Eq, Hash, Clone)]
struct Square {
x: i32,
y: i32
}
#[derive(PartialEq, Eq, Hash, Clone)]
struct SquareValue {
count: i32,
claims: Vec<i32>
}
fn main() {
let re = Regex::new(r"#(\d+) @ (\d+),(\d+): (\d+)x(\d+)").unwrap();
let stdin = io::stdin();
let input_list: Vec<Claim> = stdin.lock().lines()
.filter_map(|s| s.ok())
.map(|s| {
let caps = re.captures(&s).expect("Caps");
Claim {
number: caps.get(1).expect("Extract 1").as_str().parse::<i32>().expect("Parse 1"),
x: caps.get(2).expect("Extract 2").as_str().parse::<i32>().expect("Parse 2"),
y: caps.get(3).expect("Extract 3").as_str().parse::<i32>().expect("Parse 3"),
width: caps.get(4).expect("Extract 4").as_str().parse::<i32>().expect("Parse 4"),
height: caps.get(5).expect("Extract 5").as_str().parse::<i32>().expect("Parse 5")
}
})
.collect();
let mut fabric_squares: HashMap<Square, SquareValue>= HashMap::new();
let mut not_overlaps: Vec<i32> = Vec::new();
for input_item in &input_list {
let mut overlaps = false;
for cy in input_item.y..(input_item.y + input_item.height) {
for cx in input_item.x..(input_item.x + input_item.width) {
let target_square = Square{ x: cx, y: cy };
let mut old_value = if let Some(val) = fabric_squares.get_mut(&target_square).cloned() {
overlaps = true;
val
}
else {
SquareValue{ count: 0, claims: Vec::new() }
};
old_value.count += 1;
old_value.claims.push(input_item.number);
fabric_squares.insert(target_square, old_value);
}
}
}
for input_item in &input_list {
let num_overlapping = fabric_squares.values().filter(|sv| sv.count > 1 && sv.claims.iter().filter(|c| **c == input_item.number).count() > 0).count();
if num_overlapping == 0
{
not_overlaps.push(input_item.number);
}
}
let num_above_2 = fabric_squares.values().map(|sv| sv.count).filter(|v| *v >= 2).count();
//let num_one_claim: Vec<Vec<i32>> = fabric_squares.values().filter(|sv| sv.count == 1).map(|sv| sv.claims.clone()).collect();
println!("Number of squares with 2 or more claims: {}", num_above_2);
println!("Squares that don't overlap: {:?}", not_overlaps);
}
| true |
f722953f2ad527ccbb5016a348885e50bd5f90f1
|
Rust
|
matanmarkind/tonic_and_rocket
|
/src/server.rs
|
UTF-8
| 13,979 | 2.640625 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use std::pin::Pin;
use std::time::Instant;
use active_standby::collections::vec as asvec;
use futures::{Stream, StreamExt};
use tokio::sync::mpsc;
use tonic::transport::Server;
use tonic::{Request, Response, Status};
mod util;
use util::*;
use routeguide::program_route_server::{ProgramRoute, ProgramRouteServer};
use routeguide::route_guide_server::{RouteGuide, RouteGuideServer};
use routeguide::{Feature, Point, Rectangle, RouteNote, RouteSummary};
// The design of this server is an attempt to tie together a couple things:
// - tonic - to use GRPC
// - active_standby - for wait free reads and non-blocking writes
//
// In terms of the interface we attempt to allow wait free responses to
// non-streaming requests, and minimal waiting even to streaming requests. This
// is done by leveraging the active_standby crate. Even with active_standby, we
// continue to face a challenge, because active_standby requires passing a
// handle to each thread/task. Tonic is designed for the user not to need to
// consider generating X tasks, but at the cost of making the server Sync.
//
// In practice we handle streaming and non-streaming requests separately. For
// non-streaming requests we create a pool of worker threads which each have
// their own active_standby handle. When such a request comes in, we send it to
// the pool and wait for a response. Progress is only blocked on the worker
// threads being busy (CPU bound). For streaming requests, we will need to wait
// as part of the streaming, and so we are willing to accept a small price. What
// happens in these cases, is that this request triggers a specific task, so now
// we can allocate an active_standby handle to that task, and for the duration
// of its handling, we will have wait-free read access.
const NUM_WORKERS: i32 = 4;
enum RouteGuideServiceRequest {
// We only handle non streaming APIs here. All of the streaming APIs need to
// get their own handle to Feature and so don't work with passing off to the
// worker pool.
GetFeature(Point),
}
enum RouteGuideServiceResponse {
GetFeature(Result<Response<Feature>, Status>),
}
// TODO: Add balancing across pipelines.
struct RouteGuideService {
// Used in non-streaming APIs so send requests to the worker pool and get
// responses. This allows for each request to be handled in a wait free
// manner by each worker. If a given worker is busy we will wait until it is
// free to send it the request.
pipelines: Vec<(
// Sending requests to the worker pool is async because we may have to
// await some unknown number of other tasks being handled by the worker
// pool. Not sure if this sender is fair. It is based on crossbeam's
// channel which uses parking_lot::Mutex, which is eventually fair
// (https://github.com/crossbeam-rs/crossbeam-channel/blob/master/src/flavors/zero.rs).
// It seems that we also rely on the runtime's fairness, which I have
// little understanding of
// (https://www.reddit.com/r/rust/comments/hi9vhj/crossfire_yet_another_async_mpmcmpsc_based_on/fwg5ou4/).
crossfire::mpsc::TxFuture<RouteGuideServiceRequest, crossfire::mpsc::SharedSenderFRecvB>,
// Receiving a response from the worker pool is blocking because once
// the pool is actually working on the request we want to minimize
// latency on sending the response to the client. This may come at the
// cost of throughput since this async task will hang until it receives
// the response from the worker pool.
crossbeam::channel::Receiver<RouteGuideServiceResponse>,
)>,
// Used to clone handles to Feature for streaming APIs.
features: std::sync::Mutex<asvec::AsLockHandle<Feature>>,
// Used to send to the workers in a round robin to load balance.
worker_index: std::sync::atomic::AtomicUsize,
}
struct RouteGuideWorker {
receiver:
crossfire::mpsc::RxBlocking<RouteGuideServiceRequest, crossfire::mpsc::SharedSenderFRecvB>,
sender: crossbeam::channel::Sender<RouteGuideServiceResponse>,
features: asvec::AsLockHandle<Feature>,
}
impl RouteGuideWorker {
pub fn get_feature(&self, point: Point) -> Result<Response<Feature>, Status> {
for feature in &self.features.read()[..] {
if feature.location.as_ref() == Some(&point) {
return Ok(Response::new(feature.clone()));
}
}
Ok(Response::new(Feature::default()))
}
}
struct ProgramRouteService {
features_sender: crossbeam::channel::Sender<Feature>,
}
type StreamResponse<T> = Pin<Box<dyn Stream<Item = Result<T, Status>> + Send + Sync + 'static>>;
type ListFeaturesStream = StreamResponse<Feature>;
#[tonic::async_trait]
impl ProgramRoute for ProgramRouteService {
async fn add_feature(
&self,
request: Request<Feature>,
) -> Result<Response<routeguide::Status>, Status> {
println!("AddFeature = {:?}", request);
match self.features_sender.send(request.into_inner()) {
Ok(()) => Ok(Response::new(routeguide::Status {
status: routeguide::status::Code::Ok as i32,
error_message: "".to_owned(),
})),
Err(e) => Err(Status::new(tonic::Code::Internal, format!("{:?}", e))),
}
}
}
#[tonic::async_trait]
impl RouteGuide for RouteGuideService {
async fn get_feature(&self, request: Request<Point>) -> Result<Response<Feature>, Status> {
println!("GetFeature = {:?}", request);
let index = self
.worker_index
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
% self.pipelines.len();
let (sender, receiver) = &self.pipelines[index];
// This will await until this worker thread is free.
sender
.send(RouteGuideServiceRequest::GetFeature(request.into_inner()))
.await
.unwrap();
// This will block until the response has been received.
match receiver.recv().unwrap() {
RouteGuideServiceResponse::GetFeature(res) => res,
}
}
type ListFeaturesStream = ListFeaturesStream;
async fn list_features(
&self,
request: Request<Rectangle>,
) -> Result<Response<Self::ListFeaturesStream>, Status> {
println!("ListFeatures = {:?}", request);
// Create a handle to read features which can be sent to the streaming
// task.
let features = self.features.lock().unwrap().clone();
let (tx, rx) = mpsc::channel(4);
let rectangle = request.into_inner();
tokio::spawn(async move {
let features = features.read();
for feature in &features[..] {
if in_range(feature.location.as_ref().unwrap(), &rectangle) {
println!(" => send {:?}", feature);
tx.send(Ok(feature.clone())).await.unwrap();
}
}
});
Ok(Response::new(Box::pin(
tokio_stream::wrappers::ReceiverStream::new(rx),
)))
}
async fn record_route(
&self,
request: Request<tonic::Streaming<Point>>,
) -> Result<Response<RouteSummary>, Status> {
println!("record_route");
// Create a handle to read features which can be sent to the streaming
// task.
let features = self.features.lock().unwrap().clone();
let mut stream = request.into_inner();
let mut summary = RouteSummary::default();
let mut last_point = None;
let now = Instant::now();
while let Some(point) = stream.next().await {
// None means the end of the stream so we exit gracefully. Some(Error)
// means an actual error in the stream which we propogate up.
let point = point?;
println!(" ==> Point = {:?}", point);
summary.point_count += 1;
let features = features.read();
for feature in &features[..] {
if feature.location.as_ref() == Some(&point) {
summary.feature_count += 1;
}
}
if let Some(last_point) = last_point.as_ref() {
summary.distance += calc_distance(last_point, &point);
}
last_point = Some(point);
}
summary.elapsed_time_seconds = now.elapsed().as_secs() as i32;
Ok(Response::new(summary))
}
type RouteChatStream = StreamResponse<RouteNote>;
async fn route_chat(
&self,
request: Request<tonic::Streaming<RouteNote>>,
) -> Result<Response<Self::RouteChatStream>, Status> {
println!("route_chat");
let mut location_to_notes = HashMap::new();
let mut stream = request.into_inner();
let output = async_stream::try_stream! {
while let Some(note) = stream.next().await {
let note = note?;
let location = note.location.clone().unwrap();
let location_notes = location_to_notes.entry(location).or_insert(vec![]);
location_notes.push(note);
for note in location_notes {
yield note.clone();
}
}
};
Ok(Response::new(Box::pin(output) as Self::RouteChatStream))
}
}
fn in_range(point: &Point, bounds: &Rectangle) -> bool {
use std::cmp::{max, min};
let low = bounds.low.as_ref().unwrap();
let high = bounds.high.as_ref().unwrap();
let left = min(low.longitude, high.longitude);
let right = max(low.longitude, high.longitude);
let bottom = min(low.latitude, high.latitude);
let top = max(low.latitude, high.latitude);
point.longitude >= left
&& point.longitude <= right
&& point.latitude >= bottom
&& point.latitude <= top
}
/// Calculates the distance between two points using the "haversine" formula.
/// This code was taken from http://www.movable-type.co.uk/scripts/latlong.html.
fn calc_distance(p1: &Point, p2: &Point) -> i32 {
const CORD_FACTOR: f64 = 1e7;
const R: f64 = 6_371_000.0; // meters
let lat1 = p1.latitude as f64 / CORD_FACTOR;
let lat2 = p2.latitude as f64 / CORD_FACTOR;
let lng1 = p1.longitude as f64 / CORD_FACTOR;
let lng2 = p2.longitude as f64 / CORD_FACTOR;
let lat_rad1 = lat1.to_radians();
let lat_rad2 = lat2.to_radians();
let delta_lat = (lat2 - lat1).to_radians();
let delta_lng = (lng2 - lng1).to_radians();
let a = (delta_lat / 2f64).sin() * (delta_lat / 2f64).sin()
+ (lat_rad1).cos() * (lat_rad2).cos() * (delta_lng / 2f64).sin() * (delta_lng / 2f64).sin();
let c = 2f64 * a.sqrt().atan2((1f64 - a).sqrt());
(R * c) as i32
}
/// In order to run and check the server we need to run 3 processes:
/// - cargo run --bin server # run the backend server
/// - cargo run --bin route_programmer # update the backend server
/// - cargo run --bin web_user/route_user # run the client (web or plain)
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// The state used to generate responses.
let features = asvec::AsLockHandle::<Feature>::default();
// Create worker threads to handle requests.
let mut pipelines: Vec<_> = vec![];
let mut worker_handles: Vec<_> = vec![];
for _ in 0..NUM_WORKERS {
// We rely on creating channels with capacity 0 to synchronize the
// request and response. If there was a capacity it would be possible
// for 2 tasks to send their requests to the same worker and then
// receive the responses of each other. By placing 0 capacity on both,
// we guarantee that the order is functionally equivalent to:
// 1. task_a sends request1.
// 2. worker receives request1.
// 3. task_b sends request2 and waits for it to be received by worker.
// 4. task_a awaits receival of response1.
// 5. worker sends response1.
// 6. task_a receives response1 which only task_a is waiting to receive.
let (tx_request, rx_request) = crossfire::mpsc::bounded_tx_future_rx_blocking(0);
let (tx_response, rx_response) = crossbeam::channel::bounded(0);
pipelines.push((tx_request, rx_response));
let worker = RouteGuideWorker {
receiver: rx_request,
sender: tx_response,
features: features.clone(),
};
worker_handles.push(std::thread::spawn(move || {
while let Ok(req) = worker.receiver.recv() {
let res = match req {
RouteGuideServiceRequest::GetFeature(point) => {
RouteGuideServiceResponse::GetFeature(worker.get_feature(point))
}
};
worker.sender.send(res).unwrap();
}
}));
}
// Create the server front end which takes in requests, pipes them to the
// worker pool and gives the responses.
let route_guide = RouteGuideServer::new(RouteGuideService {
pipelines,
features: std::sync::Mutex::new(features.clone()),
worker_index: std::sync::atomic::AtomicUsize::new(0),
});
// Handle updates to the server's state.
let (sender, receiver) = crossbeam::channel::unbounded();
let route_programmer = ProgramRouteServer::new(ProgramRouteService {
features_sender: sender,
});
let writer_handle = std::thread::spawn(move || {
for feature in receiver {
features.write().push(feature);
}
});
Server::builder()
.add_service(route_guide)
.add_service(route_programmer)
.serve("[::1]:10000".parse().unwrap())
.await?;
writer_handle.join().expect("writer_handle failed");
for wh in worker_handles {
wh.join().expect("worker_handle failed");
}
Ok(())
}
| true |
b1d629bdda7e2c9e33d566421b7185424ff436ad
|
Rust
|
GeorgeKT/menhir-lang
|
/src/ast/nameref.rs
|
UTF-8
| 596 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
use crate::ast::{prefix, TreePrinter, Type};
use crate::span::Span;
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct NameRef {
pub name: String,
pub typ: Type,
pub span: Span,
}
impl NameRef {
pub fn new(name: String, span: Span) -> NameRef {
NameRef {
name: name,
typ: Type::Unknown,
span: span,
}
}
}
impl TreePrinter for NameRef {
fn print(&self, level: usize) {
let p = prefix(level);
println!("{}name {} (span: {}, type: {})", p, self.name, self.span, self.typ);
}
}
| true |
b30a11c5c295a70eeeab3bf38e72a5697ae8916b
|
Rust
|
enkron/programming_rust_web_server
|
/src/main.rs
|
UTF-8
| 3,713 | 3.9375 | 4 |
[] |
no_license
|
/// Simple web server: it'll serve only a page that prompts
/// a user for numbers to compute with.
use std::env; // Brings the env module into the scope
use std::str::FromStr; // Brings the trait FromStr
// The trait is a collection of methods that types can implement
// The trait must(!) be in scope in order to use its methods
use actix_web::{web, App, HttpResponse, HttpServer};
use serde::Deserialize;
fn main() {
let server = HttpServer::new(|| {
App::new()
.route("/", web::get().to(get_index))
.route("/gcd", web::post().to(post_gcd))
});
println!("Serving on http://localhost:3000...");
server
.bind("127.0.0.1:3000")
.expect("error binding server to address")
.run()
.expect("error running server");
let mut numbers = Vec::new(); // Creating a vector, it has to be mutable
// in order to push values onto the end of it
for arg in env::args().skip(1) {
// env::args() returns an ITERATOR
numbers.push(u64::from_str(&arg).expect("error parsing argument"));
// from_str method - it's a assotiated method (similar to
// static methods in C++ and Java)
// this method returns Result value (which enum with Err() and Ok() variants)
}
if numbers.len() == 0 {
eprintln!("Usage: gcd NUMBER ...");
std::process::exit(1);
}
let mut d = numbers[0];
for m in &numbers[1..] {
d = gcd(d, *m);
}
println!("The greatest common divisor of {:?} is {}", numbers, d);
}
// Computes the greatest common divisor of two integers, using Euclid's algorithm
fn gcd(mut n: u64, mut m: u64) -> u64 {
assert!(n != 0 && m != 0);
while m != 0 {
if m < n {
let t = m;
m = n;
n = t;
}
m = m % n;
}
n
}
// Writing unit tests
#[test] // It is an attribute:
// open-ended system for marking
// func and other declarations with extra information
fn gcd_returns_correct_value() {
assert_eq!(gcd(14, 15), 1);
assert_eq!(gcd(2 * 3 * 5 * 11 * 17, 3 * 7 * 11 * 13 * 19), 3 * 11);
}
fn get_index() -> HttpResponse {
HttpResponse::Ok().content_type("text/html").body(
r#"
<title>GCD Calculator</title>
<form action="/gcd" method="post">
<input type="text" name="n"/>
<input type="text" name="m"/>
<button type="submit">Compute GCD</button>
</form>
"#,
)
}
// Structure defined below represents the values expected
// from a web-form
#[derive(Deserialize)] // the attribute tells the `serde` crate
// to exemine below type when the program is compiled
// and automatically generate code to parse a value
// of this type from data in the format that HTML forms
// use for POST requests.
struct GcdParams {
n: u64,
m: u64,
}
fn post_gcd(form: web::Form<GcdParams>) -> HttpResponse {
if form.n == 0 || form.m == 0 {
return HttpResponse::BadRequest()
.content_type("text/html")
.body("Computing the GCD with zero is boring.");
}
// the `format!` macro is just like `println!`, except that instead of writing
// the text to the stdout, it returns is is a string.
let response = format!(
"The greatest common divisor of the numbers {} and {} \
is <b>{}</b>\n",
form.n,
form.m,
gcd(form.n, form.m)
);
HttpResponse::Ok().content_type("text/html").body(response)
}
| true |
67a0e424e92b74dd66dc021e7d77fe5264e424b4
|
Rust
|
skyne98/soap
|
/example/town.rs
|
UTF-8
| 8,306 | 2.796875 | 3 |
[] |
no_license
|
use anyhow::Result;
use serde_json::{Number, Value};
use soap::{
action::{Action, Consequence},
field::Field,
goal::Goal,
planner::plan,
requirement::CompareRequirement,
state::State,
};
// Chop wood
pub struct ChopAction {}
impl Action for ChopAction {
fn key(&self) -> String {
"chop".to_owned()
}
fn prepare(&self, state: &State) -> State {
let mut prepared_state = state.clone();
if prepared_state.contains_key("wood") == false {
prepared_state = prepared_state.with_field("wood", Field::from(0u64));
}
if prepared_state.contains_key("axe") == false {
prepared_state = prepared_state.with_field("axe", Field::from(false));
}
prepared_state
}
fn options(&self, state: &State) -> Vec<(Consequence, u64)> {
let wood = state.get_as_u64("wood").unwrap_or(0);
let axe = state.get_as_bool("axe").unwrap_or(false);
if axe {
vec![
(
Consequence {
action: self.key(),
argument: None,
result: state.with_field("wood", Field::from(wood + 2)),
},
1,
),
(
Consequence {
action: self.key(),
argument: None,
result: state.with_field("wood", Field::from(wood + 8)),
},
4,
),
]
} else {
vec![]
}
}
}
// Collect
pub struct CollectAction {}
impl Action for CollectAction {
fn key(&self) -> String {
"collect".to_owned()
}
fn prepare(&self, state: &State) -> State {
let mut prepared_state = state.clone();
if prepared_state.contains_key("shrooms") == false {
prepared_state = prepared_state.with_field("shrooms", Field::from(0u64));
}
prepared_state
}
fn options(&self, state: &State) -> Vec<(Consequence, u64)> {
let shrooms = state.get_as_u64("shrooms").unwrap_or(0);
vec![(
Consequence {
action: self.key(),
argument: Some(Value::from("shrooms")),
result: state.with_field("shrooms", Field::from(shrooms + 1)),
},
1,
)]
}
}
// Buy
pub struct BuyAction {}
impl Action for BuyAction {
fn key(&self) -> String {
"buy".to_owned()
}
fn prepare(&self, state: &State) -> State {
let mut prepared_state = state.clone();
if prepared_state.contains_key("coins") == false {
prepared_state = prepared_state.with_field("coins", Field::from(0u64));
}
if prepared_state.contains_key("axe") == false {
prepared_state = prepared_state.with_field("axe", Field::from(false));
}
if prepared_state.contains_key("shrooms") == false {
prepared_state = prepared_state.with_field("shrooms", Field::from(0u64));
}
if prepared_state.contains_key("wood") == false {
prepared_state = prepared_state.with_field("wood", Field::from(0u64));
}
prepared_state
}
fn options(&self, state: &State) -> Vec<(Consequence, u64)> {
let coins = state.get_as_u64("coins").unwrap_or(0);
let mut consequences = vec![];
if coins > 2 {
consequences.push((
Consequence {
action: self.key(),
argument: Some(Value::from("axe")),
result: state
.with_field("axe", Field::from(true))
.with_field("coins", Field::from(coins - 2)),
},
1,
));
}
consequences
}
}
// Sell
pub struct SellAction {}
impl Action for SellAction {
fn key(&self) -> String {
"sell".to_owned()
}
fn prepare(&self, state: &State) -> State {
let mut prepared_state = state.clone();
if prepared_state.contains_key("coins") == false {
prepared_state = prepared_state.with_field("coins", Field::from(0u64));
}
if prepared_state.contains_key("axe") == false {
prepared_state = prepared_state.with_field("axe", Field::from(false));
}
if prepared_state.contains_key("shrooms") == false {
prepared_state = prepared_state.with_field("shrooms", Field::from(0u64));
}
if prepared_state.contains_key("wood") == false {
prepared_state = prepared_state.with_field("wood", Field::from(0u64));
}
prepared_state
}
fn options(&self, state: &State) -> Vec<(Consequence, u64)> {
let coins = state.get_as_u64("coins").unwrap_or(0);
let wood = state.get_as_u64("wood").unwrap_or(0);
let shrooms = state.get_as_u64("shrooms").unwrap_or(0);
let axe = state.get_as_bool("axe").unwrap_or(false);
let mut consequences = vec![];
if wood > 1 {
consequences.push((
Consequence {
action: self.key(),
argument: Some(Value::from("wood")),
result: state
.with_field("wood", Field::from(wood - 1))
.with_field("coins", Field::from(coins + 3)),
},
1,
));
consequences.push((
Consequence {
action: self.key(),
argument: Some(Value::from("wood")),
result: state
.with_field("wood", Field::from(0u64))
.with_field("coins", Field::from(coins + wood * 3)),
},
1,
));
}
if shrooms > 1 {
consequences.push((
Consequence {
action: self.key(),
argument: Some(Value::from("shrooms")),
result: state
.with_field("shrooms", Field::from(shrooms - 1))
.with_field("coins", Field::from(coins + 1)),
},
1,
));
consequences.push((
Consequence {
action: self.key(),
argument: Some(Value::from("shrooms")),
result: state
.with_field("shrooms", Field::from(0u64))
.with_field("coins", Field::from(coins + shrooms)),
},
1,
));
}
if axe {
consequences.push((
Consequence {
action: self.key(),
argument: Some(Value::from("axe")),
result: state
.with_field("axe", Field::from(false))
.with_field("coins", Field::from(coins + 1)),
},
1,
));
}
consequences
}
}
fn main() -> Result<()> {
pretty_env_logger::init();
let start = State::new();
let goal = Goal::new()
.with_req(
"coins",
Box::new(CompareRequirement::MoreThanEquals(Field::from(10u64))),
)
.with_req(
"wood",
Box::new(CompareRequirement::Equals(Field::from(10u64))),
)
.with_req(
"shrooms",
Box::new(CompareRequirement::Equals(Field::from(2u64))),
);
let actions: Vec<Box<dyn Action>> = vec![
Box::new(ChopAction {}),
Box::new(BuyAction {}),
Box::new(SellAction {}),
Box::new(CollectAction {}),
];
println!("Start: {:#?}", start);
println!("Goal: {:#?}", goal);
println!("-------------------------------------");
let start_time = std::time::Instant::now();
let plan = plan(&start, &actions[..], &goal);
let done_in = std::time::Instant::now().duration_since(start_time);
println!("Plan: {:#?}", plan);
println!(
"Done in {} ms ({} μs)",
done_in.as_millis(),
done_in.as_micros()
);
Ok(())
}
| true |
2dad904dfd79aa911a20b7f87edda2e1e5c2954f
|
Rust
|
komkomh/hello_rust_world
|
/src/main.rs
|
UTF-8
| 172 | 2.59375 | 3 |
[] |
no_license
|
//use std::collections::HashMap;
fn main() {
println!("Hello, world!");
// let mut map = HashMap::new();
// map.insert("kkk".to_string(), "kkk".to_string());
}
| true |
f05da2cbc848b62f925e44e02c5296a181ef4009
|
Rust
|
TimeExceed/tianyi
|
/src/rtask/factory.rs
|
UTF-8
| 3,671 | 2.921875 | 3 |
[] |
no_license
|
use std::collections::BTreeMap;
use super::*;
pub trait Factory {
fn init(&self) -> Vec<Box<dyn RTask + Send>>;
fn recover(
&self,
snapshot: BTreeMap<RTaskId, RecoveredData>,
) -> (Progress, Vec<Box<dyn RTask + Send>>);
}
#[derive(Debug, Clone, Default)]
pub struct RecoveredData {
pub init: Bytes,
pub result: Option<Bytes>,
}
impl std::convert::TryFrom<avro_rs::types::Value> for RecoveredData {
type Error = Error;
fn try_from(x: avro_rs::types::Value) -> Result<Self, Self::Error> {
let xs = match x {
avro_rs::types::Value::Record(xs) => xs,
x @ _ => {
return Err(Error::RecoverData(x));
}
};
let mut map: BTreeMap<_, _> = xs.into_iter().collect();
let mut res = Self::default();
if let Some(v) = map.remove("init") {
match v {
avro_rs::types::Value::Bytes(v) => {
res.init = Bytes::from(v);
}
v @ _ => {
return Err(Error::RecoverData(v));
}
}
} else {
return Err(Error::from_message(r#"field "init" is required."#));
}
if let Some(v) = map.remove("result") {
let v = match v {
avro_rs::types::Value::Union(v) => v,
v @ _ => {
return Err(Error::RecoverData(v));
}
};
match v.as_ref() {
&avro_rs::types::Value::Bytes(ref v) => {
res.result = Some(Bytes::from(v.clone()));
},
&avro_rs::types::Value::Null => {},
v @ _ => {
return Err(Error::RecoverData(v.clone()));
}
};
} else {
return Err(Error::from_message(r#"field "result" is required."#));
}
Ok(res)
}
}
pub trait FactoryForDefaultImpl {
fn init(&self) -> Vec<Box<dyn RTask + Send>>;
fn recover_completed(
&self,
id: RTaskId,
init: &[u8],
result: &[u8],
) -> Progress;
fn recover_incompleted(
&self,
id: RTaskId,
init: &[u8],
) -> Box<dyn RTask + Send>;
}
pub struct DefaultImplFactory<Fac: FactoryForDefaultImpl + Send> {
fac: Fac,
}
impl<Fac: FactoryForDefaultImpl + Send> DefaultImplFactory<Fac> {
pub fn new(fac: Fac) -> Self {
Self{
fac,
}
}
}
impl<Fac: FactoryForDefaultImpl + Send> Factory for DefaultImplFactory<Fac> {
fn init(&self) -> Vec<Box<dyn RTask + Send>> {
self.fac.init()
}
fn recover(
&self,
snapshot: BTreeMap<RTaskId, RecoveredData>,
) -> (Progress, Vec<Box<dyn RTask + Send>>) {
let mut incompleted = BTreeMap::<RTaskId, Box<dyn RTask + Send>>::new();
let mut progress = Progress::default();
for (id, rdata) in snapshot.iter() {
if let Some(result) = &rdata.result {
let id = id.clone();
let prog = self.fac.recover_completed(
id,
rdata.init.as_ref(),
result);
progress += &prog;
} else {
let id = id.clone();
let task = self.fac.recover_incompleted(
id.clone(),
rdata.init.as_ref());
incompleted.insert(id, task);
}
}
let incompleted: Vec<_> = incompleted.into_iter()
.map(|(_, v)| v)
.collect();
(progress, incompleted)
}
}
| true |
d9a0ab994c3b92cc6b3d2257ea62880b39a71919
|
Rust
|
tomdewildt/rust-basics
|
/src/types.rs
|
UTF-8
| 1,227 | 3.984375 | 4 |
[
"MIT"
] |
permissive
|
// Primitive types
// Integers: u8, i8, u16, i16, u32, i32, u64, i64, u128, i128
// Floats: f32, f64
// Booleans: bool
// Characters: char
// Rust is a statically type language, which means that it must know the types of all
// variables at compile time, however, the compiler can usually infer what type we
// want to use based on the value and how we use it.
pub fn main() {
// Integer default is "i32"
let integer = 1;
println!("Integer default is i32: {}", integer);
// Float default is "f64"
let float = 2.5;
println!("Float default is f64: {}", float);
// Integer with explicit type
let integer64: i64 = 45454545454545;
println!("Integer with explicit type: {}", integer64);
// Find max size
println!("Find max size of i32: {}", std::i32::MAX);
println!("Find max size of i64: {}", std::i64::MAX);
// Boolean
let boolean = true;
println!("Boolean: {}", boolean);
// Get boolean from expression
let expression = 10 > 5;
println!("Get boolean from expression: {}", expression);
// Character
let character = 'a';
let unicode = '\u{1F600}';
println!("Character: {}", character);
println!("Unicode character: {}", unicode);
}
| true |
080b73ff3d1fa445ef9f5e7b71cf1d818760073b
|
Rust
|
adrianchitescu/aoc2019-rs
|
/day21/src/main.rs
|
UTF-8
| 1,307 | 3.1875 | 3 |
[] |
no_license
|
extern crate int_computer;
use std::env;
use int_computer::computer::*;
fn display(computer: &mut Computer) {
computer.run();
let last = computer.get_exit_value();
let output: Vec<i128> = computer.get_all_output();
for c in output {
print!("{}", (c as u8) as char);
}
println!("{:?}", last);
}
fn run(computer: &mut Computer, script: &Vec<&str>) {
script
.iter()
.for_each(|s| {
for c in s.chars() {
computer.add_input(c as i32);
}
computer.add_input(10);
});
display(computer);
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut computer = Computer::new_from_file(&args[1]);
let mut computer2 = Computer::new_from_file(&args[1]);
// J = !(A & B & C) & D
run(&mut computer, &vec![
"OR A J",
"AND B J",
"AND C J",
"NOT J J",
"AND D J",
"WALK"
]);
// JUMP if part1 conditions are true and E is solid or H is solid so the next jump is valid
// J = !(A & B & C) & D & (E | H)
run(&mut computer2, &vec![
"OR A J",
"AND B J",
"AND C J",
"NOT J J",
"AND D J",
"OR E T",
"OR H T",
"AND T J",
"RUN"
]);
}
| true |
a8930832c6e0997a4f5cc7ed7d1611eb80b9ee61
|
Rust
|
chapterzero/async-pq
|
/src/protocols/stream.rs
|
UTF-8
| 1,032 | 2.8125 | 3 |
[] |
no_license
|
use async_std::net::TcpStream;
use async_std::prelude::*;
const DEF_BUF_LEN: usize = 32;
pub async fn read_from_backend(stream: &mut TcpStream) -> Result<Vec<u8>, std::io::Error> {
read_from_backend_buf(stream, DEF_BUF_LEN).await
}
pub async fn read_from_backend_buf(
stream: &mut TcpStream,
buf_size: usize,
) -> Result<Vec<u8>, std::io::Error> {
// // first byte indicate the response type (either R / E)
// // 2nd u32 indicate message length (not including the first byte)
let mut v = Vec::with_capacity(buf_size);
let mut known_len: Option<usize> = None;
loop {
let mut buf = vec![0u8; buf_size];
let n = stream.read(&mut buf).await?;
if known_len.is_none() {
let mut msg_len = [0u8; 4];
msg_len.copy_from_slice(&buf[1..5]);
known_len = Some(u32::from_be_bytes(msg_len) as usize)
}
v.extend(&buf[..n]);
if n < buf_size || v.len() - 1 == (known_len.unwrap()) {
break
}
}
Ok(v)
}
| true |
eb56874ae828e721b3267f80b13280855e4ea34f
|
Rust
|
task-rs/task-rs
|
/crates/task-rs/src/utils/data.rs
|
UTF-8
| 691 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
use super::super::{
config::{Config, Source as CfgSrc},
data::Data,
utils::deserialize_file,
};
pub fn from_cfg_opt(config: &Option<(Config, CfgSrc)>) -> Data {
if let Some((
Config {
local_repo_location,
..
},
_,
)) = config
{
match deserialize_file(&local_repo_location) {
Ok(data) => data,
Err(error) => {
eprintln!(
"Failed to load {}: {}",
local_repo_location.to_string_lossy(),
error
);
Data::default()
}
}
} else {
Data::default()
}
}
| true |
6b6c03e9812e00b8db2fbf5e2fd0ada3492a72a9
|
Rust
|
Vicfred/codeforces-rust
|
/petyastrings.rs
|
UTF-8
| 487 | 3.15625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
// https://codeforces.com/problemset/problem/112/A
use std::io;
fn main() {
let mut first = String::new();
io::stdin().read_line(&mut first).unwrap();
let first = first.to_ascii_lowercase();
let mut second = String::new();
io::stdin().read_line(&mut second).unwrap();
let second = second.to_ascii_lowercase();
if first < second {
println!("-1");
} else if first > second {
println!("1");
} else {
println!("0");
}
}
| true |
cee12129aad963e7c1b6c8c66bc4b9fe2e364b2d
|
Rust
|
yjv/rust_fixed_width
|
/src/spec/loader/yaml.rs
|
UTF-8
| 10,882 | 2.75 | 3 |
[] |
no_license
|
extern crate yaml_rust;
use self::yaml_rust::{Yaml};
use std::io::prelude::*;
use std::collections::BTreeMap;
use spec::{Builder, FieldSpec, FieldSpecBuilder, RecordSpec, RecordSpecBuilder, Spec, SpecBuilder, PaddingDirection};
use super::BoxedErrorResult;
use std::fmt::{Display, Formatter, Error as FmtError};
pub struct YamlLoader;
impl<'a, T: 'a + Read> super::Loader<&'a mut T> for YamlLoader {
fn load(&self, resource: &'a mut T) -> BoxedErrorResult<Spec> {
let mut docs = Self::read_reader(resource)?;
if docs.len() == 0 {
return Err(Error::NoDocumentsFound.into());
}
Self::read_spec(docs.remove(0))
}
}
impl YamlLoader {
fn read_spec(doc: Yaml) -> BoxedErrorResult<Spec> {
let mut builder = SpecBuilder::new();
let records = Self::get_hash(Self::get_hash(doc, None)?
.remove(&Yaml::String("records".to_string()))
.ok_or(Error::missing_key("records", None))?, Some(&["records"]))?
;
for (name, record_spec_data) in records {
let path = &["records"];
let name = Self::get_string(name, Some(path))?;
let record_spec = Self::get_record_spec(record_spec_data, &name)?;
builder = builder.add_record(name, record_spec);
}
Ok(builder.build().map_err(Error::BuilderError)?)
}
fn read_reader<'a, T: 'a + Read>(resource: &'a mut T) -> BoxedErrorResult<Vec<Yaml>> {
let mut contents = String::new();
resource.read_to_string(&mut contents)?;
Ok(yaml_rust::YamlLoader::load_from_str(&contents)?)
}
fn get_field_spec<'a>(field_spec_data: Yaml, name: &'a str, field_name: &'a str) -> Result<FieldSpec, Error> {
let path = &["records", name, "fields", &field_name];
let mut field_spec_map = Self::get_hash(field_spec_data, Some(path))?;
let builder = FieldSpecBuilder::new()
.with_length(field_spec_map
.remove(&Yaml::String("length".to_string()))
.map(|v| Self::get_usize(v, Some(path)))
.unwrap_or_else(|| Err(Error::missing_key("length", Some(path))))?
)
.with_padding_direction(field_spec_map
.remove(&Yaml::String("padding_direction".to_string()))
.map(|v| Self::get_padding_direction(v, Some(path)))
.unwrap_or_else(|| Err(Error::missing_key("padding_direction", Some(path))))?
)
.with_padding(field_spec_map
.remove(&Yaml::String("padding".to_string()))
.map(|v| Self::get_bytes(v, Some(path)))
.unwrap_or_else(|| Ok(Vec::new()))?
)
;
let builder = match field_spec_map.remove(&Yaml::String("default".to_string())) {
Some(v) => builder.with_default(Self::get_bytes(v, Some(path))?),
_ => builder
};
Ok(builder.build().map_err(Error::BuilderError)?)
}
fn get_record_spec<'a>(record_spec_data: Yaml, name: &'a str) -> Result<RecordSpec, Error> {
let path = &["records", &name];
let mut record_spec_data = Self::get_hash(record_spec_data, Some(path))?;
let mut builder = RecordSpecBuilder::new();
let path = &["records", &name, "fields"];
let fields = Self::get_hash(record_spec_data.remove(&Yaml::String("fields".to_string())).ok_or(Error::missing_key("records", Some(path)))?, Some(path))?;
for (field_name, field_spec_data) in fields {
let field_name = Self::get_string(field_name, Some(path))?;
let field_spec = Self::get_field_spec(field_spec_data, &name, &field_name)?;
builder = builder.add_field(field_name, field_spec);
}
Ok(builder
.with_line_ending(record_spec_data.remove(&Yaml::String("line_ending".to_string())).map(|v| Self::get_bytes(v, Some(path))).unwrap_or_else(|| Ok(Vec::new()))?)
.build().map_err(Error::BuilderError)?
)
}
fn get_hash<'a, 'b>(value: Yaml, path: Option<&'a [&'b str]>) -> Result<BTreeMap<Yaml, Yaml>, Error> {
match value {
Yaml::Hash(v) => Ok(v),
_ => Err(Error::invalid_type(value, "Hash", path))
}
}
fn get_string<'a, 'b>(value: Yaml, path: Option<&'a [&'b str]>) -> Result<String, Error> {
match value {
Yaml::String(v) => Ok(v),
Yaml::Integer(v) => Ok(v.to_string()),
_ => Err(Error::invalid_type(value, "String", path))
}
}
fn get_bytes<'a, 'b>(value: Yaml, path: Option<&'a [&'b str]>) -> Result<Vec<u8>, Error> {
Self::get_string(value, path).map(String::into_bytes)
}
fn get_usize<'a, 'b>(value: Yaml, path: Option<&'a [&'a str]>) -> Result<usize, Error> {
match value {
Yaml::Integer(v) => Ok(v as usize),
_ => Err(Error::invalid_type(value, "Integer", path))
}
}
fn get_padding_direction<'a, 'b>(value: Yaml, path: Option<&'a [&'b str]>) -> Result<PaddingDirection, Error> {
match value {
Yaml::String(ref v) if v == "right" => Ok(PaddingDirection::Right),
Yaml::String(ref v) if v == "Right" => Ok(PaddingDirection::Right),
Yaml::String(ref v) if v == "left" => Ok(PaddingDirection::Left),
Yaml::String(ref v) if v == "Left" => Ok(PaddingDirection::Left),
_ => Err(Error::invalid_type(value, "String: right, Right, left, Left", path))
}
}
}
#[derive(Debug)]
pub enum Error {
NoDocumentsFound,
MissingKey { key: &'static str, path: Option<String> },
InvalidType { value: Yaml, expected_type: &'static str, path: Option<String> },
BuilderError(super::super::Error)
}
impl Error {
fn missing_key<'a, 'b>(key: &'static str, path: Option<&'a [&'b str]>) -> Self {
Error::MissingKey {
key: key,
path: path.map(Self::normalize_path)
}
}
fn invalid_type<'a, 'b>(value: Yaml, expected_type: &'static str, path: Option<&'a [&'b str]>) -> Self {
Error::InvalidType {
value: value,
expected_type: expected_type,
path: path.map(Self::normalize_path)
}
}
fn normalize_path<'a, 'b>(path: &'a [&'b str]) -> String {
let mut string = String::new();
for element in path {
string.push_str(element);
}
string
}
}
impl ::std::error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::NoDocumentsFound => "The resource at the given path has no documents in it",
Error::MissingKey { .. } => "There is a key missing",
Error::InvalidType { .. } => "The type is wrong",
Error::BuilderError(_) => "The spec builder had an error"
}
}
fn cause(&self) -> Option<&::std::error::Error> {
match *self {
Error::BuilderError(ref e) => Some(e),
_ => None
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> ::std::result::Result<(), FmtError> {
match *self {
Error::NoDocumentsFound => write!(f, "The resource at the given path has no documents in it"),
Error::MissingKey { ref key, path: Some(ref path) } => write!(f, "There is a key {} missing under key {}", key, path),
Error::MissingKey { ref key, path: None } => write!(f, "There is a key {} missing", key),
Error::InvalidType { ref value, ref expected_type, path: Some(ref path) } => write!(f, "The value {:?} at path {} has the wrong type. The expected type was {}", value, path, expected_type),
Error::InvalidType { ref value, ref expected_type, path: None } => write!(f, "The value {:?} has the wrong type. The expected type was {}", value, expected_type),
Error::BuilderError(ref e) => write!(f, "The spec builder had an error: {}", e)
}
}
}
#[cfg(test)]
mod test {
use super::YamlLoader;
use spec::loader::Loader;
use spec::{RecordSpecBuilder, SpecBuilder, FieldSpecBuilder, PaddingDirection, Builder};
use std::fs::File;
#[test]
fn read_record() {
let loader = YamlLoader;
let spec = SpecBuilder::new()
.add_record(
"record1",
RecordSpecBuilder::new()
.with_line_ending([92, 110].as_ref())
.add_field(
"$id",
FieldSpecBuilder::new()
.with_length(2)
.with_padding_direction(PaddingDirection::Right)
.with_default([51, 52].as_ref())
)
.add_field(
"field1",
FieldSpecBuilder::new()
.with_length(10)
.with_padding_direction(PaddingDirection::Left)
.with_padding([32].as_ref())
.with_default([104, 101, 108, 108, 111].as_ref())
)
.add_field(
"field2",
FieldSpecBuilder::new()
.with_length(23)
.with_padding_direction(PaddingDirection::Right)
.with_default([103, 111, 111, 100, 98, 121, 101].as_ref())
)
)
.add_record(
"record2",
RecordSpecBuilder::new()
.with_line_ending([92, 110].as_ref())
.add_field(
"$id",
FieldSpecBuilder::new()
.with_length(5)
.with_padding_direction(PaddingDirection::Right)
.with_default([51, 52].as_ref())
)
.add_field(
"field1",
FieldSpecBuilder::new()
.with_length(12)
.with_padding_direction(PaddingDirection::Left)
.with_padding([32].as_ref())
.with_default([104, 101, 108, 108, 111].as_ref())
)
.add_field(
"field2",
FieldSpecBuilder::new()
.with_length(67)
.with_padding_direction(PaddingDirection::Right)
.with_default([103, 111, 111, 100, 98, 121, 101].as_ref())
)
)
.build()
.unwrap()
;
assert_eq!(spec, loader.load(&mut File::open("src/spec/loader/spec.yml").unwrap()).unwrap());
}
}
| true |
47fc73e7f35e3302c821dab051a9cc384b48fcbb
|
Rust
|
katharostech/parry
|
/src/query/ray/ray_ball.rs
|
UTF-8
| 2,521 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use na::{self, ComplexField};
use crate::math::{Point, Real};
use crate::query::{Ray, RayCast, RayIntersection};
use crate::shape::{Ball, FeatureId};
use num::Zero;
impl RayCast for Ball {
#[inline]
fn cast_local_ray(&self, ray: &Ray, max_toi: Real, solid: bool) -> Option<Real> {
ray_toi_with_ball(&Point::origin(), self.radius, ray, solid)
.1
.filter(|toi| *toi <= max_toi)
}
#[inline]
fn cast_local_ray_and_get_normal(
&self,
ray: &Ray,
max_toi: Real,
solid: bool,
) -> Option<RayIntersection> {
ray_toi_and_normal_with_ball(&Point::origin(), self.radius, ray, solid)
.1
.filter(|int| int.toi <= max_toi)
}
}
/// Computes the time of impact of a ray on a ball.
///
/// The first result element is `true` if the ray started inside of the ball.
#[inline]
pub fn ray_toi_with_ball(
center: &Point<Real>,
radius: Real,
ray: &Ray,
solid: bool,
) -> (bool, Option<Real>) {
let dcenter = ray.origin - *center;
let a = ray.dir.norm_squared();
let b = dcenter.dot(&ray.dir);
let c = dcenter.norm_squared() - radius * radius;
// Special case for when the dir is zero.
if a.is_zero() {
if c > 0.0 {
return (false, None);
} else {
return (true, Some(0.0));
}
}
if c > 0.0 && b > 0.0 {
(false, None)
} else {
let delta = b * b - a * c;
if delta < 0.0 {
// no solution
(false, None)
} else {
let t = (-b - ComplexField::sqrt(delta)) / a;
if t <= 0.0 {
// origin inside of the ball
if solid {
(true, Some(0.0))
} else {
(true, Some((-b + delta.sqrt()) / a))
}
} else {
(false, Some(t))
}
}
}
}
/// Computes the time of impact and contact normal of a ray on a ball.
#[inline]
pub fn ray_toi_and_normal_with_ball(
center: &Point<Real>,
radius: Real,
ray: &Ray,
solid: bool,
) -> (bool, Option<RayIntersection>) {
let (inside, inter) = ray_toi_with_ball(¢er, radius, ray, solid);
(
inside,
inter.map(|n| {
let pos = ray.origin + ray.dir * n - center;
let normal = pos.normalize();
RayIntersection::new(n, if inside { -normal } else { normal }, FeatureId::Face(0))
}),
)
}
| true |
3298227f8362542bbf5544e30b6a3470011c434a
|
Rust
|
PeterCxy/cs140e-2-fs
|
/fat32/src/vfat/file.rs
|
UTF-8
| 2,291 | 3.03125 | 3 |
[] |
no_license
|
use std::cmp::{min, max};
use std::io::{self, SeekFrom};
use traits;
use vfat::{VFat, VFatExt, Shared, Cluster, Metadata};
#[derive(Debug)]
pub struct File {
pub drive: Shared<VFat>,
pub cluster: Cluster,
pub name: String,
pub metadata: Metadata,
pub size: u64,
pub offset: u64
}
impl File {
fn set_offset(&mut self, pos: u64) -> io::Result<u64> {
if pos > self.size {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Cannot seek beyond file end"))
} else {
self.offset = pos;
Ok(self.offset)
}
}
}
impl traits::File for File {
fn sync(&mut self) -> io::Result<()> {
unimplemented!();
}
fn size(&self) -> u64 {
self.size as u64
}
}
impl io::Seek for File {
/// Seek to offset `pos` in the file.
///
/// A seek to the end of the file is allowed. A seek _beyond_ the end of the
/// file returns an `InvalidInput` error.
///
/// If the seek operation completes successfully, this method returns the
/// new position from the start of the stream. That position can be used
/// later with SeekFrom::Start.
///
/// # Errors
///
/// Seeking before the start of a file or beyond the end of the file results
/// in an `InvalidInput` error.
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
let cur_offset = self.offset;
let cur_size = self.size;
match pos {
SeekFrom::Start(p) => self.set_offset(p),
SeekFrom::Current(p) => self.set_offset(((cur_offset as i64) + p) as u64),
SeekFrom::End(p) => self.set_offset(((cur_size as i64) - 1 + p) as u64)
}
}
}
impl io::Read for File {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
use std::io::Seek;
let max_len = min((self.size - self.offset) as usize, buf.len());
let read_bytes = self.drive.read_cluster(self.cluster, self.offset as usize, &mut buf[..max_len])?;
self.seek(SeekFrom::Current(read_bytes as i64))?;
Ok(read_bytes)
}
}
impl io::Write for File {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
unimplemented!();
}
fn flush(&mut self) -> io::Result<()> {
unimplemented!();
}
}
| true |
bf905f16e6598e46f1132af34ba12cb19e328267
|
Rust
|
HanMeh/byte
|
/tests/lib.rs
|
UTF-8
| 9,511 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#[macro_use]
extern crate quickcheck;
extern crate byte;
extern crate byteorder;
use byte::ctx::*;
use byte::*;
use byteorder::*;
#[test]
fn test_str() {
let bytes: &[u8] = b"abcd\0efg";
let mut offset = 0;
assert_eq!(
bytes
.read_with::<&str>(&mut offset, Str::Delimiter(NULL))
.unwrap(),
"abcd"
);
assert_eq!(offset, 5);
let bytes: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
assert_eq!(
TryRead::try_read(bytes, Str::Len(15)).unwrap(),
("abcdefghijklmno", 15)
);
assert_eq!(
TryRead::try_read(bytes, Str::Len(26)).unwrap(),
("abcdefghijklmnopqrstuvwxyz", 26)
);
assert!(bytes.read_with::<&str>(&mut 0, Str::Len(27)).is_err());
assert!(bytes.read_with::<&str>(&mut 27, Str::Len(0)).is_err());
assert!(bytes.read_with::<&str>(&mut 26, Str::Len(1)).is_err());
}
#[test]
fn test_str_delimitor() {
let bytes: &[u8] = b"";
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 0)).unwrap(),
("", 0)
);
let bytes: &[u8] = b"abcdefg";
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 6)).unwrap(),
("abcdef", 6)
);
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 7)).unwrap(),
("abcdefg", 7)
);
let bytes: &[u8] = b"\0abcdefg";
assert_eq!(
TryRead::try_read(bytes, Str::Delimiter(NULL)).unwrap(),
("", 1)
);
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 0)).unwrap(),
("", 0)
);
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 1)).unwrap(),
("", 1)
);
let bytes: &[u8] = b"abcd\0efg";
assert_eq!(
TryRead::try_read(bytes, Str::Delimiter(NULL)).unwrap(),
("abcd", 5)
);
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 4)).unwrap(),
("abcd", 4)
);
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 5)).unwrap(),
("abcd", 5)
);
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 6)).unwrap(),
("abcd", 5)
);
let bytes: &[u8] = b"abcdefg\0";
assert_eq!(
TryRead::try_read(bytes, Str::Delimiter(NULL)).unwrap(),
("abcdefg", 8)
);
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 8)).unwrap(),
("abcdefg", 8)
);
assert_eq!(
TryRead::try_read(bytes, Str::DelimiterUntil(NULL, 20)).unwrap(),
("abcdefg", 8)
);
let bytes: &[u8] = b"";
assert!(bytes
.read_with::<&str>(&mut 0, Str::Delimiter(NULL))
.is_err());
assert!(bytes
.read_with::<&str>(&mut 0, Str::DelimiterUntil(NULL, 1))
.is_err());
let bytes: &[u8] = b"abcdefg";
assert!(bytes
.read_with::<&str>(&mut 0, Str::DelimiterUntil(NULL, 8))
.is_err());
assert!(bytes
.read_with::<&str>(&mut 0, Str::Delimiter(NULL))
.is_err());
}
#[test]
fn test_str_write() {
let mut bytes = [0; 20];
let mut offset = 0;
bytes.write(&mut offset, "hello world!").unwrap();
assert_eq!(offset, 12);
assert_eq!(&bytes[..offset], b"hello world!" as &[u8]);
let bytes = &mut [0; 10];
assert!(bytes.write(&mut 0, "hello world!").is_err());
}
#[test]
fn test_bytes() {
let bytes: &[u8] = &[0xde, 0xad, 0xbe, 0xef];
assert_eq!(
TryRead::try_read(&bytes, Bytes::Len(4)).unwrap(),
(&bytes[..], 4)
);
assert!(bytes.read_with::<&[u8]>(&mut 5, Bytes::Len(0)).is_err());
let mut write = [0; 5];
assert_eq!(TryWrite::try_write(bytes, &mut write, ()).unwrap(), 4);
assert_eq!(&write[..4], bytes);
assert!([0u8; 3].write(&mut 0, bytes).is_err());
}
#[test]
fn test_bytes_pattern() {
let bytes: &[u8] = b"abcdefghijk";
assert_eq!(
TryRead::try_read(bytes, Bytes::Pattern(b"abc")).unwrap(),
(&b"abc"[..], 3)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::Pattern(b"cde")).unwrap(),
(&b"abcde"[..], 5)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::Pattern(b"jk")).unwrap(),
(&b"abcdefghijk"[..], 11)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::PatternUntil(b"abc", 3)).unwrap(),
(&b"abc"[..], 3)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::PatternUntil(b"abc", 4)).unwrap(),
(&b"abc"[..], 3)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::PatternUntil(b"cde", 3)).unwrap(),
(&b"abc"[..], 3)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::PatternUntil(b"cde", 4)).unwrap(),
(&b"abcd"[..], 4)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::PatternUntil(b"cde", 5)).unwrap(),
(&b"abcde"[..], 5)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::PatternUntil(b"cde", 6)).unwrap(),
(&b"abcde"[..], 5)
);
assert_eq!(
TryRead::try_read(bytes, Bytes::PatternUntil(b"xyz", 5)).unwrap(),
(&b"abcde"[..], 5)
);
assert!(bytes
.read_with::<&[u8]>(&mut 0, Bytes::Pattern(b"xyz"))
.is_err());
assert!(bytes
.read_with::<&[u8]>(&mut 0, Bytes::Pattern(b""))
.is_err());
assert!(bytes
.read_with::<&[u8]>(&mut 0, Bytes::PatternUntil(b"", 3))
.is_err());
assert!(bytes
.read_with::<&[u8]>(&mut 0, Bytes::PatternUntil(b"abcd", 3))
.is_err());
assert!(bytes
.read_with::<&[u8]>(&mut 0, Bytes::PatternUntil(b"xyz", 20))
.is_err());
let bytes: &[u8] = b"";
assert!(bytes
.read_with::<&[u8]>(&mut 0, Bytes::Pattern(b"xyz"))
.is_err());
assert!(bytes
.read_with::<&[u8]>(&mut 0, Bytes::PatternUntil(b"abc", 3))
.is_err());
assert!(bytes
.read_with::<&[u8]>(&mut 0, Bytes::PatternUntil(b"abc", 4))
.is_err());
}
#[test]
fn test_bool() {
let bytes = [0x00, 0x01, 0x80, 0xff];
assert_eq!(bytes.read::<bool>(&mut 0).unwrap(), false);
assert_eq!(bytes.read::<bool>(&mut 1).unwrap(), true);
assert_eq!(bytes.read::<bool>(&mut 2).unwrap(), true);
assert_eq!(bytes.read::<bool>(&mut 3).unwrap(), true);
let mut bytes = [0u8; 2];
bytes.write(&mut 0, false).unwrap();
bytes.write(&mut 1, true).unwrap();
assert!(bytes[0] == 0);
assert!(bytes[1] != 0);
}
#[test]
fn test_iter() {
let bytes: &[u8] = b"hello\0world\0dead\0beef\0more";
let mut offset = 0;
{
let mut iter = bytes.read_iter(&mut offset, Str::Delimiter(NULL));
assert_eq!(iter.next(), Some("hello"));
assert_eq!(iter.next(), Some("world"));
assert_eq!(iter.next(), Some("dead"));
assert_eq!(iter.next(), Some("beef"));
assert_eq!(iter.next(), None);
}
assert_eq!(offset, 22);
}
macro_rules! test_num {
($test_name: tt, $ty: ty, $byteorder_read_fn: tt, $byteorder_write_fn: tt) => {
quickcheck! {
fn $test_name (num: $ty) -> () {
let mut bytes = [0u8; 8];
bytes.write_with(&mut 0, num, LE).unwrap();
let result = LittleEndian::$byteorder_read_fn(&bytes);
assert_eq!(result, num);
let mut bytes = [0u8; 8];
LittleEndian::$byteorder_write_fn(&mut bytes, num);
let result: $ty = bytes.read_with(&mut 0, LE).unwrap();
assert_eq!(result, num);
let mut bytes = [0u8; 8];
bytes.write_with(&mut 0, num, BE).unwrap();
let result = BigEndian::$byteorder_read_fn(&bytes);
assert_eq!(result, num);
let mut bytes = [0u8; 8];
BigEndian::$byteorder_write_fn(&mut bytes, num);
let result: $ty = bytes.read_with(&mut 0, BE).unwrap();
assert_eq!(result, num);
}
}
};
}
test_num!(test_u16, u16, read_u16, write_u16);
test_num!(test_u32, u32, read_u32, write_u32);
test_num!(test_u64, u64, read_u64, write_u64);
test_num!(test_i16, i16, read_i16, write_i16);
test_num!(test_i32, i32, read_i32, write_i32);
test_num!(test_i64, i64, read_i64, write_i64);
test_num!(test_f32, f32, read_f32, write_f32);
test_num!(test_f64, f64, read_f64, write_f64);
struct Header<'a> {
name: &'a str,
enabled: bool,
}
impl<'a> TryRead<'a, Endian> for Header<'a> {
fn try_read(bytes: &'a [u8], endian: Endian) -> Result<(Self, usize)> {
let offset = &mut 0;
let name_len = bytes.read_with::<u16>(offset, endian)? as usize;
let header = Header {
name: bytes.read_with::<&str>(offset, Str::Len(name_len))?,
enabled: bytes.read(offset)?,
};
Ok((header, *offset))
}
}
impl<'a> TryWrite<Endian> for Header<'a> {
fn try_write(self, bytes: &mut [u8], endian: Endian) -> Result<usize> {
let offset = &mut 0;
bytes.write_with(offset, self.name.len() as u16, endian)?;
bytes.write(offset, self.name)?;
bytes.write(offset, self.enabled)?;
Ok(*offset)
}
}
#[test]
fn test_api() {
let bytes = [0, 5, b"H"[0], b"E"[0], b"L"[0], b"L"[0], b"O"[0], 0];
let header: Header = bytes.read_with(&mut 0, BE).unwrap();
assert_eq!(header.name, "HELLO");
assert_eq!(header.enabled, false);
let mut write = [0u8; 8];
write.write_with(&mut 0, header, BE).unwrap();
assert_eq!(write, bytes);
}
| true |
17dea5c309ddf0167acd511d8b39d35cf8f29476
|
Rust
|
RadeonGalwet/planets
|
/src/main.rs
|
UTF-8
| 4,286 | 2.84375 | 3 |
[] |
no_license
|
extern crate glutin_window;
extern crate graphics;
extern crate opengl_graphics;
extern crate piston;
use piston::{WindowSettings, Size, RenderArgs, EventSettings, Events, RenderEvent, UpdateEvent, UpdateArgs};
use glutin_window::{GlutinWindow as Window, OpenGL};
use opengl_graphics::GlGraphics;
use graphics::{clear, Transformed, circle_arc};
use graphics::color::{WHITE, BLACK};
use rand::{thread_rng, Rng};
use graphics::ellipse::circle;
use std::f64::consts::PI;
use graphics::types::Color;
use vecmath::{Vector2, vec2_len, vec2_dot, vec2_sub};
#[derive(PartialEq)]
struct Planet {
x: f64,
y: f64,
mass: f64,
color: Color,
vec: Vector2<f64>
}
struct App {
backend: GlGraphics,
planets: Vec<Planet>,
}
impl Planet {
pub fn radius(&self) -> f64 {
2.0 * self.mass
}
pub fn position(&self) -> Vector2<f64> {
[self.x, self.y]
}
pub fn influence(&mut self, b: &mut Self) {
let x = b.x - self.x;
let y = b.y - self.y;
let resistance = x.hypot(y);
let acceleration = b.mass / resistance.powf(2.0) / self.mass;
self.vec[0] += acceleration * x / resistance;
self.vec[1] += acceleration * y / resistance;
}
pub fn distance(&mut self, b: &mut Planet) -> f64 {
let (distance_x, distance_y) = (self.x - b.x, self.y - b.y);
distance_x.hypot(distance_y)
}
pub fn collision(&mut self, b: &mut Planet) -> bool {
self.distance(b) <= self.radius() * 2.0 + b.radius() * 2.0
}
pub fn movement(&mut self) {
self.x += self.vec[0];
self.y += self.vec[1];
}
}
impl App {
pub fn render(&mut self, render_args: &RenderArgs) {
let (x, y) = (render_args.window_size[0] / 2.0, render_args.window_size[1] / 2.0);
let planets = &self.planets;
self.backend.draw(render_args.viewport(), |context, backend| {
clear(WHITE, backend);
let transform = context.transform.trans(x, y);
for planet in planets {
let rect = circle(planet.x, planet.y, planet.radius());
circle_arc(planet.color, planet.radius(), 0.0, 2.0*PI, rect, transform, backend);
}
})
}
pub fn mass_update(&mut self) {
for idx in 0..self.planets.len() {
let (left, rest) = self.planets.split_at_mut(idx);
let (a, right) = rest.split_first_mut().unwrap();
let other_planets = left.iter_mut().chain(right);
for b in other_planets {
a.influence(b);
if a.collision(b) {
let x = a.vec[0] - b.vec[0];
let y = a.vec[1] - b.vec[1];
a.vec[0] = (a.vec[0] * (a.mass - b.mass) + (2.0 * b.mass * b.vec[0])) / (a.mass + b.mass);
a.vec[1] = (a.vec[1] * (a.mass - b.mass) + (2.0 * b.mass * b.vec[1])) / (a.mass + b.mass);
b.vec[0] = x + a.vec[0];
b.vec[1] = y + a.vec[1];
}
a.movement()
}
}
}
pub fn update(&mut self) {
self.mass_update();
}
}
fn random_color() -> Color {
let mut rng = thread_rng();
[rng.gen_range(0.0..1.0), rng.gen_range(0.0..1.0), rng.gen_range(0.0..1.0), 1.0]
}
fn main() {
let version = OpenGL::V4_5;
let window_size = Size {
width: 500.0,
height: 600.0
};
let mut window: Window = WindowSettings::new("Planets", window_size)
.exit_on_esc(false)
.graphics_api(version)
.samples(16)
.build()
.unwrap();
let mut app = App {
backend: GlGraphics::new(version),
planets: vec![Planet {x: 150.0, y: 15.0, mass: 15.0, color: random_color(), vec: [-0.07, 0.0]},
Planet {x: 225.0, y: 233.0, mass: 15.0, color: random_color(), vec: [0.07; 2]},
Planet {x: 300.0, y: 50.0, mass: 2.0, color: random_color(), vec: [0.15; 2]}
]
};
let mut events = Events::new(EventSettings::new());
while let Some(e) = events.next(&mut window) {
if let Some(args) = e.render_args() {
app.render(&args);
}
if let Some(_args) = e.update_args() {
app.update()
}
}
}
| true |
27f1645db877a79afc50f1b50beb505c58442bd9
|
Rust
|
marco-c/gecko-dev-wordified
|
/third_party/rust/hyper/src/headers.rs
|
UTF-8
| 4,443 | 2.796875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#
[
cfg
(
feature
=
"
http1
"
)
]
use
bytes
:
:
BytesMut
;
use
http
:
:
header
:
:
CONTENT_LENGTH
;
use
http
:
:
header
:
:
{
HeaderValue
ValueIter
}
;
use
http
:
:
HeaderMap
;
#
[
cfg
(
all
(
feature
=
"
http2
"
feature
=
"
client
"
)
)
]
use
http
:
:
Method
;
#
[
cfg
(
feature
=
"
http1
"
)
]
pub
(
super
)
fn
connection_keep_alive
(
value
:
&
HeaderValue
)
-
>
bool
{
connection_has
(
value
"
keep
-
alive
"
)
}
#
[
cfg
(
feature
=
"
http1
"
)
]
pub
(
super
)
fn
connection_close
(
value
:
&
HeaderValue
)
-
>
bool
{
connection_has
(
value
"
close
"
)
}
#
[
cfg
(
feature
=
"
http1
"
)
]
fn
connection_has
(
value
:
&
HeaderValue
needle
:
&
str
)
-
>
bool
{
if
let
Ok
(
s
)
=
value
.
to_str
(
)
{
for
val
in
s
.
split
(
'
'
)
{
if
val
.
trim
(
)
.
eq_ignore_ascii_case
(
needle
)
{
return
true
;
}
}
}
false
}
#
[
cfg
(
all
(
feature
=
"
http1
"
feature
=
"
server
"
)
)
]
pub
(
super
)
fn
content_length_parse
(
value
:
&
HeaderValue
)
-
>
Option
<
u64
>
{
from_digits
(
value
.
as_bytes
(
)
)
}
pub
(
super
)
fn
content_length_parse_all
(
headers
:
&
HeaderMap
)
-
>
Option
<
u64
>
{
content_length_parse_all_values
(
headers
.
get_all
(
CONTENT_LENGTH
)
.
into_iter
(
)
)
}
pub
(
super
)
fn
content_length_parse_all_values
(
values
:
ValueIter
<
'
_
HeaderValue
>
)
-
>
Option
<
u64
>
{
/
/
If
multiple
Content
-
Length
headers
were
sent
everything
can
still
/
/
be
alright
if
they
all
contain
the
same
value
and
all
parse
/
/
correctly
.
If
not
then
it
'
s
an
error
.
let
mut
content_length
:
Option
<
u64
>
=
None
;
for
h
in
values
{
if
let
Ok
(
line
)
=
h
.
to_str
(
)
{
for
v
in
line
.
split
(
'
'
)
{
if
let
Some
(
n
)
=
from_digits
(
v
.
trim
(
)
.
as_bytes
(
)
)
{
if
content_length
.
is_none
(
)
{
content_length
=
Some
(
n
)
}
else
if
content_length
!
=
Some
(
n
)
{
return
None
;
}
}
else
{
return
None
}
}
}
else
{
return
None
}
}
return
content_length
}
fn
from_digits
(
bytes
:
&
[
u8
]
)
-
>
Option
<
u64
>
{
/
/
cannot
use
FromStr
for
u64
since
it
allows
a
signed
prefix
let
mut
result
=
0u64
;
const
RADIX
:
u64
=
10
;
if
bytes
.
is_empty
(
)
{
return
None
;
}
for
&
b
in
bytes
{
/
/
can
'
t
use
char
:
:
to_digit
since
we
haven
'
t
verified
these
bytes
/
/
are
utf
-
8
.
match
b
{
b
'
0
'
.
.
=
b
'
9
'
=
>
{
result
=
result
.
checked_mul
(
RADIX
)
?
;
result
=
result
.
checked_add
(
(
b
-
b
'
0
'
)
as
u64
)
?
;
}
_
=
>
{
/
/
not
a
DIGIT
get
outta
here
!
return
None
;
}
}
}
Some
(
result
)
}
#
[
cfg
(
all
(
feature
=
"
http2
"
feature
=
"
client
"
)
)
]
pub
(
super
)
fn
method_has_defined_payload_semantics
(
method
:
&
Method
)
-
>
bool
{
match
*
method
{
Method
:
:
GET
|
Method
:
:
HEAD
|
Method
:
:
DELETE
|
Method
:
:
CONNECT
=
>
false
_
=
>
true
}
}
#
[
cfg
(
feature
=
"
http2
"
)
]
pub
(
super
)
fn
set_content_length_if_missing
(
headers
:
&
mut
HeaderMap
len
:
u64
)
{
headers
.
entry
(
CONTENT_LENGTH
)
.
or_insert_with
(
|
|
HeaderValue
:
:
from
(
len
)
)
;
}
#
[
cfg
(
feature
=
"
http1
"
)
]
pub
(
super
)
fn
transfer_encoding_is_chunked
(
headers
:
&
HeaderMap
)
-
>
bool
{
is_chunked
(
headers
.
get_all
(
http
:
:
header
:
:
TRANSFER_ENCODING
)
.
into_iter
(
)
)
}
#
[
cfg
(
feature
=
"
http1
"
)
]
pub
(
super
)
fn
is_chunked
(
mut
encodings
:
ValueIter
<
'
_
HeaderValue
>
)
-
>
bool
{
/
/
chunked
must
always
be
the
last
encoding
according
to
spec
if
let
Some
(
line
)
=
encodings
.
next_back
(
)
{
return
is_chunked_
(
line
)
;
}
false
}
#
[
cfg
(
feature
=
"
http1
"
)
]
pub
(
super
)
fn
is_chunked_
(
value
:
&
HeaderValue
)
-
>
bool
{
/
/
chunked
must
always
be
the
last
encoding
according
to
spec
if
let
Ok
(
s
)
=
value
.
to_str
(
)
{
if
let
Some
(
encoding
)
=
s
.
rsplit
(
'
'
)
.
next
(
)
{
return
encoding
.
trim
(
)
.
eq_ignore_ascii_case
(
"
chunked
"
)
;
}
}
false
}
#
[
cfg
(
feature
=
"
http1
"
)
]
pub
(
super
)
fn
add_chunked
(
mut
entry
:
http
:
:
header
:
:
OccupiedEntry
<
'
_
HeaderValue
>
)
{
const
CHUNKED
:
&
str
=
"
chunked
"
;
if
let
Some
(
line
)
=
entry
.
iter_mut
(
)
.
next_back
(
)
{
/
/
+
2
for
"
"
let
new_cap
=
line
.
as_bytes
(
)
.
len
(
)
+
CHUNKED
.
len
(
)
+
2
;
let
mut
buf
=
BytesMut
:
:
with_capacity
(
new_cap
)
;
buf
.
extend_from_slice
(
line
.
as_bytes
(
)
)
;
buf
.
extend_from_slice
(
b
"
"
)
;
buf
.
extend_from_slice
(
CHUNKED
.
as_bytes
(
)
)
;
*
line
=
HeaderValue
:
:
from_maybe_shared
(
buf
.
freeze
(
)
)
.
expect
(
"
original
header
value
plus
ascii
is
valid
"
)
;
return
;
}
entry
.
insert
(
HeaderValue
:
:
from_static
(
CHUNKED
)
)
;
}
| true |
8eedf6a57a770b3d0eddccac3ce999b5ab94fc63
|
Rust
|
steveklabnik/curl-rust
|
/src/test/simple.rs
|
UTF-8
| 473 | 2.75 | 3 |
[] |
no_license
|
use std::io::stdio::stdout;
use {get,request};
use super::server;
#[test]
pub fn test_simple_get() {
let srv = server!(
recv!("FOO"), // Send the data
send!("FOO")); // Sends
let res = get("http://localhost:8482");
stdout().write_str("Finishing request\n");
stdout().write_str(format!("res: {}", res).as_slice());
srv.assert();
stdout().write_str("Finished test\n");
// assert!(srv.recv());
// assert!(res.is_success());
// panic!("nope");
}
| true |
445c489753ef386d70e4c207c7e77adc31226fc3
|
Rust
|
wjzz/chess-in-rust
|
/src/bin/cmp_search_alg.rs
|
UTF-8
| 3,185 | 2.71875 | 3 |
[] |
no_license
|
use std::time;
use rust_chess::move_search::*;
use rust_chess::*;
#[derive(PartialEq)]
enum MoveSearcher {
Negamax,
AlphaBeta,
AlphaBetaIter,
PVS,
}
use MoveSearcher::*;
impl MoveSearcher {
pub fn evaluation(self: &Self, pos: &mut Position, depth: i32) -> (IntMove, f64) {
match self {
Negamax =>
negamax_top(pos, depth),
AlphaBeta =>
alphabeta_top(pos, depth),
AlphaBetaIter =>
alphabeta_iterative_deepening(pos, depth, false),
PVS =>
best_move_pvs(pos, depth),
}
}
pub fn name(self: &Self) -> String {
match self {
Negamax =>
format!("Negamax"),
AlphaBeta =>
format!("AlphaBeta"),
AlphaBetaIter =>
format!("AlphaBeta ItD"),
PVS =>
format!("PVS"),
}
}
}
fn main() {
let positions = [
//
"rnbqk1n1/8/pbp1p3/4N1pQ/1PB4p/2N4P/2P2PPB/3rR1K1 b q - 1 24",
// engine's blunder
"rnbqk1n1/3r4/pbp1p3/4N1p1/1PB4p/2N4P/2P1QPPB/3RR1K1 b q - 0 23",
// mate in 3
"2rk2r1/3p2rr/8/1Q3Q2/6B1/8/3Q4/K7 w - - 0 1",
// scholar's mate
"r1bqkbnr/ppp2ppp/2np4/4p3/2B1P3/5Q2/PPPP1PPP/RNB1K1NR w KQkq - 0 4",
// mate after a silent move
"3r2k1/5p1p/5Bp1/8/5Q2/8/PPPP4/1K6 w - - 0 1",
// starting
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
// random dynamic pos from chessbase blog
"r1b2r2/pp4k1/1bpp1q1p/5ppQ/2B2NN1/2P5/P5PP/R1B1R2K b - - 0 22",
// dynamic position, black in trouble
"rnbqk1nr/3p1ppp/1p1P4/p3p3/PbB5/2N2Q2/1PPBNPPP/2KRR3 b kq - 0 1",
// start of middle game
"rnbqk1nr/3p1ppp/1pp1p3/p2P4/PbB1P3/2N2Q2/1PPBNPPP/2KRR3 b kq - 0 11",
];
let searchers = [
// Negamax,
PVS,
AlphaBeta,
AlphaBetaIter,
];
for (i, fen) in positions.iter().enumerate() {
println!("#{} Comparing position {}", i+1, fen);
for depth in 1..=5 {
for searcher in searchers.iter() {
if depth >= 5 && *searcher == Negamax {
continue;
}
let mut pos = Position::from_fen(fen);
unsafe {
VISITED_NODES = 0;
};
let start = time::Instant::now();
let (mv, ev) = searcher.evaluation(&mut pos, depth);
let elapsed = start.elapsed();
let move_ascii = intmove_to_uci_ascii(mv);
let visited_nodes_safe = unsafe { VISITED_NODES };
let nodes_per_sec = visited_nodes_safe as f64 / elapsed.as_secs_f64() / 1000.0;
let elapsed_str = format!("{:.2?}", elapsed);
println!(
"{:15} d={} | {} | {:.1} | {:10} | {:>8} | {:.0} knps",
searcher.name(), depth, move_ascii, ev, visited_nodes_safe, elapsed_str, nodes_per_sec
);
}
println!();
}
// break;
}
}
| true |
6555f24b209ebc7b29d283113fad913081866952
|
Rust
|
AndrewScull/rust
|
/src/test/compile-fail/borrowck-partial-reinit-2.rs
|
UTF-8
| 912 | 2.875 | 3 |
[
"MIT",
"Apache-2.0",
"Unlicense",
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"bzip2-1.0.6",
"NCSA",
"ISC",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Copyright 2014-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.
struct Test {
a: isize,
b: Option<Box<Test>>,
}
impl Drop for Test {
fn drop(&mut self) {
println!("Dropping {}", self.a);
}
}
fn stuff() {
let mut t = Test { a: 1, b: None};
let mut u = Test { a: 2, b: Some(Box::new(t))};
t.b = Some(Box::new(u));
//~^ ERROR partial reinitialization of uninitialized structure `t`
println!("done");
}
fn main() {
stuff();
println!("Hello, world!")
}
| true |
677fce0b421c1e2119bb7a9d44d588a4808499e9
|
Rust
|
LuoZijun/sysctl-rs
|
/examples/struct.rs
|
UTF-8
| 1,573 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
#![allow(dead_code)]
#![allow(unused_imports)]
extern crate libc;
extern crate sysctl;
// Import the trait
use sysctl::Sysctl;
// Converted from definition in from /usr/include/sys/time.h
#[derive(Debug)]
#[repr(C)]
struct ClockInfo {
hz: libc::c_int, /* clock frequency */
tick: libc::c_int, /* micro-seconds per hz tick */
spare: libc::c_int,
stathz: libc::c_int, /* statistics clock frequency */
profhz: libc::c_int, /* profiling clock frequency */
}
#[cfg(any(target_os = "freebsd", target_os = "macos"))]
fn main() {
let ctl = sysctl::Ctl::new("kern.clockrate").expect("could not get sysctl: kern.clockrate");
let name = ctl.name().expect("could not get sysctl name");
println!("Read sysctl {} and parse result to struct ClockInfo", name);
let d = ctl.description().expect("could not get sysctl description");
println!("Description: {:?}", d);
let val_enum = ctl.value().expect("could not get sysctl value");
println!("ClockInfo raw data (byte array): {:?}", val_enum);
if let sysctl::CtlValue::Struct(val) = val_enum {
// Make sure we got correct data size
assert_eq!(std::mem::size_of::<ClockInfo>(), val.len());
let val_ptr: *const u8 = val.as_ptr();
let struct_ptr: *const ClockInfo = val_ptr as *const ClockInfo;
let struct_ref: &ClockInfo = unsafe { &*struct_ptr };
println!("{:?}", struct_ref);
}
}
#[cfg(not(any(target_os = "freebsd", target_os = "macos")))]
fn main() {
println!("This operation is only supported on FreeBSD and macOS.");
}
| true |
902007b8c7973e958b226e8521587dfb4c26c634
|
Rust
|
chamons/tldr-patch
|
/src/lib.rs
|
UTF-8
| 2,850 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::HashSet;
use std::io::Read;
use error_chain::error_chain;
use regex::Regex;
use std::result::Result as StdResult;
error_chain! {
foreign_links {
Io(std::io::Error);
HttpRequest(reqwest::Error);
Regex(regex::Error);
}
}
struct FileFilter {
filters: Option<Vec<Regex>>,
}
impl FileFilter {
pub fn init(filter: &Option<String>) -> Result<FileFilter> {
let filters: Option<Vec<Regex>> = if let Some(filter) = filter {
// error_chain's Result gave me grief here
let filters: StdResult<_, _> = std::fs::read_to_string(filter)?.lines().map(|l| Regex::new(l)).collect();
Some(filters?)
} else {
None
};
Ok(FileFilter { filters })
}
pub fn should_be_filtered(&self, file_name: &str) -> bool {
if file_name.contains("/dev/null") {
true
} else if let Some(filters) = &self.filters {
filters.iter().any(|f| f.is_match(file_name))
} else {
file_name.contains("Generated") || file_name.contains("SessionRecords")
}
}
}
fn patch_line_to_file_name(line: &str) -> &str {
let file = &line[4..];
if file.starts_with("a/") || file.starts_with("b/") {
&file[2..]
} else {
&file
}
}
fn calculate_modified_files<'a>(body: &'a str, filter: &Option<String>) -> Result<HashSet<&'a str>> {
let filter = FileFilter::init(filter)?;
let mut files = HashSet::new();
for line in body.lines() {
if line.starts_with("+++ ") || line.starts_with("--- ") {
let file = patch_line_to_file_name(&line);
if !filter.should_be_filtered(file) {
files.insert(file);
}
}
}
Ok(files)
}
fn get_modified_files(body: &str, filter: &Option<String>) -> Result<Vec<String>> {
let mut files: Vec<String> = calculate_modified_files(&body, filter)?.iter().map(|s| s.to_string()).collect();
files.sort();
Ok(files)
}
pub fn print_modified_filed(body: &str, filter: &Option<String>) -> Result<()> {
for file in &get_modified_files(body, filter)? {
println!("{}", file);
}
Ok(())
}
pub fn print_diff(body: &str, filter: &Option<String>) -> Result<()> {
let files = calculate_modified_files(body, filter)?;
let mut should_print = false;
for line in body.lines() {
if line.starts_with("+++ ") || line.starts_with("--- ") {
let file = patch_line_to_file_name(&line);
should_print = files.contains(file);
}
if should_print {
println!("{}", line);
}
}
Ok(())
}
pub fn fetch_pr(url: &str) -> Result<String> {
let mut res = reqwest::blocking::get(url)?;
let mut body = String::new();
res.read_to_string(&mut body)?;
Ok(body)
}
| true |
7e049fa875529ebc9c8a57b08ebda5559bf222d3
|
Rust
|
minus3theta/contest
|
/atcoder/abc/144/f.rs
|
UTF-8
| 2,515 | 2.9375 | 3 |
[] |
no_license
|
#[allow(unused_imports)]
use std::cmp;
use std::io::Write;
// Input macro from https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
(source = $s:expr, $($r:tt)*) => {
let mut iter = $s.split_whitespace();
input_inner!{iter, $($r)*}
};
($($r:tt)*) => {
let s = {
use std::io::Read;
let mut s = String::new();
std::io::stdin().read_to_string(&mut s).unwrap();
s
};
let mut iter = s.split_whitespace();
input_inner!{iter, $($r)*}
};
}
macro_rules! input_inner {
($iter:expr) => {};
($iter:expr, ) => {};
($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
let $var = read_value!($iter, $t);
input_inner!{$iter $($r)*}
};
}
macro_rules! read_value {
($iter:expr, ( $($t:tt),* )) => {
( $(read_value!($iter, $t)),* )
};
($iter:expr, [ $t:tt ; $len:expr ]) => {
(0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
};
($iter:expr, chars) => {
read_value!($iter, String).chars().collect::<Vec<char>>()
};
($iter:expr, usize1) => {
read_value!($iter, usize) - 1
};
($iter:expr, [ $t:tt ]) => {{
let len = read_value!($iter, usize);
(0..len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
}};
($iter:expr, $t:ty) => {
$iter.next().unwrap().parse::<$t>().expect("Parse error")
};
}
fn fmin(x: f64, y: f64) -> f64 {
if x < y {
x
} else {
y
}
}
#[derive(PartialEq, PartialOrd)]
pub struct Total<T>(pub T);
impl<T: PartialEq> Eq for Total<T> {}
impl<T: PartialOrd> Ord for Total<T> {
fn cmp(&self, other: &Total<T>) -> std::cmp::Ordering {
self.0.partial_cmp(&other.0).unwrap()
}
}
fn main() {
let out = std::io::stdout();
let mut out = std::io::BufWriter::new(out.lock());
macro_rules! puts {
($($format:tt)*) => (write!(out,$($format)*).unwrap());
}
input! {
n: usize,
m: usize,
es: [(usize1, usize1); m],
}
let mut exp = vec![0.0; n];
let mut adj = vec![vec![]; n];
for &(s, t) in &es {
adj[s].push(t);
}
let mut ans = 1.0 / 0.0;
for b in 0 .. n {
for i in (0 .. n - 1).rev() {
let l = adj[i].len();
exp[i] = 1.0 + if i == b && l > 1 {
let mut next: Vec<_> = adj[i].iter().map(|&x| Total(exp[x])).collect();
next.sort();
next.iter().take(l - 1).map(|x| x.0).sum::<f64>() / (l - 1) as f64
} else {
adj[i].iter().map(|&x| exp[x]).sum::<f64>() / l as f64
};
}
ans = fmin(ans, exp[0]);
}
puts!("{:.15}\n", ans);
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.