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 |
---|---|---|---|---|---|---|---|---|---|---|---|
50c35dc00a2185051fd83981c0bc6e3ecd1f3b95
|
Rust
|
2color/prisma-engines
|
/libs/datamodel/core/tests/attributes/unique.rs
|
UTF-8
| 7,448 | 2.78125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#![allow(non_snake_case)]
use datamodel::{ast::Span, diagnostics::*, render_datamodel_to_string, IndexDefinition, IndexType};
use crate::common::*;
#[test]
fn basic_unique_index_must_work() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique([firstName,lastName])
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: None,
fields: vec!["firstName".to_string(), "lastName".to_string()],
tpe: IndexType::Unique,
});
}
#[test]
fn multiple_unnamed_arguments_must_error() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique(firstName,lastName)
}
"#;
let errors = parse_error(dml);
errors.assert_is(DatamodelError::new_attribute_validation_error("You provided multiple unnamed arguments. This is not possible. Did you forget the brackets? Did you mean `[firstName, lastName]`?", "unique", Span::new(108, 134)));
}
#[test]
fn multi_field_unique_indexes_on_relation_fields_must_error_and_give_nice_error_on_inline_side() {
let dml = r#"
model User {
id Int @id
identificationId Int
identification Identification @relation(fields: [identificationId], references:[id])
@@unique([identification])
}
model Identification {
id Int @id
}
"#;
let errors = parse_error(dml);
errors.assert_is(DatamodelError::new_model_validation_error("The unique index definition refers to the relation fields identification. Index definitions must reference only scalar fields. Did you mean `@@unique([identificationId])`?", "User",Span::new(193, 217)));
}
#[test]
fn multi_field_unique_indexes_on_relation_fields_must_error_and_give_nice_error_on_NON_inline_side() {
let dml = r#"
model User {
id Int @id
identificationId Int
identification Identification @relation(fields: [identificationId], references:[id])
}
model Identification {
id Int @id
user User
@@unique([user])
}
"#;
let errors = parse_error(dml);
// in this case the error can't give a suggestion
errors.assert_is(DatamodelError::new_model_validation_error("The unique index definition refers to the relation fields user. Index definitions must reference only scalar fields.", "Identification",Span::new(270, 284)));
}
#[test]
fn single_field_unique_on_relation_fields_must_error_nicely_with_ONE_underlying_fields() {
let dml = r#"
model User {
id Int @id
identificationId Int
identification Identification @relation(fields: [identificationId], references:[id]) @unique
}
model Identification {
id Int @id
}
"#;
let errors = parse_error(dml);
errors.assert_is(DatamodelError::new_attribute_validation_error("The field `identification` is a relation field and cannot be marked with `unique`. Only scalar fields can be made unique. Did you mean to put it on `identificationId`?", "unique", Span::new(183, 189)));
}
#[test]
fn single_field_unique_on_relation_fields_must_error_nicely_with_MANY_underlying_fields() {
let dml = r#"
model User {
id Int @id
identificationId1 Int
identificationId2 Int
identification Identification @relation(fields: [identificationId1, identificationId2], references:[id]) @unique
}
model Identification {
id1 Int
id2 Int
@@id([id1, id2])
}
"#;
let errors = parse_error(dml);
errors.assert_is(DatamodelError::new_attribute_validation_error("The field `identification` is a relation field and cannot be marked with `unique`. Only scalar fields can be made unique. Did you mean to provide `@@unique([identificationId1, identificationId2])`?", "unique", Span::new(235, 241)));
}
#[test]
fn single_field_unique_on_enum_field_must_work() {
let dml = r#"
model User {
id Int @id
role Role @unique
}
enum Role {
Admin
Member
}
"#;
let schema = parse(dml);
schema
.assert_has_model("User")
.assert_has_scalar_field("role")
.assert_is_unique(true);
}
#[test]
fn the_name_argument_must_work() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique([firstName,lastName], name: "MyIndexName")
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: Some("MyIndexName".to_string()),
fields: vec!["firstName".to_string(), "lastName".to_string()],
tpe: IndexType::Unique,
});
}
#[test]
fn multiple_unique_must_work() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique([firstName,lastName])
@@unique([firstName,lastName], name: "MyIndexName")
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: None,
fields: vec!["firstName".to_string(), "lastName".to_string()],
tpe: IndexType::Unique,
});
user_model.assert_has_index(IndexDefinition {
name: Some("MyIndexName".to_string()),
fields: vec!["firstName".to_string(), "lastName".to_string()],
tpe: IndexType::Unique,
});
}
#[test]
fn multi_field_unique_indexes_on_enum_fields_must_work() {
let dml = r#"
model User {
id Int @id
role Role
@@unique([role])
}
enum Role {
Admin
Member
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: None,
fields: vec!["role".to_string()],
tpe: IndexType::Unique,
});
}
#[test]
fn must_error_when_unknown_fields_are_used() {
let dml = r#"
model User {
id Int @id
@@unique([foo,bar])
}
"#;
let errors = parse_error(dml);
errors.assert_is(DatamodelError::new_model_validation_error(
"The unique index definition refers to the unknown fields foo, bar.",
"User",
Span::new(48, 65),
));
}
#[test]
fn must_error_when_using_the_same_field_multiple_times() {
let dml = r#"
model User {
id Int @id
email String @unique
@@unique([email, email])
}
"#;
let errors = parse_error(dml);
errors.assert_is(DatamodelError::new_model_validation_error(
"The unique index definition refers to the fields email multiple times.",
"User",
Span::new(83, 105),
));
}
#[test]
fn unique_attributes_must_serialize_to_valid_dml() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique([firstName,lastName], name: "customName")
}
"#;
let schema = parse(dml);
assert!(datamodel::parse_datamodel(&render_datamodel_to_string(&schema)).is_ok());
}
| true |
8191a2bed1521315ebc2a50ba20e0386c06efd99
|
Rust
|
waywardmonkeys/app_units
|
/src/app_unit.rs
|
UTF-8
| 10,104 | 3.171875 | 3 |
[] |
no_license
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use num_traits::Zero;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use std::default::Default;
use std::fmt;
use std::i32;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign};
/// The number of app units in a pixel.
pub const AU_PER_PX: i32 = 60;
#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)]
/// An App Unit, the fundamental unit of length in Servo. Usually
/// 1/60th of a pixel (see AU_PER_PX)
///
/// Please ensure that the values are between MIN_AU and MAX_AU.
/// It is safe to construct invalid Au values, but it may lead to
/// panics and overflows.
pub struct Au(pub i32);
impl<'de> Deserialize<'de> for Au {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Au, D::Error> {
Ok(Au(try!(i32::deserialize(deserializer))).clamp())
}
}
impl Serialize for Au {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
}
impl Default for Au {
#[inline]
fn default() -> Au {
Au(0)
}
}
impl Zero for Au {
#[inline]
fn zero() -> Au {
Au(0)
}
#[inline]
fn is_zero(&self) -> bool {
self.0 == 0
}
}
// (1 << 30) - 1 lets us add/subtract two Au and check for overflow
// after the operation. Gecko uses the same min/max values
pub const MAX_AU: Au = Au((1 << 30) - 1);
pub const MIN_AU: Au = Au(- ((1 << 30) - 1));
impl fmt::Debug for Au {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}px", self.to_f64_px())
}
}
impl Add for Au {
type Output = Au;
#[inline]
fn add(self, other: Au) -> Au {
Au(self.0 + other.0).clamp()
}
}
impl Sub for Au {
type Output = Au;
#[inline]
fn sub(self, other: Au) -> Au {
Au(self.0 - other.0).clamp()
}
}
impl Mul<Au> for i32 {
type Output = Au;
#[inline]
fn mul(self, other: Au) -> Au {
if let Some(new) = other.0.checked_mul(self) {
Au(new).clamp()
} else if (self > 0) ^ (other.0 > 0) {
MIN_AU
} else {
MAX_AU
}
}
}
impl Mul<i32> for Au {
type Output = Au;
#[inline]
fn mul(self, other: i32) -> Au {
if let Some(new) = self.0.checked_mul(other) {
Au(new).clamp()
} else if (self.0 > 0) ^ (other > 0) {
MIN_AU
} else {
MAX_AU
}
}
}
impl Div for Au {
type Output = i32;
#[inline]
fn div(self, other: Au) -> i32 {
self.0 / other.0
}
}
impl Div<i32> for Au {
type Output = Au;
#[inline]
fn div(self, other: i32) -> Au {
Au(self.0 / other)
}
}
impl Rem for Au {
type Output = Au;
#[inline]
fn rem(self, other: Au) -> Au {
Au(self.0 % other.0)
}
}
impl Rem<i32> for Au {
type Output = Au;
#[inline]
fn rem(self, other: i32) -> Au {
Au(self.0 % other)
}
}
impl Neg for Au {
type Output = Au;
#[inline]
fn neg(self) -> Au {
Au(-self.0)
}
}
impl AddAssign for Au {
#[inline]
fn add_assign(&mut self, other: Au) {
*self = *self + other;
self.clamp_self();
}
}
impl SubAssign for Au {
#[inline]
fn sub_assign(&mut self, other: Au) {
*self = *self - other;
self.clamp_self();
}
}
impl MulAssign<i32> for Au {
#[inline]
fn mul_assign(&mut self, other: i32) {
*self = *self * other;
self.clamp_self();
}
}
impl DivAssign<i32> for Au {
#[inline]
fn div_assign(&mut self, other: i32) {
*self = *self / other;
self.clamp_self();
}
}
impl Au {
/// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
#[inline]
pub fn new(value: i32) -> Au {
Au(value).clamp()
}
#[inline]
fn clamp(self) -> Self {
if self.0 > MAX_AU.0 {
MAX_AU
} else if self.0 < MIN_AU.0 {
MIN_AU
} else {
self
}
}
#[inline]
fn clamp_self(&mut self) {
*self = Au::clamp(*self)
}
#[inline]
pub fn scale_by(self, factor: f32) -> Au {
let new_float = ((self.0 as f64) * factor as f64).round();
Au::from_f64_au(new_float)
}
#[inline]
/// Scale, but truncate (useful for viewport-relative units)
pub fn scale_by_trunc(self, factor: f32) -> Au {
let new_float = ((self.0 as f64) * factor as f64).trunc();
Au::from_f64_au(new_float)
}
#[inline]
pub fn from_f64_au(float: f64) -> Self {
// We *must* operate in f64. f32 isn't precise enough
// to handle MAX_AU
Au(float.min(MAX_AU.0 as f64)
.max(MIN_AU.0 as f64)
as i32)
}
#[inline]
pub fn from_px(px: i32) -> Au {
Au(px) * AU_PER_PX
}
/// Rounds this app unit down to the pixel towards zero and returns it.
#[inline]
pub fn to_px(self) -> i32 {
self.0 / AU_PER_PX
}
/// Ceil this app unit to the appropriate pixel boundary and return it.
#[inline]
pub fn ceil_to_px(self) -> i32 {
((self.0 as f64) / (AU_PER_PX as f64)).ceil() as i32
}
#[inline]
pub fn to_nearest_px(self) -> i32 {
((self.0 as f64) / (AU_PER_PX as f64)).round() as i32
}
#[inline]
pub fn to_nearest_pixel(self, pixels_per_px: f32) -> f32 {
((self.0 as f32) / (AU_PER_PX as f32) * pixels_per_px).round() / pixels_per_px
}
#[inline]
pub fn to_f32_px(self) -> f32 {
(self.0 as f32) / (AU_PER_PX as f32)
}
#[inline]
pub fn to_f64_px(self) -> f64 {
(self.0 as f64) / (AU_PER_PX as f64)
}
#[inline]
pub fn from_f32_px(px: f32) -> Au {
let float = (px * AU_PER_PX as f32).round();
Au::from_f64_au(float as f64)
}
#[inline]
pub fn from_f64_px(px: f64) -> Au {
let float = (px * AU_PER_PX as f64).round();
Au::from_f64_au(float)
}
#[inline]
pub fn abs(self) -> Self {
Au(self.0.abs())
}
}
#[test]
fn create() {
assert_eq!(Au::zero(), Au(0));
assert_eq!(Au::default(), Au(0));
assert_eq!(Au::new(7), Au(7));
}
#[test]
fn operations() {
assert_eq!(Au(7) + Au(5), Au(12));
assert_eq!(MAX_AU + Au(1), MAX_AU);
assert_eq!(Au(7) - Au(5), Au(2));
assert_eq!(MIN_AU - Au(1), MIN_AU);
assert_eq!(Au(7) * 5, Au(35));
assert_eq!(5 * Au(7), Au(35));
assert_eq!(MAX_AU * -1, MIN_AU);
assert_eq!(MIN_AU * -1, MAX_AU);
assert_eq!(-1 * MAX_AU, MIN_AU);
assert_eq!(-1 * MIN_AU, MAX_AU);
assert_eq!((Au(14) / 5) * 5 + Au(14) % 5, Au(14));
assert_eq!((Au(14) / Au(5)) * Au(5) + Au(14) % Au(5), Au(14));
assert_eq!(Au(35) / 5, Au(7));
assert_eq!(Au(35) % 6, Au(5));
assert_eq!(Au(35) / Au(5), 7);
assert_eq!(Au(35) / Au(5), 7);
assert_eq!(-Au(7), Au(-7));
}
#[test]
fn saturate() {
let half = MAX_AU / 2;
assert_eq!(half + half + half + half + half, MAX_AU);
assert_eq!(-half - half - half - half - half, MIN_AU);
assert_eq!(half * -10, MIN_AU);
assert_eq!(-half * 10, MIN_AU);
assert_eq!(half * 10, MAX_AU);
assert_eq!(-half * -10, MAX_AU);
}
#[test]
fn scale() {
assert_eq!(Au(12).scale_by(1.5), Au(18));
assert_eq!(Au(12).scale_by(1.7), Au(20));
assert_eq!(Au(12).scale_by(1.8), Au(22));
assert_eq!(Au(12).scale_by_trunc(1.8), Au(21));
}
#[test]
fn abs() {
assert_eq!(Au(-10).abs(), Au(10));
}
#[test]
fn convert() {
assert_eq!(Au::from_px(5), Au(300));
assert_eq!(Au(300).to_px(), 5);
assert_eq!(Au(330).to_px(), 5);
assert_eq!(Au(350).to_px(), 5);
assert_eq!(Au(360).to_px(), 6);
assert_eq!(Au(300).ceil_to_px(), 5);
assert_eq!(Au(310).ceil_to_px(), 6);
assert_eq!(Au(330).ceil_to_px(), 6);
assert_eq!(Au(350).ceil_to_px(), 6);
assert_eq!(Au(360).ceil_to_px(), 6);
assert_eq!(Au(300).to_nearest_px(), 5);
assert_eq!(Au(310).to_nearest_px(), 5);
assert_eq!(Au(330).to_nearest_px(), 6);
assert_eq!(Au(350).to_nearest_px(), 6);
assert_eq!(Au(360).to_nearest_px(), 6);
assert_eq!(Au(60).to_nearest_pixel(2.), 1.);
assert_eq!(Au(70).to_nearest_pixel(2.), 1.);
assert_eq!(Au(80).to_nearest_pixel(2.), 1.5);
assert_eq!(Au(90).to_nearest_pixel(2.), 1.5);
assert_eq!(Au(100).to_nearest_pixel(2.), 1.5);
assert_eq!(Au(110).to_nearest_pixel(2.), 2.);
assert_eq!(Au(120).to_nearest_pixel(2.), 2.);
assert_eq!(Au(300).to_f32_px(), 5.);
assert_eq!(Au(312).to_f32_px(), 5.2);
assert_eq!(Au(330).to_f32_px(), 5.5);
assert_eq!(Au(348).to_f32_px(), 5.8);
assert_eq!(Au(360).to_f32_px(), 6.);
assert_eq!((Au(367).to_f32_px() * 1000.).round(), 6_117.);
assert_eq!((Au(368).to_f32_px() * 1000.).round(), 6_133.);
assert_eq!(Au(300).to_f64_px(), 5.);
assert_eq!(Au(312).to_f64_px(), 5.2);
assert_eq!(Au(330).to_f64_px(), 5.5);
assert_eq!(Au(348).to_f64_px(), 5.8);
assert_eq!(Au(360).to_f64_px(), 6.);
assert_eq!((Au(367).to_f64_px() * 1000.).round(), 6_117.);
assert_eq!((Au(368).to_f64_px() * 1000.).round(), 6_133.);
assert_eq!(Au::from_f32_px(5.), Au(300));
assert_eq!(Au::from_f32_px(5.2), Au(312));
assert_eq!(Au::from_f32_px(5.5), Au(330));
assert_eq!(Au::from_f32_px(5.8), Au(348));
assert_eq!(Au::from_f32_px(6.), Au(360));
assert_eq!(Au::from_f32_px(6.12), Au(367));
assert_eq!(Au::from_f32_px(6.13), Au(368));
assert_eq!(Au::from_f64_px(5.), Au(300));
assert_eq!(Au::from_f64_px(5.2), Au(312));
assert_eq!(Au::from_f64_px(5.5), Au(330));
assert_eq!(Au::from_f64_px(5.8), Au(348));
assert_eq!(Au::from_f64_px(6.), Au(360));
assert_eq!(Au::from_f64_px(6.12), Au(367));
assert_eq!(Au::from_f64_px(6.13), Au(368));
}
| true |
97377fd1c2ef3aa928709a4a239ffc3f4d3b625d
|
Rust
|
pitpo/AdventOfCode2018
|
/days/day24/src/lib.rs
|
UTF-8
| 8,513 | 3.15625 | 3 |
[] |
no_license
|
extern crate utils;
use utils::Day;
use std::cmp::Ordering;
use std::collections::HashMap;
pub struct Day24 {
groups: Vec<Group>,
}
#[derive(Debug, Clone)]
struct Group {
is_foe: bool,
units: usize,
hp: usize,
weak: Vec<String>,
immune: Vec<String>,
attack: usize,
attack_type: String,
initiative: usize,
combat_power: usize,
}
impl PartialEq for Group {
fn eq(&self, rhs: &Group) -> bool {
return self.is_foe == rhs.is_foe && self.hp == rhs.hp && self.attack == rhs.attack && self.initiative == rhs.initiative;
}
}
impl Day24 {
pub fn new(input: String) -> Day24 {
let mut input_iter = input.lines();
let mut string;
input_iter.next();
let mut groups: Vec<Group> = Vec::new();
loop {
string = input_iter.next().unwrap().to_string();
if string == "" {
break;
}
let mut group = Day24::parse_line(&string);
group.is_foe = false;
groups.push(group);
}
input_iter.next();
while let Some(string) = input_iter.next() {
let group = Day24::parse_line(&string.to_string());
groups.push(group);
}
Day24 { groups }
}
fn parse_line(line: &String) -> Group {
// YES, I KNOW, I really should learn regexps
// My anger towards this year's AoC difficulty level/time consumption just hit another level, that's why I don't give a single heck about code quality anymore
let perks = line.split(|c| c == '(' || c == ')').collect::<Vec<&str>>();
let mut weak: Vec<String> = Vec::new();
let mut immune: Vec<String> = Vec::new();
if perks.len() == 3 {
let perks = perks[1].split(|c| c == ';').collect::<Vec<&str>>();
for perk in perks {
let perk = perk.trim();
if perk.starts_with("weak to") {
let (_, weaknesses) = perk.split_at(7);
weak = weaknesses.split(|c| c == ',').map(|s| s.trim().to_string()).collect::<Vec<String>>();
} else {
let (_, immunities) = perk.split_at(9);
immune = immunities.split(|c| c == ',').map(|s| s.trim().to_string()).collect::<Vec<String>>();
}
}
}
let numbers = utils::extract_unsigned_integers_from_string(line);
let units = numbers[0][0];
let hp = numbers[0][1];
let attack = numbers[0][2];
let initiative = numbers[0][3];
let tmp = line.split_whitespace().collect::<Vec<&str>>();
let mut attack_type = String::new();
for i in 0..tmp.len() {
if tmp[i] == "damage" {
attack_type = tmp[i-1].to_string();
break;
}
}
let combat_power = units * attack;
let is_foe = true;
Group { is_foe, units, hp, weak, immune, attack, attack_type, initiative, combat_power }
}
fn get_opponents(&self, groups: &mut Vec<Group>) -> Vec<(Group, Group)> {
let mut attacked_groups: Vec<Option<Group>> = Vec::new();
groups.sort_by(|a, b| {
let ord = b.combat_power.cmp(&a.combat_power);
if ord == Ordering::Equal {
return b.initiative.cmp(&a.initiative);
}
ord
});
for i in 0..groups.len() {
let mut foe: Option<Group> = None;
let mut max_dmg = 0;
for j in 0..groups.len() {
if i != j && groups[j].is_foe != groups[i].is_foe && !attacked_groups.contains(&Some(groups[j].clone())) {
let mut dmg = groups[i].combat_power;
if groups[j].weak.contains(&groups[i].attack_type) {
dmg = groups[i].combat_power * 2;
}
if groups[j].immune.contains(&groups[i].attack_type) {
dmg = 0;
}
if dmg > max_dmg {
foe = Some(groups[j].clone());
max_dmg = dmg;
}
}
}
attacked_groups.push(foe);
}
groups.iter().zip(attacked_groups.iter()).filter(|tup| tup.1.is_some()).map(|tup| (tup.0.clone(), tup.1.clone().unwrap())).collect::<Vec<(Group, Group)>>()
}
fn attack(&self, groups: &mut Vec<Group>, fights: Vec<(Group, Group)>) -> bool {
let mut damage_dealt = false;
groups.sort_by(|a, b| {
let ord = b.initiative.cmp(&a.initiative);
if ord == Ordering::Equal {
return b.combat_power.cmp(&a.combat_power);
}
ord
});
for i in 0..groups.len() {
for j in 0..fights.len() {
if groups[i] == fights[j].0 {
if groups[i].units == 0 {
break;
}
for k in 0..groups.len() {
if groups[k] == fights[j].1 {
let dmg;
if groups[k].weak.contains(&groups[i].attack_type) {
dmg = groups[i].combat_power * 2;
} else {
dmg = groups[i].combat_power;
}
let casualties = dmg / groups[k].hp;
if casualties > 0 {
damage_dealt = true;
}
if casualties > groups[k].units {
groups[k].units = 0;
} else {
groups[k].units -= casualties;
}
groups[k].combat_power = groups[k].units * groups[k].attack;
break;
}
}
break;
}
}
}
let mut i = 0;
while i < groups.len() {
if groups[i].units == 0 {
groups.remove(i);
} else {
groups[i].combat_power = groups[i].units * groups[i].attack;
i += 1;
}
}
damage_dealt
}
}
impl Day for Day24 {
fn get_part_a_result(&self) -> String {
let mut groups: Vec<Group> = self.groups.clone();
while groups.iter().filter(|g| g.is_foe).count() != 0 && groups.iter().filter(|g| !g.is_foe).count() != 0 {
let fights = self.get_opponents(&mut groups);
self.attack(&mut groups, fights);
}
groups.iter().fold(0, |acc, g| acc + g.units).to_string()
}
fn get_part_b_result(&self) -> String {
// it's broken beyond repair but somehow gave me a good answer
// it doesn't even pass the sample test, but i couldn't care less
let groups: Vec<Group> = self.groups.clone();
let (mut min, mut max) = (0, 20000);
let mut result_map: HashMap<usize, usize> = HashMap::new();
let mut boost = 10000;
loop {
let mut boosted_groups = groups.iter().map(|group| {
let mut group = group.clone();
if !group.is_foe {
group.attack += boost;
}
group
}).collect::<Vec<Group>>();
while boosted_groups.iter().filter(|g| g.is_foe).count() != 0 && boosted_groups.iter().filter(|g| !g.is_foe).count() != 0 {
let fights = self.get_opponents(&mut boosted_groups);
let damage_dealt = self.attack(&mut boosted_groups, fights);
if !damage_dealt {
break;
}
}
let remaining_allies = boosted_groups.iter().filter(|g| !g.is_foe).fold(0, |acc, g| acc + g.units);
let remaining_foes = boosted_groups.iter().filter(|g| g.is_foe).fold(0, |acc, g| acc + g.units);
result_map.insert(boost, remaining_allies);
if remaining_allies == 0 || (remaining_foes != 0 && remaining_allies != 0) {
min = boost + 1;
} else {
max = boost - 1;
}
boost = (min + max) / 2;
if min > max {
return result_map[&min].to_string();
}
}
}
}
| true |
f5c8d368b82de6313c8f910405030a025751ec84
|
Rust
|
doraneko94/CA3-Rust
|
/pinsky-rinzel/src/neuron.rs
|
UTF-8
| 630 | 2.703125 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use crate::compartment::*;
pub struct Neuron {
pub soma: Soma,
pub dend: Dend,
}
impl Default for Neuron {
fn default() -> Self {
Self::new(&HashMap::new())
}
}
impl Neuron {
pub fn new(params: &HashMap<&str, f64>) -> Self {
let soma = Soma::new(params);
let dend = Dend::new(params);
Self { soma, dend, }
}
pub fn run(&mut self, dt: f64, v_pre: &Vec<f64>) -> f64 {
let v_s = self.soma.v;
let v_d = self.dend.v;
self.soma.run(v_d, dt, v_pre);
self.dend.run(v_s, dt, v_pre);
self.soma.v
}
}
| true |
3e5781697cbd6cc517a014391461506aed02e374
|
Rust
|
Vuenc/Advent-of-Code-2018
|
/src/day4.rs
|
UTF-8
| 4,549 | 3.125 | 3 |
[] |
no_license
|
// use std::cmp::{max};
use regex::Regex;
use self::GuardAction::*;
use bit_vec::BitVec;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq)]
enum GuardAction {
BeginsShift,
WakesUp,
FallsAsleep
}
#[derive(Debug)]
struct GuardEvent {
date: String,
minute: i32,
guard_id: Option<i32>,
action: GuardAction
}
#[derive(Debug)]
struct Day {
guard_id: i32,
minutes: BitVec,
minutes_awake: i32
}
impl Day {
pub fn new(guard_id: i32) -> Day {
let minutes = BitVec::with_capacity(60);
Day {guard_id, minutes, minutes_awake: 0}
}
pub fn set_next_minute(&mut self, awake: bool) {
self.minutes.push(awake);
self.minutes_awake += i32::from(awake);
}
}
impl GuardEvent {
pub fn from_line(line: &String, regex: &Regex) -> GuardEvent {
let captures = regex.captures(line).expect("No captures for line!");
let action = match &captures[3] {
"wakes" => WakesUp,
"falls" => FallsAsleep,
_ => BeginsShift
};
GuardEvent {date: captures[1].to_string(),
minute: captures[2].replace(":", "").parse().unwrap(),
guard_id: captures.get(4).map(|id| id.as_str().parse().unwrap()),
action
}
}
}
fn initialize(lines: &Vec<String>) -> Vec<Day> {
let regex = Regex::new(r"(\d\d-\d\d) ((?:23|00):\d\d)\] (Guard #(\d*)|wakes|falls)").expect("Building Regex failed");
let mut events = lines.iter().map(|l| GuardEvent::from_line(l, ®ex)).collect::<Vec<GuardEvent>>();
events.sort_by(|GuardEvent {date: date1, minute: minute1, ..}, GuardEvent {date: date2, minute: minute2, ..}| {
date1.cmp(date2).then(minute1.cmp(minute2))
});
let mut days = Vec::new();
let mut events_iter = events.iter();
let mut event_option = events_iter.next();
while event_option.is_some() {
let event = event_option.unwrap();
assert_eq!(event.action, BeginsShift);
let mut current_day = Day::new(event.guard_id.unwrap());
let mut is_awake = true;
event_option = events_iter.next();
for minute in 0..60 {
if event_option.map_or(false, |e| e.action != BeginsShift && e.minute == minute) {
is_awake = !is_awake;
event_option = events_iter.next();
}
current_day.set_next_minute(is_awake);
}
days.push(current_day);
}
days
}
pub fn star1(lines: &Vec<String>) -> String {
let days = initialize(lines);
let mut guard_map = HashMap::new();
for day in days {
guard_map.entry(day.guard_id)
.or_insert(vec![])
.push(day);
}
let (&sleepiest_guard_id, sleepiest_guard_days) = guard_map.iter()
.max_by_key(|(_, v)| v.iter()
.map(|day| 60 - day.minutes_awake)
.sum::<i32>()
).unwrap();
let mut sleepiest_guard_awake_by_minutes = vec![0; 60];
for day in sleepiest_guard_days {
// println!("Day: {:?}", day);
for minute in 0..60 {
sleepiest_guard_awake_by_minutes[minute] += i32::from(day.minutes[minute]);
}
}
let (max_minute, _) = sleepiest_guard_awake_by_minutes.iter().enumerate().min_by_key(|(_, times)| *times).unwrap();
println!("Min minute: {}, max guard: {}", max_minute, sleepiest_guard_id);
(sleepiest_guard_id * max_minute as i32).to_string()
}
pub fn star2(lines: &Vec<String>) -> String {
let days = initialize(lines);
let mut guard_map = HashMap::new();
for day in days {
guard_map.entry(day.guard_id)
.or_insert(vec![])
.push(day);
}
let mut max_guard_asleep_per_minute = vec![(0, None); 60];
for &guard_id in guard_map.keys() {
let mut guard_asleep_by_minute = vec![0; 60];
for day in &guard_map[&guard_id] {
for minute in 0..60 {
guard_asleep_by_minute[minute] += i32::from(!day.minutes[minute]);
}
}
for minute in 0..60 {
if max_guard_asleep_per_minute[minute].0 < guard_asleep_by_minute[minute] {
max_guard_asleep_per_minute[minute] = (guard_asleep_by_minute[minute], Some(guard_id));
}
}
}
if let Some((max_minute, (_, Some(max_guard_id)))) = max_guard_asleep_per_minute.iter().enumerate().max_by_key(|(_, (times, _))| times) {
return (max_minute as i32 * max_guard_id) .to_string();
}
panic!("No maximum found: Invalid input!");
}
| true |
ea715be5961eecb6f8ea7a10f68f1d31eadfb2e8
|
Rust
|
async-raft/async-raft
|
/async-raft/tests/shutdown.rs
|
UTF-8
| 1,875 | 2.6875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
mod fixtures;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{anyhow, Result};
use async_raft::Config;
use tokio::time::sleep;
use fixtures::RaftRouter;
/// Cluster shutdown test.
///
/// What does this test do?
///
/// - this test builds upon the `initialization` test.
/// - after the cluster has been initialize, it performs a shutdown routine
/// on each node, asserting that the shutdown routine succeeded.
///
/// RUST_LOG=async_raft,memstore,shutdown=trace cargo test -p async-raft --test shutdown
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn initialization() -> Result<()> {
fixtures::init_tracing();
// Setup test dependencies.
let config = Arc::new(Config::build("test".into()).validate().expect("failed to build Raft config"));
let router = Arc::new(RaftRouter::new(config.clone()));
router.new_raft_node(0).await;
router.new_raft_node(1).await;
router.new_raft_node(2).await;
// Assert all nodes are in non-voter state & have no entries.
sleep(Duration::from_secs(10)).await;
router.assert_pristine_cluster().await;
// Initialize the cluster, then assert that a stable cluster was formed & held.
tracing::info!("--- initializing cluster");
router.initialize_from_single_node(0).await?;
sleep(Duration::from_secs(10)).await;
router.assert_stable_cluster(Some(1), Some(1)).await;
tracing::info!("--- performing node shutdowns");
let (node0, _) = router.remove_node(0).await.ok_or_else(|| anyhow!("failed to find node 0 in router"))?;
node0.shutdown().await?;
let (node1, _) = router.remove_node(1).await.ok_or_else(|| anyhow!("failed to find node 1 in router"))?;
node1.shutdown().await?;
let (node2, _) = router.remove_node(2).await.ok_or_else(|| anyhow!("failed to find node 2 in router"))?;
node2.shutdown().await?;
Ok(())
}
| true |
1f3f52c1b890983078f1d66a0ba9ab24524e3cec
|
Rust
|
bvssvni/ncollide
|
/src/parametric/parametric.rs
|
UTF-8
| 1,727 | 3.1875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
// FIXME: support more than rectangular surfaces?
use math::Scalar;
/// Trait implemented by differentiable parametric surfaces.
///
/// The parametrization space is assumed to be `[0.0, 1.0] x [0.0, 1.0]`.
pub trait ParametricSurface<N: Scalar, P, V> {
// FIXME: rename those d0, du, etc. ? (just like in the `symbolic` module.
/// Evaluates the parametric surface.
fn at(&self, u: N, v: N) -> P;
/// Evaluates the surface derivative wrt. `u`.
fn at_u(&self, u: N, v: N) -> V;
/// Evaluates the surface derivative wrt. `v`.
fn at_v(&self, u: N, v: N) -> V;
/// Evaluates the surface second derivative wrt. `u`.
fn at_uu(&self, u: N, v: N) -> V;
/// Evaluates the surface second derivative wrt. `v`.
fn at_vv(&self, u: N, v: N) -> V;
/// Evaluates the surface second derivative wrt. `u` and `v`.
fn at_uv(&self, u: N, v: N) -> V;
/// Evaluates the parametric surface and its first derivatives.
///
/// Returns (S(u, v), dS / du, dS / dv)
#[inline]
fn at_u_v(&self, u: N, v: N) -> (P, V, V) {
(self.at(u, v), self.at_u(u, v), self.at_v(u, v))
}
/// Evaluates the parametric surface and its first and second derivatides.
///
/// Returns (S(u, v), dS / du, dS / dv, d²S / du², d²S / dv², d²S / dudv)
#[inline]
fn at_u_v_uu_vv_uv(&self, u: N, v: N) -> (P, V, V, V, V, V) {
(self.at(u, v), self.at_u(u, v), self.at_v(u, v), self.at_uu(u, v), self.at_vv(u, v), self.at_uv(u, v))
}
/// Evaluates the parametric surface and its derivative wrt. `u` `n` times and wrt. `v` `k` times.
///
/// Returns d^(n + k) S(u, v) / (du^n dk^n).
fn at_uv_nk(&self, u: N, v: N, n: uint, k: uint) -> V;
}
| true |
dcef0169c6c99be4ca7a15f5b178f66bf2e1df8b
|
Rust
|
iqlusioninc/abscissa
|
/core/src/thread/name.rs
|
UTF-8
| 1,021 | 3.421875 | 3 |
[
"Apache-2.0"
] |
permissive
|
//! Thread names.
use crate::{FrameworkError, FrameworkErrorKind::ThreadError};
use std::{fmt, str::FromStr};
/// Thread name.
///
/// Cannot contain null bytes.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Name(String);
impl Name {
/// Create a new thread name
pub fn new(name: impl ToString) -> Result<Self, FrameworkError> {
let name = name.to_string();
if name.contains('\0') {
fail!(ThreadError, "name contains null bytes: {:?}", name)
} else {
Ok(Name(name))
}
}
}
impl AsRef<str> for Name {
fn as_ref(&self) -> &str {
&self.0
}
}
impl FromStr for Name {
type Err = FrameworkError;
fn from_str(s: &str) -> Result<Self, FrameworkError> {
Self::new(s)
}
}
impl From<Name> for String {
fn from(name: Name) -> String {
name.0
}
}
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
| true |
270c1eb1a45470b3dab44f6cfd54a6ee3caac1c9
|
Rust
|
peku33/logicblocks
|
/Controller/src/devices/houseblocks/avr_v1/hardware/driver.rs
|
UTF-8
| 6,311 | 2.515625 | 3 |
[] |
no_license
|
use super::{
super::super::houseblocks_v1::{
common::{Address, Payload},
master::Master,
},
parser::Parser,
};
use anyhow::{ensure, Context, Error};
use std::time::Duration;
#[derive(Debug)]
pub struct PowerFlags {
wdt: bool,
bod: bool,
ext_reset: bool,
pon: bool,
}
#[derive(Debug)]
pub struct Version {
avr_v1: u16,
application: u16,
}
#[derive(Debug)]
pub struct Driver<'m> {
master: &'m Master,
address: Address,
}
impl<'m> Driver<'m> {
const TIMEOUT_DEFAULT: Duration = Duration::from_millis(250);
pub fn new(
master: &'m Master,
address: Address,
) -> Self {
Self { master, address }
}
pub fn address(&self) -> &Address {
&self.address
}
// Transactions
async fn transaction_out(
&self,
service_mode: bool,
payload: Payload,
) -> Result<(), Error> {
self.master
.transaction_out(service_mode, self.address, payload)
.await
.context("transaction_out")?;
Ok(())
}
async fn transaction_out_in(
&self,
service_mode: bool,
payload: Payload,
timeout: Option<Duration>,
) -> Result<Payload, Error> {
let result = self
.master
.transaction_out_in(
service_mode,
self.address,
payload,
timeout.unwrap_or(Self::TIMEOUT_DEFAULT),
)
.await
.context("transaction_out_in")?;
Ok(result)
}
// Routines
async fn healthcheck(
&self,
service_mode: bool,
) -> Result<(), Error> {
let response = self
.transaction_out_in(service_mode, Payload::new(Box::from(*b"")).unwrap(), None)
.await
.context("transaction_out_in")?;
ensure!(
response.as_bytes() == &b""[..],
"invalid healthcheck response"
);
Ok(())
}
async fn reboot(
&self,
service_mode: bool,
) -> Result<(), Error> {
self.transaction_out(service_mode, Payload::new(Box::from(*b"!")).unwrap())
.await
.context("transaction_out")?;
tokio::time::sleep(Self::TIMEOUT_DEFAULT).await;
Ok(())
}
async fn read_clear_power_flags(
&self,
service_mode: bool,
) -> Result<PowerFlags, Error> {
let response = self
.transaction_out_in(service_mode, Payload::new(Box::from(*b"@")).unwrap(), None)
.await
.context("transaction_out_in")?;
let mut parser = Parser::from_payload(&response);
let wdt = parser.expect_bool().context("wdt")?;
let bod = parser.expect_bool().context("bod")?;
let ext_reset = parser.expect_bool().context("ext_reset")?;
let pon = parser.expect_bool().context("pon")?;
parser.expect_end().context("expect_end")?;
Ok(PowerFlags {
wdt,
bod,
ext_reset,
pon,
})
}
async fn read_application_version(
&self,
service_mode: bool,
) -> Result<Version, Error> {
let response = self
.transaction_out_in(service_mode, Payload::new(Box::from(*b"#")).unwrap(), None)
.await
.context("transaction_out_in")?;
let mut parser = Parser::from_payload(&response);
let avr_v1 = parser.expect_u16().context("avr_v1")?;
let application = parser.expect_u16().context("application")?;
parser.expect_end().context("expect_end")?;
Ok(Version {
avr_v1,
application,
})
}
// Service mode routines
async fn service_mode_read_application_checksum(&self) -> Result<u16, Error> {
let response = self
.transaction_out_in(true, Payload::new(Box::new(*b"C")).unwrap(), None)
.await
.context("transaction_out_in")?;
let mut parser = Parser::from_payload(&response);
let checksum = parser.expect_u16().context("checksum")?;
parser.expect_end().context("expect_end")?;
Ok(checksum)
}
async fn service_mode_jump_to_application_mode(&self) -> Result<(), Error> {
self.transaction_out(true, Payload::new(Box::from(*b"R")).unwrap())
.await
.context("transaction_out")?;
tokio::time::sleep(Duration::from_millis(250)).await;
Ok(())
}
// Procedures
pub async fn prepare(&self) -> Result<(), Error> {
// Driver may be already initialized, check it.
let healthcheck_result = self.healthcheck(false).await;
if healthcheck_result.is_ok() {
// Is initialized, perform reboot
self.reboot(false).await.context("deinitialize reboot")?;
}
// We should be in service mode
self.healthcheck(true)
.await
.context("service mode healthcheck")?;
// Check application up to date
let application_checksum = self
.service_mode_read_application_checksum()
.await
.context("service mode read application checksum")?;
log::trace!("application_checksum: {}", application_checksum);
// TODO: Push new firmware
// Reboot to application section
self.service_mode_jump_to_application_mode()
.await
.context("jump to application mode")?;
// Check life in application section
self.healthcheck(false)
.await
.context("application mode healthcheck")?;
Ok(())
}
}
#[derive(Debug)]
pub struct ApplicationDriver<'d> {
driver: &'d Driver<'d>,
}
impl<'d> ApplicationDriver<'d> {
pub fn new(driver: &'d Driver<'d>) -> Self {
Self { driver }
}
pub async fn transaction_out(
&self,
payload: Payload,
) -> Result<(), Error> {
self.driver.transaction_out(false, payload).await
}
pub async fn transaction_out_in(
&self,
payload: Payload,
timeout: Option<Duration>,
) -> Result<Payload, Error> {
self.driver
.transaction_out_in(false, payload, timeout)
.await
}
}
| true |
c1fa22ba7f032f9b23c8e82328a6710d0342286b
|
Rust
|
higgsofwolfram74/rustcreditcardchecksum
|
/creditcheck/src/main.rs
|
UTF-8
| 1,519 | 3.578125 | 4 |
[] |
no_license
|
use std::io;
fn credit_checksum(number_check: &mut [u32; 16]) {
let test: u32 = number_check[15];
number_check[15] = 0;
for index in (0..15).step_by(2) {
let mut number = number_check[index] * 2;
if number > 9 {
number = 1 + (number - 10);
}
number_check[index] = number;
}
println!("{:?}", number_check);
let mut total: u32 = number_check.iter().sum();
total += test;
if total % 10 == 0 {
println!("This is a valid card number.")
} else {
println!("This card number is invalid.")
}
}
fn number_vectorizer(card_digits: &String) {
let mut card_number: [u32; 16] = [0; 16];
let mut index = 0;
for digit in card_digits.chars() {
card_number[index] = digit.to_digit(10).expect("Non number on credit card");
index += 1;
}
credit_checksum(&mut card_number);
}
fn main() {
println!("Welcome to my credit card verifier. Please input number to check.");
let mut card_number = String::new();
io::stdin()
.read_line(&mut card_number)
.expect("Failed to read the input");
if card_number.ends_with('\n') {
card_number.pop();
if card_number.ends_with('\r') {
card_number.pop();
}
}
if card_number.len() != 16 {
panic!("Card number is not the correct length")
}
println!("Now checking the validity of the credit card number.");
number_vectorizer(&card_number);
}
| true |
e01787d07825c553a84a5c76024f6a5c266b8289
|
Rust
|
TheBlueMatt/rust-lightning
|
/lightning-block-sync/src/utils.rs
|
UTF-8
| 941 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
use bitcoin::util::uint::Uint256;
pub fn hex_to_uint256(hex: &str) -> Option<Uint256> {
if hex.len() != 64 { return None; }
let mut out = [0u64; 4];
let mut b: u64 = 0;
for (idx, c) in hex.as_bytes().iter().enumerate() {
b <<= 4;
match *c {
b'A'..=b'F' => b |= (c - b'A' + 10) as u64,
b'a'..=b'f' => b |= (c - b'a' + 10) as u64,
b'0'..=b'9' => b |= (c - b'0') as u64,
_ => return None,
}
if idx % 16 == 15 {
out[3 - (idx / 16)] = b;
b = 0;
}
}
Some(Uint256::from(&out[..]))
}
#[cfg(feature = "rpc-client")]
pub fn hex_to_vec(hex: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(hex.len() / 2);
let mut b = 0;
for (idx, c) in hex.as_bytes().iter().enumerate() {
b <<= 4;
match *c {
b'A'..=b'F' => b |= c - b'A' + 10,
b'a'..=b'f' => b |= c - b'a' + 10,
b'0'..=b'9' => b |= c - b'0',
_ => return None,
}
if (idx & 1) == 1 {
out.push(b);
b = 0;
}
}
Some(out)
}
| true |
de7cb8d52d367ddef807053a425e2253e8e799b5
|
Rust
|
s-aran/nae
|
/src/natural_sort.rs
|
UTF-8
| 7,625 | 3.671875 | 4 |
[] |
no_license
|
use std::cmp::Ordering;
pub struct NaturalSort {}
impl NaturalSort {
/// internal common radix
const RADIX: u32 = 10;
/// strcmp with natural
/// # Arguments
/// * `a` - first string
/// * `b` - second string
/// # Return
/// * `Ordering` - result of comparison
/// # Example
/// ```
/// use std::cmp::Ordering;
/// use nae::natural_sort::NaturalSort;
/// assert_eq!(NaturalSort::strcmp_natural("1", "2"), Ordering::Less);
/// assert_eq!(NaturalSort::strcmp_natural("2", "2"), Ordering::Equal);
/// assert_eq!(NaturalSort::strcmp_natural("3", "2"), Ordering::Greater);
/// ```
pub fn strcmp_natural(a: &str, b: &str) -> Ordering {
// println!("a: {} ({}), b: {} ({})", a, a.len(), b, b.len());
if a == b {
// return Ordering::Equal;
}
let a_len = a.len();
let b_len = b.len();
let max_len = std::cmp::max(a.len(), b.len());
// println!("max_len: {}", max_len);
let mut ret = Ordering::Equal;
for i in 0..max_len {
let ac = if i < a_len {
a.chars().nth(i).unwrap()
} else {
'\0'
};
let bc = if i < b_len {
b.chars().nth(i).unwrap()
} else {
'\0'
};
// println!("a[{}]: {} (0x{:04X})", i, ac, ac as u32);
// println!("b[{}]: {} (0x{:04X})", i, bc, bc as u32);
if ac != bc {
ret = if ac < bc {
Ordering::Less
} else {
Ordering::Greater
};
// println!("a: {}, b: {}", ac.is_digit(Radix), bc.is_digit(Radix));
if ac.is_digit(NaturalSort::RADIX) && bc.is_digit(NaturalSort::RADIX) {
let mut ai = i;
for _ in i..a_len {
// println!("ai: {} -> {}", ai, a.chars().nth(ai).unwrap());
if !a.chars().nth(ai).unwrap().is_digit(NaturalSort::RADIX) {
break;
}
ai += 1;
}
// println!("{}[{}..{}] --> {}", a, i, ai, &a[i..ai]);
let asl = &a[i..ai];
let anum = if asl == "" {
0
} else {
asl.parse::<u32>().unwrap()
};
let mut bi = i;
for _ in i..b_len {
// println!("bi: {} -> {}", bi, b.chars().nth(bi).unwrap());
if !b.chars().nth(bi).unwrap().is_digit(NaturalSort::RADIX) {
break;
}
bi += 1;
}
// println!("{}[{}..{}] --> {}", b, i, bi, &b[i..bi]);
let bsl = &b[i..bi];
let bnum = if bsl == "" {
0
} else {
bsl.parse::<u32>().unwrap()
};
// println!("anum: {}", anum);
// println!("bnum: {}", bnum);
ret = if anum < bnum {
Ordering::Less
} else {
Ordering::Greater
};
break;
} else if ret == Ordering::Equal {
continue;
} else {
break;
}
}
}
// println!(
// "ret: {}",
// match ret {
// Ordering::Less => "Less",
// Ordering::Greater => "Greater",
// Ordering::Equal => "Equal",
// }
// );
ret
}
pub fn natural_sort(v: &mut Vec<&str>) {
v.sort_unstable_by(|a, b| NaturalSort::strcmp_natural(&a, &b));
}
}
#[cfg(test)]
mod tests {
use crate::natural_sort::NaturalSort;
use std::cmp::Ordering;
#[test]
fn test_natural_sort_1() {
let mut vec = vec!["10", "9", "8", "7", "5", "1", "2", "3", "4", "6"];
let expected = vec!["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
NaturalSort::natural_sort(&mut vec);
assert_eq!(vec, expected);
}
#[test]
fn test_natural_sort_2() {
let mut vec = vec![
"a100a", "a100", "a", "a10", "a2", "a200", "a20", "a1", "a100a10", "a100a1",
];
let expected = vec![
"a", "a1", "a2", "a10", "a20", "a100", "a100a", "a100a1", "a100a10", "a200",
];
NaturalSort::natural_sort(&mut vec);
assert_eq!(vec, expected);
}
#[test]
fn test_strcmp_natural() {
assert_eq!(NaturalSort::strcmp_natural("1", "2"), Ordering::Less);
assert_eq!(NaturalSort::strcmp_natural("2", "2"), Ordering::Equal);
assert_eq!(NaturalSort::strcmp_natural("3", "2"), Ordering::Greater);
}
#[test]
fn test_strcmp_natural_equal() {
let a = "a100";
let b = "a100";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Equal);
}
#[test]
fn test_strcmp_natural_equal_alpha() {
let a = "aaa";
let b = "aaa";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Equal);
}
#[test]
fn test_strcmp_natural_greater_1() {
let a = "a100";
let b = "a10";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Greater);
}
#[test]
fn test_strcmp_natural_greater_2() {
let a = "a10b";
let b = "a10a";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Greater);
}
#[test]
fn test_strcmp_natural_greater_3() {
let a = "a10a100";
let b = "a10a10";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Greater);
}
#[test]
fn test_strcmp_natural_greater_4() {
let a = "a200";
let b = "a100a";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Greater);
}
#[test]
fn test_strcmp_natural_less_1() {
let a = "a10";
let b = "a100";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Less);
}
#[test]
fn test_strcmp_natural_less_2() {
let a = "a10a";
let b = "a10b";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Less);
}
#[test]
fn test_strcmp_natural_less_3() {
let a = "a10a100";
let b = "a10b10";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Less);
}
#[test]
fn test_strcmp_natural_less_4() {
let a = "a100a";
let b = "a200";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Less);
}
#[test]
fn test_strcmp_natural_greater_alpha_1() {
let a = "baa";
let b = "aaa";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Greater);
}
#[test]
fn test_strcmp_natural_greater_alpha_2() {
let a = "aba";
let b = "aaa";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Greater);
}
#[test]
fn test_strcmp_natural_greater_alpha_3() {
let a = "aab";
let b = "aaa";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Greater);
}
#[test]
fn test_strcmp_natural_less_alpha_1() {
let a = "aaa";
let b = "baa";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Less);
}
#[test]
fn test_strcmp_natural_less_alpha_2() {
let a = "aaa";
let b = "aba";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Less);
}
#[test]
fn test_strcmp_natural_less_alpha_3() {
let a = "aaa";
let b = "aab";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Less);
}
#[test]
fn test_strcmp_natural_greater_number_1() {
let a = "100b";
let b = "100a";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Greater);
}
#[test]
fn test_strcmp_natural_less_number_1() {
let a = "100a";
let b = "100b";
let result = NaturalSort::strcmp_natural(a, b);
assert!(result == Ordering::Less);
}
}
| true |
ceb9615477eae540dce6be43fc8a9b18d03fdf58
|
Rust
|
Emerentius/drain_experiments
|
/src/_try_drain.rs
|
UTF-8
| 635 | 2.828125 | 3 |
[] |
no_license
|
pub(crate) struct _TryDrain<'a, T: 'a> {
pub vec: &'a mut Vec<T>,
pub finished: bool,
pub idx: usize,
pub del: usize,
pub old_len: usize,
}
impl<'a, T: 'a> _TryDrain<'a, T> {
pub fn tail_len(&self) -> usize {
self.old_len - self.idx
}
}
impl<'a, T: 'a> _TryDrain<'a, T> {
pub fn new(vec: &'a mut Vec<T>) -> Self {
let old_len = vec.len();
// Guard against us getting leaked (leak amplification)
unsafe { vec.set_len(0); }
_TryDrain {
vec,
finished: false,
idx: 0,
del: 0,
old_len,
}
}
}
| true |
c4431e79f9f4751fcd73fee8b29cec34db27cfb6
|
Rust
|
mcginty/snow
|
/src/error.rs
|
UTF-8
| 6,098 | 3.1875 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! All error types used by Snow operations.
use std::fmt;
/// `snow` provides decently detailed errors, exposed as the [`Error`] enum,
/// to allow developers to react to errors in a more actionable way.
///
/// *With that said*, security vulnerabilities *can* be introduced by passing
/// along detailed failure information to an attacker. While an effort was
/// made to not make any particularly foolish choices in this regard, we strongly
/// recommend you don't dump the `Debug` output to a user, for example.
///
/// This enum is intentionally non-exhasutive to allow new error types to be
/// introduced without causing a breaking API change.
///
/// `snow` may eventually add a feature flag and enum variant to only return
/// an "unspecified" error for those who would prefer safety over observability.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// The noise pattern failed to parse.
Pattern(PatternProblem),
/// Initialization failure, at a provided stage.
Init(InitStage),
/// Missing prerequisite material.
Prereq(Prerequisite),
/// An error in `snow`'s internal state.
State(StateProblem),
/// Invalid input.
Input,
/// Diffie-Hellman agreement failed.
Dh,
/// Decryption failed.
Decrypt,
/// Key-encapsulation failed
#[cfg(feature = "hfs")]
Kem,
}
/// The various stages of initialization used to help identify
/// the specific cause of an `Init` error.
#[derive(Debug)]
pub enum PatternProblem {
/// Caused by a pattern string that is too short and malformed (e.g. `Noise_NN_25519`).
TooFewParameters,
/// The handshake section of the string (e.g. `XXpsk3`) isn't supported. Check for typos
/// and necessary feature flags.
UnsupportedHandshakeType,
/// This was a trick choice -- an illusion. The correct answer was `Noise`.
UnsupportedBaseType,
/// Invalid hash type (e.g. `BLAKE2s`).
/// Check that there are no typos and that any feature flags you might need are toggled
UnsupportedHashType,
/// Invalid DH type (e.g. `25519`).
/// Check that there are no typos and that any feature flags you might need are toggled
UnsupportedDhType,
/// Invalid cipher type (e.g. `ChaChaPoly`).
/// Check that there are no typos and that any feature flags you might need are toggled
UnsupportedCipherType,
/// The PSK position must be a number, and a pretty small one at that.
InvalidPsk,
/// Invalid modifier (e.g. `fallback`).
/// Check that there are no typos and that any feature flags you might need are toggled
UnsupportedModifier,
#[cfg(feature = "hfs")]
/// Invalid KEM type.
/// Check that there are no typos and that any feature flags you might need are toggled
UnsupportedKemType,
}
impl From<PatternProblem> for Error {
fn from(reason: PatternProblem) -> Self {
Error::Pattern(reason)
}
}
/// The various stages of initialization used to help identify
/// the specific cause of an `Init` error.
#[derive(Debug)]
pub enum InitStage {
/// Provided and received key lengths were not equal.
ValidateKeyLengths,
/// Provided and received preshared key lengths were not equal.
ValidatePskLengths,
/// Two separate cipher algorithms were initialized.
ValidateCipherTypes,
/// The RNG couldn't be initialized.
GetRngImpl,
/// The DH implementation couldn't be initialized.
GetDhImpl,
/// The cipher implementation couldn't be initialized.
GetCipherImpl,
/// The hash implementation couldn't be initialized.
GetHashImpl,
#[cfg(feature = "hfs")]
/// The KEM implementation couldn't be initialized.
GetKemImpl,
/// The PSK position (specified in the pattern string) isn't valid for the given
/// handshake type.
ValidatePskPosition,
}
impl From<InitStage> for Error {
fn from(reason: InitStage) -> Self {
Error::Init(reason)
}
}
/// A prerequisite that may be missing.
#[derive(Debug)]
pub enum Prerequisite {
/// A local private key wasn't provided when it was needed by the selected pattern.
LocalPrivateKey,
/// A remote public key wasn't provided when it was needed by the selected pattern.
RemotePublicKey,
}
impl From<Prerequisite> for Error {
fn from(reason: Prerequisite) -> Self {
Error::Prereq(reason)
}
}
/// Specific errors in the state machine.
#[derive(Debug)]
pub enum StateProblem {
/// Missing key material in the internal handshake state.
MissingKeyMaterial,
/// Preshared key missing in the internal handshake state.
MissingPsk,
/// You attempted to write a message when it's our turn to read.
NotTurnToWrite,
/// You attempted to read a message when it's our turn to write.
NotTurnToRead,
/// You tried to go into transport mode before the handshake was done.
HandshakeNotFinished,
/// You tried to continue the handshake when it was already done.
HandshakeAlreadyFinished,
/// You called a method that is only valid if this weren't a one-way handshake.
OneWay,
/// The nonce counter attempted to go higher than (2^64) - 1
Exhausted,
}
impl From<StateProblem> for Error {
fn from(reason: StateProblem) -> Self {
Error::State(reason)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Pattern(reason) => write!(f, "pattern error: {:?}", reason),
Error::Init(reason) => {
write!(f, "initialization error: {:?}", reason)
},
Error::Prereq(reason) => {
write!(f, "prerequisite error: {:?}", reason)
},
Error::State(reason) => write!(f, "state error: {:?}", reason),
Error::Input => write!(f, "input error"),
Error::Dh => write!(f, "diffie-hellman error"),
Error::Decrypt => write!(f, "decrypt error"),
#[cfg(feature = "hfs")]
Error::Kem => write!(f, "kem error"),
}
}
}
impl std::error::Error for Error {}
| true |
ca3afa77fd4d2fa3275e2996416d425dcf3e5175
|
Rust
|
Sword-Smith/rust-tutorial
|
/src/scoping_rules/aliasing.rs
|
UTF-8
| 1,686 | 3.9375 | 4 |
[
"Unlicense"
] |
permissive
|
struct Point {
x: i32,
y: i32,
z: i32,
}
pub fn aliasing() {
let mut point = Point { x: 0, y: 0, z: 0 };
let borrowed_point = &point;
let another_borrow = &point;
println!(
"Point has coordinates: ({}, {}, {})",
borrowed_point.x, borrowed_point.y, borrowed_point.z
);
// `point` cannot be mutably borrowed because it is currently immutably borrowed.
// let mutable_borrow = &mut point;
// The borrowed values are used again here
println!(
"Point has coordinates: ({}, {}, {})",
borrowed_point.x, another_borrow.y, point.z
);
// Here, the immutable borrows are garbage collected, since they are not used later in the program.
// The immutable references are no longer used for the rest of the code, so it is possible to reborrow with a mutable reference.
let mutable_borrow = &mut point;
mutable_borrow.x = 5;
mutable_borrow.y = 2;
mutable_borrow.z = 1;
// point cannot be borrowed as immutable because it's currently borrowed as mutable
// let y = &point.y;
// point cannot be printed, since the `println!` macro takes an immutable borrow.
// println!("Point Z coordinate is {}", point.z);
// Mutable references can, however, be passed as immutable to `println!`. So it *is* possible to print even though a mutable reference exists.
println!(
"Point has coordinates: ({}, {}, {})",
mutable_borrow.x, mutable_borrow.y, mutable_borrow.z
);
let new_borrowed_point = &point;
println!(
"Point now has coordinates: ({}, {}, {})",
new_borrowed_point.x, new_borrowed_point.y, new_borrowed_point.z
);
}
| true |
526875f2de9cf68692eb0842ffbcd673d534e6f8
|
Rust
|
LesnyRumcajs/wakey
|
/wakey/src/lib.rs
|
UTF-8
| 8,182 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
//! Library for managing Wake-on-LAN packets.
//! # Example
//! ```
//! let wol = wakey::WolPacket::from_string("01:02:03:04:05:06", ':').unwrap();
//! if wol.send_magic().is_ok() {
//! println!("Sent the magic packet!");
//! } else {
//! println!("Failed to send the magic packet!");
//! }
//! ```
use std::error::Error;
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
use std::{fmt, iter};
use arrayvec::ArrayVec;
const MAC_SIZE: usize = 6;
const MAC_PER_MAGIC: usize = 16;
const HEADER: [u8; 6] = [0xFF; 6];
const PACKET_LEN: usize = HEADER.len() + MAC_SIZE * MAC_PER_MAGIC;
type Packet = ArrayVec<u8, PACKET_LEN>;
type Mac = ArrayVec<u8, MAC_SIZE>;
/// Wrapper `Result` for the module errors.
pub type Result<T> = std::result::Result<T, WakeyError>;
/// Wrapper Error for fiascoes occuring in this module.
#[derive(Debug)]
pub enum WakeyError {
/// The provided MAC address has invalid length.
InvalidMacLength,
/// The provided MAC address has invalid format.
InvalidMacFormat,
/// There was an error sending the WoL packet.
SendFailure(std::io::Error),
}
impl Error for WakeyError {}
impl fmt::Display for WakeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
WakeyError::InvalidMacLength => {
write!(f, "Invalid MAC address length")
}
WakeyError::InvalidMacFormat => write!(f, "Invalid MAC address format"),
WakeyError::SendFailure(e) => write!(f, "Couldn't send WoL packet: {e}"),
}
}
}
impl From<std::io::Error> for WakeyError {
fn from(error: std::io::Error) -> Self {
WakeyError::SendFailure(error)
}
}
/// Wake-on-LAN packet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WolPacket {
/// WOL packet bytes
packet: Packet,
}
impl WolPacket {
/// Creates WOL packet from byte MAC representation
/// # Example
/// ```
/// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]);
/// ```
pub fn from_bytes(mac: &[u8]) -> Result<WolPacket> {
Ok(WolPacket {
packet: WolPacket::create_packet_bytes(mac)?,
})
}
/// Creates WOL packet from string MAC representation (e.x. 00:01:02:03:04:05)
/// # Example
/// ```
/// let wol = wakey::WolPacket::from_string("00:01:02:03:04:05", ':');
/// ```
/// # Panic
/// Panics when input MAC is invalid (i.e. contains non-byte characters)
pub fn from_string<T: AsRef<str>>(data: T, sep: char) -> Result<WolPacket> {
WolPacket::from_bytes(&WolPacket::mac_to_byte(data, sep)?)
}
/// Broadcasts the magic packet from / to default address
/// Source: 0.0.0.0:0
/// Destination 255.255.255.255:9
/// # Example
/// ```
/// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]).unwrap();
/// wol.send_magic();
/// ```
pub fn send_magic(&self) -> Result<()> {
self.send_magic_to(
SocketAddr::from(([0, 0, 0, 0], 0)),
SocketAddr::from(([255, 255, 255, 255], 9)),
)
}
/// Broadcasts the magic packet from / to specified address.
/// # Example
/// ```
/// use std::net::SocketAddr;
/// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]).unwrap();
/// let src = SocketAddr::from(([0,0,0,0], 0));
/// let dst = SocketAddr::from(([255,255,255,255], 9));
/// wol.send_magic_to(src, dst);
/// ```
pub fn send_magic_to<A: ToSocketAddrs>(&self, src: A, dst: A) -> Result<()> {
let udp_sock = UdpSocket::bind(src)?;
udp_sock.set_broadcast(true)?;
udp_sock.send_to(&self.packet, dst)?;
Ok(())
}
/// Returns the underlying WoL packet bytes
pub fn into_inner(self) -> Packet {
self.packet
}
/// Converts string representation of MAC address (e.x. 00:01:02:03:04:05) to raw bytes.
/// # Panic
/// Panics when input MAC is invalid (i.e. contains non-byte characters)
fn mac_to_byte<T: AsRef<str>>(data: T, sep: char) -> Result<Mac> {
// hex-encoded bytes * 2 plus separators
if data.as_ref().len() != MAC_SIZE * 3 - 1 {
return Err(WakeyError::InvalidMacLength);
}
let bytes = data
.as_ref()
.split(sep)
.map(|x| hex::decode(x).map_err(|_| WakeyError::InvalidMacFormat))
.collect::<Result<ArrayVec<_, MAC_SIZE>>>()?
.into_iter()
.flatten()
.collect::<Mac>();
debug_assert_eq!(MAC_SIZE, bytes.len());
Ok(bytes)
}
/// Extends the MAC address to fill the magic packet
fn extend_mac(mac: &[u8]) -> ArrayVec<u8, { MAC_SIZE * MAC_PER_MAGIC }> {
let magic = iter::repeat(mac)
.take(MAC_PER_MAGIC)
.flatten()
.copied()
.collect::<ArrayVec<u8, { MAC_SIZE * MAC_PER_MAGIC }>>();
debug_assert_eq!(MAC_SIZE * MAC_PER_MAGIC, magic.len());
magic
}
/// Creates bytes of the magic packet from MAC address
fn create_packet_bytes(mac: &[u8]) -> Result<Packet> {
if mac.len() != MAC_SIZE {
return Err(WakeyError::InvalidMacLength);
}
let mut packet = Packet::new();
packet.extend(HEADER);
packet.extend(WolPacket::extend_mac(mac));
debug_assert_eq!(PACKET_LEN, packet.len());
Ok(packet)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extend_mac_test() {
let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
let extended_mac = WolPacket::extend_mac(&mac);
assert_eq!(extended_mac.len(), MAC_PER_MAGIC * MAC_SIZE);
assert_eq!(&extended_mac[(MAC_PER_MAGIC - 1) * MAC_SIZE..], &mac[..]);
}
#[test]
#[should_panic]
fn extend_mac_mac_too_long_test() {
let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
WolPacket::extend_mac(&mac);
}
#[test]
#[should_panic]
fn extend_mac_mac_too_short_test() {
let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05];
WolPacket::extend_mac(&mac);
}
#[test]
fn mac_to_byte_test() {
let mac = "01:02:03:04:05:06";
let result = WolPacket::mac_to_byte(mac, ':');
assert_eq!(
result.unwrap().into_inner().unwrap(),
[0x01, 0x02, 0x03, 0x04, 0x05, 0x06]
);
}
#[test]
fn mac_to_byte_invalid_chars_test() {
let mac = "ZZ:02:03:04:05:06";
assert!(matches!(
WolPacket::mac_to_byte(mac, ':'),
Err(WakeyError::InvalidMacFormat)
));
}
#[test]
fn mac_to_byte_invalid_separator_test() {
let mac = "01002:03:04:05:06";
assert!(matches!(
WolPacket::mac_to_byte(mac, ':'),
Err(WakeyError::InvalidMacFormat)
));
}
#[test]
fn mac_to_byte_mac_too_long_test() {
let mac = "01:02:03:04:05:06:07";
assert!(matches!(
WolPacket::mac_to_byte(mac, ':'),
Err(WakeyError::InvalidMacLength)
));
}
#[test]
fn mac_to_byte_mac_too_short_test() {
let mac = "01:02:03:04:05";
assert!(matches!(
WolPacket::mac_to_byte(mac, ':'),
Err(WakeyError::InvalidMacLength)
));
}
#[test]
fn create_packet_bytes_test() {
let bytes = WolPacket::create_packet_bytes(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).unwrap();
assert_eq!(bytes.len(), MAC_SIZE * MAC_PER_MAGIC + HEADER.len());
assert!(bytes.iter().all(|&x| x == 0xFF));
}
#[test]
fn create_wol_packet() {
let mac = vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05];
let wol = WolPacket::from_bytes(&mac).unwrap();
let packet = wol.into_inner();
assert_eq!(packet.len(), PACKET_LEN);
assert_eq!(
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
&packet[0..HEADER.len()]
);
for offset in (HEADER.len()..PACKET_LEN).step_by(MAC_SIZE) {
assert_eq!(&mac, &packet[offset..offset + MAC_SIZE]);
}
}
}
| true |
a232e300facfddb1c1cdf3e918b9ed7271ab9e16
|
Rust
|
jakewitcher/rusty_parsec
|
/tests/combinators_pipe_tests.rs
|
UTF-8
| 8,024 | 2.953125 | 3 |
[] |
no_license
|
mod common;
use common::*;
use rusty_parsec::*;
#[test]
fn tuple_2_run_simple_parserss_succeeds() {
let expected = Ok(ParserSuccess::new(
(123, String::from("hello")),
Position::new(1, 9, 8)
));
let actual = tuple_2(
p_u32(),
p_hello()
).run(String::from("123hello"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_2_run_simple_parsers_fails_with_error_at_first_parser() {
let expected = Err(ParserFailure::new_err(
String::from("integral value"),
None,
Position::new(1, 1, 0)
));
let actual = tuple_2(
p_u32(),
p_hello()
).run(String::from("hello123"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_2_run_complex_parsers_fails_with_fatal_error_at_first_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("integral value"),
None,
Position::new(1, 4, 3)
));
let actual = tuple_2(
p_abc_123(),
p_hello()
).run(String::from("abcdefhello"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_2_run_simple_parsers_fails_with_fatal_error_at_second_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("hello"),
Some(String::from("world")),
Position::new(1, 4, 3)
));
let actual = tuple_2(
p_u32(),
p_hello()
).run(String::from("123world"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_2_run_complex_parsers_fails_with_fatal_error_at_second_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("integral value"),
None,
Position::new(1, 7, 6)
));
let actual = tuple_2(
p_u32(),
p_abc_123()
).run(String::from("100abcdef"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_3_run_simple_parserss_succeeds() {
let expected = Ok(ParserSuccess::new(
(String::from("hello"), 123 , true),
Position::new(1, 13, 12)
));
let actual = tuple_3(
p_hello(),
p_u32(),
p_true()
).run(String::from("hello123true"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_3_run_simple_parsers_fails_with_error_at_first_parser() {
let expected = Err(ParserFailure::new_err(
String::from("hello"),
Some(String::from("world")),
Position::new(1, 1, 0)
));
let actual = tuple_3(
p_hello(),
p_u32(),
p_true()
).run(String::from("world123true"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_3_run_simple_parsers_fails_with_fatal_error_at_second_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("integral value"),
None,
Position::new(1, 6, 5)
));
let actual = tuple_3(
p_hello(),
p_u32(),
p_true()
).run(String::from("helloabctrue"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_3_run_simple_parsers_fails_with_fatal_error_at_third_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("true"),
Some(String::from("fals")),
Position::new(1, 9, 8)
));
let actual = tuple_3(
p_hello(),
p_u32(),
p_true()
).run(String::from("hello123false"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_4_run_simple_parserss_succeeds() {
let expected = Ok(ParserSuccess::new(
(String::from("hello"), 123 , true, 1.5),
Position::new(1, 16, 15)
));
let actual = tuple_4(
p_hello(),
p_u32(),
p_true(),
p_f32()
).run(String::from("hello123true1.5"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_4_run_simple_parsers_fails_with_error_at_first_parser() {
let expected = Err(ParserFailure::new_err(
String::from("hello"),
Some(String::from("world")),
Position::new(1, 1, 0)
));
let actual = tuple_4(
p_hello(),
p_u32(),
p_true(),
p_f32()
).run(String::from("world123true1.5"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_4_run_simple_parsers_fails_with_fatal_error_at_second_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("integral value"),
None,
Position::new(1, 6, 5)
));
let actual = tuple_4(
p_hello(),
p_u32(),
p_true(),
p_f32()
).run(String::from("helloabctrue1.5"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_4_run_simple_parsers_fails_with_fatal_error_at_third_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("true"),
Some(String::from("fals")),
Position::new(1, 9, 8)
));
let actual = tuple_4(
p_hello(),
p_u32(),
p_true(),
p_f32()
).run(String::from("hello123false1.5"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_4_run_simple_parsers_fails_with_fatal_error_at_fourth_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("floating point value"),
None,
Position::new(1, 13, 12)
));
let actual = tuple_4(
p_hello(),
p_u32(),
p_true(),
p_f32()
).run(String::from("hello123trueabc"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_5_run_simple_parserss_succeeds() {
let expected = Ok(ParserSuccess::new(
(String::from("hello"), 123 , true, 1.5, 'a'),
Position::new(1, 17, 16)
));
let actual = tuple_5(
p_hello(),
p_u32(),
p_true(),
p_f32(),
p_char('a')
).run(String::from("hello123true1.5a"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_5_run_simple_parsers_fails_with_error_at_first_parser() {
let expected = Err(ParserFailure::new_err(
String::from("hello"),
Some(String::from("world")),
Position::new(1, 1, 0)
));
let actual = tuple_5(
p_hello(),
p_u32(),
p_true(),
p_f32(),
p_char('a')
).run(String::from("world123true1.5a"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_5_run_simple_parsers_fails_with_fatal_error_at_second_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("integral value"),
None,
Position::new(1, 6, 5)
));
let actual = tuple_5(
p_hello(),
p_u32(),
p_true(),
p_f32(),
p_char('a')
).run(String::from("helloabctrue1.5a"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_5_run_simple_parsers_fails_with_fatal_error_at_third_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("true"),
Some(String::from("fals")),
Position::new(1, 9, 8)
));
let actual = tuple_5(
p_hello(),
p_u32(),
p_true(),
p_f32(),
p_char('a')
).run(String::from("hello123false1.5a"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_5_run_simple_parsers_fails_with_fatal_error_at_fourth_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("floating point value"),
None,
Position::new(1, 13, 12)
));
let actual = tuple_5(
p_hello(),
p_u32(),
p_true(),
p_f32(),
p_char('a')
).run(String::from("hello123trueabca"));
assert_eq!(actual, expected);
}
#[test]
fn tuple_5_run_simple_parsers_fails_with_fatal_error_at_fifth_parser() {
let expected = Err(ParserFailure::new_fatal_err(
String::from("a"),
Some(String::from("c")),
Position::new(1, 16, 15)
));
let actual = tuple_5(
p_hello(),
p_u32(),
p_true(),
p_f32(),
p_char('a')
).run(String::from("hello123true1.5c"));
assert_eq!(actual, expected);
}
| true |
4b8fcb648752536f375db1cfc68305433d23757c
|
Rust
|
morri2/leonardp-chess
|
/hansing_gui/src/texturepack.rs
|
UTF-8
| 1,041 | 2.984375 | 3 |
[] |
no_license
|
use ggez::graphics::*;
use ggez::Context;
pub struct Texturepack {
pub piece_texture: Vec<Image>,
pub placeholder: bool,
}
impl Texturepack {
pub fn new_placeholder() -> Self {
Self {
piece_texture: Vec::new(),
placeholder: true,
}
}
pub fn new() -> Self {
Self {
piece_texture: Vec::new(),
placeholder: false,
}
}
pub fn texture_from_index(&self, index: usize) -> Option<Image> {
if index >= self.piece_texture.len() {
None
} else {
Some(self.piece_texture[index].clone())
}
}
}
const PIECE_NAMES: [&str; 6] = ["pawn", "knight", "bishop", "rook", "queen", "king"];
pub fn make_texturepack(c: &mut Context) -> Texturepack {
let mut tp = Texturepack::new();
for color in ["w", "b"].iter() {
for piece in PIECE_NAMES.iter() {
tp.piece_texture
.push(Image::new(c, format!("/{}_{}.png", color, piece)).unwrap());
}
}
tp
}
| true |
90314fd979ff038c488ca7660245ef6f21d74452
|
Rust
|
htk16/build_your_own_lisp_in_rust
|
/src/error.rs
|
UTF-8
| 811 | 3.078125 | 3 |
[] |
no_license
|
use crate::expression::{Expression, ExpressionType};
use anyhow::{anyhow, Error};
pub fn argument_error(name: &str, required: usize, passed: usize) -> Error {
anyhow!(
"Function '{}' required {} argument(s), but passed {}",
name,
required,
passed
)
}
pub fn type_error(required: ExpressionType, passed: ExpressionType) -> Error {
anyhow!("{} required, but passed {}", required.name(), passed.name())
}
pub fn expression_type_error(required: ExpressionType, passed: &Expression) -> Error {
anyhow!(
"{} required, but passed {} ({})",
required.name(),
passed.type_name(),
passed.to_string()
)
}
pub fn divide_by_zero() -> Error {
anyhow!("Divide by zero")
}
pub fn fatal_error() -> Error {
anyhow!("Fatal error!")
}
| true |
f3b440009a19c0b5955fe0a8c93c39cc5e7fb671
|
Rust
|
oli-obk/stdsimd
|
/coresimd/ppsv/api/masks_select.rs
|
UTF-8
| 1,741 | 2.90625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! Mask select method
#![allow(unused)]
/// Implements mask select method
macro_rules! impl_mask_select {
($id:ident, $elem_ty:ident, $elem_count:expr) => {
impl $id {
/// Selects elements of `a` and `b` using mask.
///
/// For each lane, the result contains the element of `a` if the
/// mask is true, and the element of `b` otherwise.
#[inline]
pub fn select<T>(self, a: T, b: T) -> T
where
T: super::api::Lanes<[u32; $elem_count]>,
{
use coresimd::simd_llvm::simd_select;
unsafe { simd_select(self, a, b) }
}
}
};
}
#[cfg(test)]
macro_rules! test_mask_select {
($mask_id:ident, $vec_id:ident, $elem_ty:ident) => {
#[test]
fn select() {
use coresimd::simd::{$mask_id, $vec_id};
let o = 1 as $elem_ty;
let t = 2 as $elem_ty;
let a = $vec_id::splat(o);
let b = $vec_id::splat(t);
let m = a.lt(b);
assert_eq!(m.select(a, b), a);
let m = b.lt(a);
assert_eq!(m.select(b, a), a);
let mut c = a;
let mut d = b;
let mut m_e = $mask_id::splat(false);
for i in 0..$vec_id::lanes() {
if i % 2 == 0 {
let c_tmp = c.extract(i);
c = c.replace(i, d.extract(i));
d = d.replace(i, c_tmp);
} else {
m_e = m_e.replace(i, true);
}
}
let m = c.lt(d);
assert_eq!(m_e, m);
assert_eq!(m.select(c, d), a);
}
};
}
| true |
adc493372f1d80fce1493c1c4fe92be471cee502
|
Rust
|
tov/succinct-rs
|
/src/rank/prim.rs
|
UTF-8
| 2,698 | 2.890625 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use rank::{BitRankSupport, RankSupport};
use storage::BlockType;
macro_rules! impl_rank_support_prim {
( $t:ident )
=>
{
impl RankSupport for $t {
type Over = bool;
fn rank(&self, position: u64, value: bool) -> u64 {
if value {self.rank1(position)} else {self.rank0(position)}
}
fn limit(&self) -> u64 {
Self::nbits() as u64
}
}
impl BitRankSupport for $t {
fn rank1(&self, position: u64) -> u64 {
debug_assert!(position < Self::nbits() as u64);
let mask = Self::low_mask((position + 1) as usize);
(*self & mask).count_ones() as u64
}
}
}
}
impl_rank_support_prim!(u8);
impl_rank_support_prim!(u16);
impl_rank_support_prim!(u32);
impl_rank_support_prim!(u64);
impl_rank_support_prim!(usize);
#[cfg(test)]
mod test {
use rank::*;
#[test]
fn rank1() {
assert_eq!(0, 0b00000000u8.rank1(0));
assert_eq!(0, 0b00000000u8.rank1(7));
assert_eq!(1, 0b01010101u8.rank1(0));
assert_eq!(1, 0b01010101u8.rank1(1));
assert_eq!(2, 0b01010101u8.rank1(2));
assert_eq!(2, 0b01010101u8.rank1(3));
assert_eq!(3, 0b00001111u8.rank1(2));
assert_eq!(4, 0b00001111u8.rank1(3));
assert_eq!(4, 0b00001111u8.rank1(4));
assert_eq!(4, 0b00001111u8.rank1(5));
assert_eq!(4, 0b00001111u8.rank1(7));
assert_eq!(0, 0b11110000u8.rank1(0));
assert_eq!(0, 0b11110000u8.rank1(3));
assert_eq!(1, 0b11110000u8.rank1(4));
assert_eq!(2, 0b11110000u8.rank1(5));
assert_eq!(4, 0b11110000u8.rank1(7));
}
#[test]
fn rank0() {
assert_eq!(1, 0b00000000u8.rank0(0));
assert_eq!(8, 0b00000000u8.rank0(7));
assert_eq!(0, 0b01010101u8.rank0(0));
assert_eq!(1, 0b01010101u8.rank0(1));
assert_eq!(1, 0b01010101u8.rank0(2));
assert_eq!(2, 0b01010101u8.rank0(3));
}
#[test]
fn rank() {
assert_eq!(1, 0b00000000u8.rank(0, false));
assert_eq!(8, 0b00000000u8.rank(7, false));
assert_eq!(0, 0b01010101u8.rank(0, false));
assert_eq!(1, 0b01010101u8.rank(1, false));
assert_eq!(1, 0b01010101u8.rank(2, false));
assert_eq!(2, 0b01010101u8.rank(3, false));
assert_eq!(0, 0b00000000u8.rank(0, true));
assert_eq!(0, 0b00000000u8.rank(7, true));
assert_eq!(1, 0b01010101u8.rank(0, true));
assert_eq!(1, 0b01010101u8.rank(1, true));
assert_eq!(2, 0b01010101u8.rank(2, true));
assert_eq!(2, 0b01010101u8.rank(3, true));
}
}
| true |
f47bc13d0a34d2272755d51dc23cea2753f2a5d7
|
Rust
|
torourk/padding-oracle-visual
|
/src/main.rs
|
UTF-8
| 1,752 | 2.671875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use aes::Aes128;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
use hkdf::Hkdf;
use sha2::Sha256;
use rand::rngs::OsRng;
use rand::RngCore;
use colored::*;
use std::io::{self, Write};
pub mod adversary;
pub mod oracle;
pub mod ui;
use adversary::Adversary;
use oracle::Oracle;
type Aes128Cbc = Cbc<Aes128, Pkcs7>;
fn main() {
println!("{}", "--- Padding Oracle Attack ---".bold());
print!(
"{}{}{}",
"Enter key ",
"(Derived using SHA256-HKDF)".italic(),
": "
);
io::stdout().flush().unwrap();
// Reads a key string
let mut key_str = String::new();
io::stdin().read_line(&mut key_str).unwrap();
print!("Enter message: ");
io::stdout().flush().unwrap();
// Reads a message string
let mut msg_str = String::new();
io::stdin().read_line(&mut msg_str).unwrap();
if msg_str.ends_with("\n") {
msg_str.truncate(msg_str.len() - 1);
}
// Derives a key using HKDF-SHA256 (weak password key derivation is sufficient for demonstration purposes)
let hkdf = Hkdf::<Sha256>::new(None, key_str.as_bytes());
let mut key = [0u8; 16];
hkdf.expand(&[], &mut key).unwrap();
// Creates a random IV
let mut iv = [0u8; 16];
OsRng.fill_bytes(&mut iv);
// Encrypts the message using AES-128 in CBC mode
let aes_cipher = Aes128Cbc::new_var(&key, &iv).unwrap();
let cipher = aes_cipher.encrypt_vec(msg_str.as_bytes());
// Creates a keyed oracle
let oracle = Oracle::new(&key);
// Sends the oracle, IV, and ciphertext to the adversary
let adversary = Adversary::new(oracle, iv.to_vec(), cipher.clone());
println!();
// Runs the attack
adversary.break_ciphertext_fancy();
}
| true |
47c43205b241d5e519df64d54b334483fd9701e4
|
Rust
|
zexa/json_gatherer
|
/src/main.rs
|
UTF-8
| 1,175 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
use serde_json;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::collections::HashMap;
struct JsonFile {
stem: String,
content: String,
}
fn get_dir_json(P: &Path) -> io::Result<()> {
let entries = fs::read_dir(P)?
.map(|res| res.map(|e| e.path()))
.map(|path| path.map(|p| get_file_json(p).unwrap()))
.collect::<Result<Vec<_>, io::Error>>()?;
Ok(())
}
fn serialize_json_file(input: Vec<JsonFile>) -> io::Result<serde_json::Value> {
let hash: HashMap<String, serde_json::Value> = HashMap::new();
in
Ok()
}
fn get_file_json(file: PathBuf) -> io::Result<JsonFile> {
Ok(JsonFile {
stem: match file.file_stem() {
None => panic!("Could not read file stem"),
Some(file_stem) => match file_stem.to_str() {
None => panic!("Could not convert OsStr to String"),
Some(file_stem_str) => file_stem_str,
}
}.to_string(),
content: fs::read_to_string(file)?
})
}
fn main() {
get_dir_json(Path::new("/home/zexa/Projects/get-files/src/examples"))
.expect("Could not read directory");
}
| true |
7e4864b2fcd1fb13428c10492b3e0aa9f23ea016
|
Rust
|
germolinal/PhD_Thesis_Simulations
|
/src/lib.rs
|
UTF-8
| 2,352 | 2.84375 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use simulation_state::simulation_state::SimulationState;
use building_model::building::Building;
use communication_protocols::simulation_model::SimulationModel;
use calendar::date_factory::DateFactory;
use calendar::date::Date;
use people::people::People;
use multiphysics_model::multiphysics_model::MultiphysicsModel;
use weather::Weather;
use simple_results::{SimulationResults, TimeStepResults};
/// This function drives the simulation, after having parsed and built
/// the Building, State and Peoeple.
pub fn run(start: Date, end: Date, person: &dyn People, building: &mut Building, state: &mut SimulationState, weather: &dyn Weather, n: usize)->Result<SimulationResults,String>{
if start == end || start.is_later(end) {
return Err(format!("Time period inconsistency... Start = {} | End = {}", start, end));
}
let model = match MultiphysicsModel::new(&building, state, n){
Ok(v)=>v,
Err(e)=>return Err(e),
};
// Map the state
building.map_simulation_state(state)?;
// Calculate timestep and build the Simulation Period
let dt = 60. * 60. / n as f64;
let sim_period = DateFactory::new(start, end, dt);
// TODO: Calculate the capacity needed for the results
let mut results = SimulationResults::new();
// Simulate the whole simulation period
for date in sim_period {
// initialize results struct
let mut step_results = TimeStepResults{
timestep_start : date,
state_elements : state.elements().clone(),
weather : weather.get_weather_data(date),
controllers: HashMap::new()
};
// Get the current weather data
//let current_weather = weather.get_weather_data(date);
// Make the model march
match model.march(date, weather, building, state ) {
Ok(_)=>{},
Err(e) => panic!(e)
}
// Control the building or person, if needed
let person_result = person.control(date, weather, building, &model, state);
step_results.controllers.insert(format!("person"), person_result);
// push results
results.push(step_results);
}
Ok(results)
}
| true |
978dafdab1d99635532f89a8593fd37b773897e1
|
Rust
|
karjonas/advent-of-code
|
/2016/day18/src/lib.rs
|
UTF-8
| 1,658 | 3.203125 | 3 |
[] |
no_license
|
use std::fs::File;
use std::io::prelude::*;
fn is_trap(r: usize, c: usize, num_cols: usize, grid: &Vec<Vec<bool>>) -> bool {
let left = if c == 0 { false } else { grid[r - 1][c - 1] };
let center = grid[r - 1][c];
let right = if c == num_cols - 1 {
false
} else {
grid[r - 1][c + 1]
};
let p = (left, center, right);
return p == (true, true, false)
|| p == (false, true, true)
|| p == (true, false, false)
|| p == (false, false, true);
}
fn generate_rows(start: Vec<bool>, num_rows_inclusive: usize) -> Vec<Vec<bool>> {
let num_cols = start.len();
let mut output: Vec<Vec<bool>> = Vec::new();
output.resize(num_rows_inclusive, Vec::new());
output[0] = start;
for row in 1..(num_rows_inclusive) {
output[row].resize(num_cols, false);
for col in 0..num_cols {
output[row][col] = is_trap(row, col, num_cols, &output);
}
}
return output;
}
fn solve_internal(path: &str, rows: usize) -> usize {
let mut file = File::open(path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let start: Vec<bool> = contents
.chars()
.filter(|&c| c == '.' || c == '^')
.map(|c| c == '^')
.collect();
let output = generate_rows(start, rows);
let nums = output.iter().fold(0, |sum, v| {
sum + v.iter().fold(0, |sum, &v0| sum + if !v0 { 1 } else { 0 })
});
return nums;
}
pub fn solve() {
println!("Part 1: {}", solve_internal("2016/day18/input", 40));
println!("Part 2: {}", solve_internal("2016/day18/input", 400000));
}
| true |
1174ba0b92b569c91b5693a88cccfea48065e6cd
|
Rust
|
pisa-engine/trec-text-rs
|
/src/lib.rs
|
UTF-8
| 12,737 | 3.390625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#![doc(html_root_url = "https://docs.rs/trec-text/0.1.0")]
//! Parsing TREC Text format.
//!
//! TREC Text is a text format containing a sequence of records:
//! `<DOC> <DOCNO> 0 </DOCNO> Text body </DOC>`
//!
//! # Examples
//!
//! Typically, document records will be read from files.
//! [`Parser`](struct.Parser.html) can be constructer from any structure that implements
//! [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html),
//! and implements [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html).
//!
//! Because parsing of a record can fail, either due to IO error or corupted records,
//! the iterator returns elements of `Result<DocumentRecord>`.
//!
//! ```
//! # use trec_text::*;
//! # fn main() -> Result<()> {
//! use std::io::Cursor;
//!
//! let input = r#"
//!<DOC> <DOCNO> 0 </DOCNO> zero </DOC>
//!CORRUPTED <DOCNO> 1 </DOCNO> ten </DOC>
//!<DOC> <DOCNO> 2 </DOCNO> ten nine </DOC>
//! "#;
//! let mut parser = Parser::new(Cursor::new(input));
//!
//! let document = parser.next().unwrap()?;
//! assert_eq!(String::from_utf8_lossy(document.docno()), "0");
//! assert_eq!(String::from_utf8_lossy(document.content()), " zero ");
//!
//! assert!(parser.next().unwrap().is_err());
//!
//! let document = parser.next().unwrap()?;
//! assert_eq!(String::from_utf8_lossy(document.docno()), "2");
//! assert_eq!(String::from_utf8_lossy(document.content()), " ten nine ");
//!
//! assert!(parser.next().is_none());
//! # Ok(())
//! # }
//! ```
pub use anyhow::Result;
use anyhow::anyhow;
use std::io::{self, Read};
use std::iter::Peekable;
/// TREC Text record data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocumentRecord {
docno: Vec<u8>,
content: Vec<u8>,
}
impl DocumentRecord {
/// Retrieves `DOCNO` field bytes. Any whitespaces proceeding `<DOCNO>` and preceeding
/// `</DOCNO>` are trimmed.
#[must_use]
pub fn docno(&self) -> &[u8] {
&self.docno
}
/// Retrieves content bytes.
#[must_use]
pub fn content(&self) -> &[u8] {
&self.content
}
}
/// TREC Text format parser.
pub struct Parser<B>
where
B: Iterator<Item = io::Result<u8>>,
{
bytes: Peekable<B>,
in_progress: bool,
}
impl<R: Read> Parser<io::Bytes<R>> {
/// Consumes the reader and returns a new TREC Text parser starting at the beginning.
pub fn new(reader: R) -> Self {
Self {
bytes: reader.bytes().peekable(),
in_progress: false,
}
}
}
impl<B> Parser<B>
where
B: Iterator<Item = io::Result<u8>>,
{
/// Returns the underlying iterator of remaining bytes.
pub fn into_bytes(self) -> impl Iterator<Item = Result<u8>> {
self.bytes.map(|elem| elem.map_err(anyhow::Error::new))
}
fn consume_tag_discarding_prefix(&mut self, tag: &str) -> Result<()> {
let pattern: Vec<_> = tag.bytes().collect();
let mut pos = 0;
for byte in &mut self.bytes {
pos = byte.map(|b| if pattern[pos] == b { pos + 1 } else { 0 })?;
if pos == pattern.len() {
return Ok(());
}
}
Err(anyhow!("Unexpected EOF"))
}
fn skip_whitespaces(&mut self) -> Result<()> {
while let Some(byte) = self.bytes.peek() {
match byte {
Ok(byte) => {
if !byte.is_ascii_whitespace() {
break;
}
}
Err(err) => {
return Err(anyhow!(format!("{}", err)));
}
}
self.bytes.next();
}
Ok(())
}
fn consume_tag_with_prefix(&mut self, tag: &str) -> Result<Vec<u8>> {
let pattern: Vec<_> = tag.bytes().collect();
let mut buf: Vec<u8> = Vec::new();
let mut pos = 0;
for byte in &mut self.bytes {
pos = byte.map(|b| {
buf.push(b);
if pattern[pos] == b {
pos + 1
} else {
0
}
})?;
if pos == pattern.len() {
buf.drain(buf.len() - pattern.len()..);
return Ok(buf);
}
}
Err(anyhow!("Unexpected EOF"))
}
fn consume_tag(&mut self, tag: &str) -> Result<()> {
for byte in tag.bytes() {
if let Some(b) = self.bytes.next() {
if b? != byte {
return Err(anyhow!(format!("Unable to consume tag: {}", tag)));
}
} else {
return Err(anyhow!("Unexpected EOF"));
}
}
Ok(())
}
fn next_document(&mut self) -> Result<DocumentRecord> {
if self.in_progress {
self.consume_tag_discarding_prefix("<DOC>")?;
} else {
self.in_progress = true;
self.skip_whitespaces()?;
self.consume_tag("<DOC>")?;
}
self.skip_whitespaces()?;
self.consume_tag("<DOCNO>")?;
self.skip_whitespaces()?;
let mut docno = self.consume_tag_with_prefix("</DOCNO>")?;
let ws_suffix = docno
.iter()
.copied()
.rev()
.take_while(u8::is_ascii_whitespace)
.count();
docno.drain(docno.len() - ws_suffix..);
let content = self.consume_tag_with_prefix("</DOC>")?;
self.skip_whitespaces()?;
self.in_progress = false;
Ok(DocumentRecord { docno, content })
}
}
impl<B> Iterator for Parser<B>
where
B: Iterator<Item = io::Result<u8>>,
{
type Item = Result<DocumentRecord>;
fn next(&mut self) -> Option<Self::Item> {
if self.bytes.peek().is_none() {
None
} else {
Some(self.next_document())
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::Cursor;
fn assert_rest_eq<B>(parser: Parser<B>, expected: &str) -> Result<()>
where
B: Iterator<Item = io::Result<u8>> + 'static,
{
let rest: Result<Vec<_>> = parser.into_bytes().collect();
assert_eq!(rest?, expected.bytes().collect::<Vec<_>>());
Ok(())
}
#[test]
fn test_consume_tag() -> Result<()> {
let input = "<DOC>";
let mut parser = Parser::new(Cursor::new(input));
assert!(parser.consume_tag("<DOC>").is_ok());
assert_rest_eq(parser, "")
}
#[test]
fn test_consume_tag_fails() -> Result<()> {
let input = "DOC>";
let mut parser = Parser::new(Cursor::new(input));
assert!(parser.consume_tag("<DOC>").is_err());
assert_rest_eq(parser, "OC>")
}
#[test]
fn test_consume_tag_with_remaining_bytes() -> Result<()> {
let mut parser = Parser::new(Cursor::new("<DOC>rest"));
assert!(parser.consume_tag("<DOC>").is_ok());
assert_rest_eq(parser, "rest")
}
#[test]
fn test_consume_tag_discarding_prefix_no_prefix() -> Result<()> {
let mut parser = Parser::new(Cursor::new("<DOC>rest"));
assert!(parser.consume_tag_discarding_prefix("<DOC>").is_ok());
assert_rest_eq(parser, "rest")
}
#[test]
fn test_consume_tag_discarding_prefix_garbage_prefix() -> Result<()> {
let mut parser = Parser::new(Cursor::new("xxx dsfa sdaf///<<<>>><DOC>rest"));
assert!(parser.consume_tag_discarding_prefix("<DOC>").is_ok());
assert_rest_eq(parser, "rest")
}
#[test]
fn test_consume_tag_discarding_prefix_no_matching_tag() -> Result<()> {
let mut parser = Parser::new(Cursor::new("xxx dsfa sdaf///<<<>>>"));
assert!(parser.consume_tag_discarding_prefix("<DOC>").is_err());
Ok(())
}
#[test]
fn test_consume_tag_with_prefix_no_prefix() -> Result<()> {
let mut parser = Parser::new(Cursor::new("</DOC>rest"));
assert!(parser.consume_tag_with_prefix("</DOC>").is_ok());
assert_rest_eq(parser, "rest")
}
#[test]
fn test_consume_tag_with_prefix_content() -> Result<()> {
let mut parser = Parser::new(Cursor::new("xxx dsfa sdaf///<<<>>></DOC>rest"));
assert_eq!(
parser.consume_tag_with_prefix("</DOC>").unwrap(),
"xxx dsfa sdaf///<<<>>>".bytes().collect::<Vec<_>>()
);
assert_rest_eq(parser, "rest")
}
#[test]
fn test_consume_tag_with_prefix_no_matching_tag() -> Result<()> {
let mut parser = Parser::new(Cursor::new("xxx dsfa sdaf///<<<>>>"));
assert!(parser.consume_tag_with_prefix("<DOC>").is_err());
Ok(())
}
#[test]
fn test_next_document() -> Result<()> {
let input = r#"
<DOC> <DOCNO> 0 </DOCNO> zero </DOC>
<DOC> <DOCNO> 1 </DOCNO> ten </DOC>
<DOC> <DOCNO> 2 </DOCNO> ten nine </DOC>
"#;
let mut parser = Parser::new(Cursor::new(input));
let document = parser.next_document()?;
assert_eq!(String::from_utf8_lossy(document.docno()), "0");
assert_eq!(String::from_utf8_lossy(document.content()), " zero ");
let document = parser.next_document()?;
assert_eq!(String::from_utf8_lossy(document.docno()), "1");
assert_eq!(String::from_utf8_lossy(document.content()), " ten ");
let document = parser.next_document()?;
assert_eq!(String::from_utf8_lossy(document.docno()), "2");
assert_eq!(String::from_utf8_lossy(document.content()), " ten nine ");
Ok(())
}
#[test]
fn test_iter_documents() -> Result<()> {
let input = r#"
<DOC> <DOCNO> 0 </DOCNO> zero </DOC>
CORRUPTED <DOCNO> 1 </DOCNO> ten </DOC>
<DOC> <DOCNO> 2 </DOCNO> ten nine </DOC>
"#;
let mut parser = Parser::new(Cursor::new(input));
let document = parser.next().unwrap()?;
assert_eq!(String::from_utf8_lossy(document.docno()), "0");
assert_eq!(String::from_utf8_lossy(document.content()), " zero ");
assert!(parser.next().unwrap().is_err());
assert!(parser.in_progress);
let document = parser.next().unwrap()?;
assert_eq!(String::from_utf8_lossy(document.docno()), "2");
assert_eq!(String::from_utf8_lossy(document.content()), " ten nine ");
assert!(parser.next().is_none());
Ok(())
}
#[test]
fn test_parse_jassjr_example() -> io::Result<()> {
let input = r#"
<DOC> <DOCNO> 0 </DOCNO> zero </DOC>
<DOC> <DOCNO> 1 </DOCNO> ten </DOC>
<DOC> <DOCNO> 2 </DOCNO> ten nine </DOC>
<DOC> <DOCNO> 3 </DOCNO> ten nine eight </DOC>
<DOC>
<DOCNO> 4 </DOCNO>
ten nine eight seven
</DOC>
<DOC> <DOCNO> 5 </DOCNO> ten nine eight seven six </DOC>
<DOC> <DOCNO> 6 </DOCNO> ten nine eight seven six five </DOC>
<DOC> <DOCNO> 7 </DOCNO> ten nine eight seven six five four </DOC>
<DOC> <DOCNO> 8 </DOCNO> ten nine eight seven six five four three </DOC>
<DOC> <DOCNO> 9 </DOCNO> ten nine eight seven six five four three two </DOC>
<DOC> <DOCNO> 10 </DOCNO> ten nine eight seven six five four three two one </DOC>
"#;
let documents: Result<Vec<_>> = Parser::new(Cursor::new(input)).collect();
assert!(documents.is_ok());
let documents: Vec<_> = documents
.unwrap()
.into_iter()
.map(|doc| {
(
String::from_utf8_lossy(doc.docno()).trim().to_string(),
String::from_utf8_lossy(doc.content()).trim().to_string(),
)
})
.collect();
assert_eq!(
documents,
vec![
(String::from("0"), String::from("zero")),
(String::from("1"), String::from("ten")),
(String::from("2"), String::from("ten nine")),
(String::from("3"), String::from("ten nine eight")),
(String::from("4"), String::from("ten nine eight seven")),
(String::from("5"), String::from("ten nine eight seven six")),
(
String::from("6"),
String::from("ten nine eight seven six five")
),
(
String::from("7"),
String::from("ten nine eight seven six five four")
),
(
String::from("8"),
String::from("ten nine eight seven six five four three")
),
(
String::from("9"),
String::from("ten nine eight seven six five four three two")
),
(
String::from("10"),
String::from("ten nine eight seven six five four three two one")
),
]
);
Ok(())
}
}
| true |
a17d0e7c65c96276a36315ebc13c91df38e416bd
|
Rust
|
jahfer/accountant
|
/src/transaction/presidents_choice.rs
|
UTF-8
| 2,413 | 2.71875 | 3 |
[] |
no_license
|
use std::path::Path;
use super::csv_import;
use super::{Transaction, ImportableTransaction, TransactionSource, Format, to_hash};
use ::money::Money;
use std::hash::{Hash, Hasher};
use chrono::{TimeZone, DateTime, UTC};
use regex::Regex;
#[derive(RustcDecodable)]
pub struct Csv {
transaction_date: String,
_posting_date: String,
amount: String,
merchant: String,
_merchant_city: String,
_merchant_state: String,
_merchant_zip: String,
reference: String,
_direction: char,
_sicmcc_code: u16
}
impl Csv {
fn date_as_datetime(&self) -> DateTime<UTC> {
lazy_static! {
static ref RE: Regex = Regex::new(r"^(\d{1,2})/(\d{1,2})/(\d{4})$").unwrap();
}
let captures = RE.captures(&self.transaction_date).unwrap();
let (month, day, year) = (captures.at(1), captures.at(2), captures.at(3));
UTC.ymd(
year.unwrap().parse::<i32>().unwrap(),
month.unwrap().parse::<u32>().unwrap(),
day.unwrap().parse::<u32>().unwrap()
).and_hms(0,0,0)
}
// PC uses + amounts for credits, () amounts for debits
fn formatted_amount(&self) -> String {
let debit_re = Regex::new(r"\((.*)\)").unwrap();
let amount_re = Regex::new(r"([\d\.,]+)").unwrap();
let is_debit = debit_re.is_match(&self.amount);
match amount_re.captures(&self.amount) {
Some(captures) => {
let amount = captures.at(1).unwrap();
if !is_debit {
String::from("-") + amount
} else {
amount.to_string()
}
},
None => panic!("Unable to parse CSV field as money")
}
}
}
impl Hash for Csv {
fn hash<H: Hasher>(&self, state: &mut H) {
self.reference.hash(state)
}
}
impl ImportableTransaction for Csv {
fn import(file_path: &Path) -> Vec<Transaction> {
csv_import::read::<Csv>(file_path, true)
.into_iter()
.map(|tx| Transaction {
source: TransactionSource::PresidentsChoice(Format::CSV),
identifier: to_hash(&tx),
date: tx.date_as_datetime(),
description: None,
note: None,
amount: Money::parse(&tx.formatted_amount()),
merchant: tx.merchant
}).collect()
}
}
| true |
bbd16c6b308ccc0430e960abe5e360a948ba00f1
|
Rust
|
ZoeyR/wearte
|
/testing/tests/benchs.rs
|
UTF-8
| 1,566 | 3.34375 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use wearte::Template;
#[test]
fn big_table() {
let size = 3;
let mut table = Vec::with_capacity(size);
for _ in 0..size {
let mut inner = Vec::with_capacity(size);
for i in 0..size {
inner.push(i);
}
table.push(inner);
}
let table = BigTable { table };
assert_eq!(table.call().unwrap(), "<table><tr><td>0</td><td>1</td><td>2</td></tr><tr><td>0</td><td>1</td><td>2</td></tr><tr><td>0</td><td>1</td><td>2</td></tr></table>");
}
#[derive(Template)]
#[template(path = "big-table.html")]
struct BigTable {
table: Vec<Vec<usize>>,
}
#[test]
fn teams() {
let teams = Teams {
year: 2015,
teams: vec![
Team {
name: "Jiangsu".into(),
score: 43,
},
Team {
name: "Beijing".into(),
score: 27,
},
Team {
name: "Guangzhou".into(),
score: 22,
},
Team {
name: "Shandong".into(),
score: 12,
},
],
};
assert_eq!(teams.call().unwrap(), "<html><head><title>2015</title></head><body><h1>CSL 2015</h1><ul><li class=\"champion\"><b>Jiangsu</b>: 43</li><li class=\"\"><b>Beijing</b>: 27</li><li class=\"\"><b>Guangzhou</b>: 22</li><li class=\"\"><b>Shandong</b>: 12</li></ul></body></html>");
}
#[derive(Template)]
#[template(path = "teams.html")]
struct Teams {
year: u16,
teams: Vec<Team>,
}
struct Team {
name: String,
score: u8,
}
| true |
56fda6a82c3e79e7d839680c73599d4e831c27a0
|
Rust
|
Jaxelr/RustTutorial
|
/Rust Cookbook/12_01_1_read_and_write_files/src/main.rs
|
UTF-8
| 1,491 | 3.125 | 3 |
[] |
no_license
|
use std::fs::File;
use same_file::Handle;
use memmap::Mmap;
use std::io::{Write, BufReader, BufRead, Error, ErrorKind};
use std::path::Path;
fn main() -> Result<(), Box <dyn std::error::Error>> {
read_write_file()?;
same_file()?;
random_memory()?;
Ok(())
}
fn read_write_file() -> Result<(), Error> {
let path = "lines.txt";
let mut output = File::create(path)?;
write!(output, "Rust\n💖\nFun")?;
let input = File::open(path)?;
let buffered = BufReader::new(input);
for line in buffered.lines() {
println!("{}", line?);
}
Ok(())
}
fn same_file() -> Result<(), Error> {
let path_to_read = Path::new("new.txt");
let stdout_handle = Handle::stdout()?;
let handle = Handle::from_path(path_to_read)?;
if stdout_handle == handle {
return Err(Error::new(
ErrorKind::Other,
"You are reading and writing to the same file",
));
} else {
let file = File::open(&path_to_read)?;
let file = BufReader::new(file);
for (num, line) in file.lines().enumerate() {
println!("{} : {}", num, line?.to_uppercase());
}
}
Ok(())
}
fn random_memory() -> Result<(), Error> {
let file = File::open("content.txt")?;
let map = unsafe { Mmap::map(&file)? };
let random_indexes = [0, 1, 2, 19, 22, 10, 11, 29];
let _random_bytes: Vec<u8> = random_indexes.iter()
.map(|&idx| map[idx])
.collect();
Ok(())
}
| true |
16d2253599b3a1fa9c3ec0e7e1a316a4ba3b4b27
|
Rust
|
modelflat/twitchbot
|
/src/state.rs
|
UTF-8
| 1,414 | 2.765625 | 3 |
[] |
no_license
|
use async_std::sync::RwLock;
use std::collections::{BTreeSet, HashMap};
use crate::executor::ShareableExecutableCommand;
use crate::irc;
use crate::permissions::PermissionList;
pub type Commands<T> = HashMap<String, ShareableExecutableCommand<T>>;
pub struct BotState<T: 'static + Send + Sync> {
pub username: String,
pub prefix: String,
pub channels: BTreeSet<String>,
pub commands: Commands<T>,
pub permissions: PermissionList,
pub data: RwLock<T>,
}
impl<T: 'static + Send + Sync> BotState<T> {
pub fn new(
username: String,
prefix: String,
channels: Vec<String>,
commands: Commands<T>,
permissions: PermissionList,
data: T,
) -> BotState<T> {
BotState {
username,
prefix,
channels: channels.into_iter().map(|s| s.to_string()).collect(),
commands,
permissions,
data: RwLock::new(data),
}
}
pub fn try_convert_to_command(&self, message: &irc::Message) -> Option<String> {
if let Some(s) = message.trailing {
if s.starts_with(&self.prefix) {
return Some((&s[self.prefix.len()..]).trim_start().to_string());
}
if s.starts_with(&self.username) {
return Some((&s[self.username.len()..]).trim_start().to_string());
}
}
None
}
}
| true |
07bc5a3bb6501e0fabcb458956b399a89779f61e
|
Rust
|
tertsdiepraam/vrp
|
/vrp-core/src/models/common/load.rs
|
UTF-8
| 8,491 | 3.09375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#[cfg(test)]
#[path = "../../../tests/unit/models/domain/load_test.rs"]
mod load_test;
use crate::models::common::{Dimensions, ValueDimension};
use std::cmp::Ordering;
use std::iter::Sum;
use std::ops::{Add, Mul, Sub};
const CAPACITY_DIMENSION_KEY: &str = "cpc";
const DEMAND_DIMENSION_KEY: &str = "dmd";
const LOAD_DIMENSION_SIZE: usize = 8;
/// Represents a load type used to represent customer's demand or vehicle's load.
pub trait Load: Add + Sub + Ord + Copy + Default + Send + Sync {
/// Returns true if it represents an empty load.
fn is_not_empty(&self) -> bool;
/// Returns max load value.
fn max_load(self, other: Self) -> Self;
/// Returns true if `other` can be loaded into existing capacity.
fn can_fit(&self, other: &Self) -> bool;
/// Returns ratio.
fn ratio(&self, other: &Self) -> f64;
}
/// Represents job demand, both static and dynamic.
pub struct Demand<T: Load + Add<Output = T> + Sub<Output = T> + 'static> {
/// Keeps static and dynamic pickup amount.
pub pickup: (T, T),
/// Keeps static and dynamic delivery amount.
pub delivery: (T, T),
}
/// A trait to get or set vehicle's capacity.
pub trait CapacityDimension<T: Load + Add<Output = T> + Sub<Output = T> + 'static> {
/// Sets capacity.
fn set_capacity(&mut self, demand: T) -> &mut Self;
/// Gets capacity.
fn get_capacity(&self) -> Option<&T>;
}
/// A trait to get or set demand.
pub trait DemandDimension<T: Load + Add<Output = T> + Sub<Output = T> + 'static> {
/// Sets demand.
fn set_demand(&mut self, demand: Demand<T>) -> &mut Self;
/// Gets demand.
fn get_demand(&self) -> Option<&Demand<T>>;
}
impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> Demand<T> {
/// Returns capacity change as difference between pickup and delivery.
pub fn change(&self) -> T {
self.pickup.0 + self.pickup.1 - self.delivery.0 - self.delivery.1
}
}
impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> Default for Demand<T> {
fn default() -> Self {
Self { pickup: (Default::default(), Default::default()), delivery: (Default::default(), Default::default()) }
}
}
impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> Clone for Demand<T> {
fn clone(&self) -> Self {
Self { pickup: self.pickup, delivery: self.delivery }
}
}
impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> CapacityDimension<T> for Dimensions {
fn set_capacity(&mut self, demand: T) -> &mut Self {
self.set_value(CAPACITY_DIMENSION_KEY, demand);
self
}
fn get_capacity(&self) -> Option<&T> {
self.get_value(CAPACITY_DIMENSION_KEY)
}
}
impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> DemandDimension<T> for Dimensions {
fn set_demand(&mut self, demand: Demand<T>) -> &mut Self {
self.set_value(DEMAND_DIMENSION_KEY, demand);
self
}
fn get_demand(&self) -> Option<&Demand<T>> {
self.get_value(DEMAND_DIMENSION_KEY)
}
}
/// Specifies single dimensional load type.
#[derive(Clone, Copy, Debug)]
pub struct SingleDimLoad {
/// An actual load value.
pub value: i32,
}
impl SingleDimLoad {
/// Creates a new instance of `SingleDimLoad`.
pub fn new(value: i32) -> Self {
Self { value }
}
}
impl Default for SingleDimLoad {
fn default() -> Self {
Self { value: 0 }
}
}
impl Load for SingleDimLoad {
fn is_not_empty(&self) -> bool {
self.value != 0
}
fn max_load(self, other: Self) -> Self {
let value = self.value.max(other.value);
Self { value }
}
fn can_fit(&self, other: &Self) -> bool {
self.value >= other.value
}
fn ratio(&self, other: &Self) -> f64 {
self.value as f64 / other.value as f64
}
}
impl Add for SingleDimLoad {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
let value = self.value + rhs.value;
Self { value }
}
}
impl Sub for SingleDimLoad {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
let value = self.value - rhs.value;
Self { value }
}
}
impl Ord for SingleDimLoad {
fn cmp(&self, other: &Self) -> Ordering {
self.value.cmp(&other.value)
}
}
impl PartialOrd for SingleDimLoad {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for SingleDimLoad {}
impl PartialEq for SingleDimLoad {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Mul<f64> for SingleDimLoad {
type Output = Self;
fn mul(self, value: f64) -> Self::Output {
Self::new((self.value as f64 * value).round() as i32)
}
}
/// Specifies multi dimensional load type.
#[derive(Clone, Copy, Debug)]
pub struct MultiDimLoad {
/// Load data.
pub load: [i32; LOAD_DIMENSION_SIZE],
/// Actual used size.
pub size: usize,
}
impl MultiDimLoad {
/// Creates a new instance of `MultiDimLoad`.
pub fn new(data: Vec<i32>) -> Self {
assert!(data.len() <= LOAD_DIMENSION_SIZE);
let mut load = [0; LOAD_DIMENSION_SIZE];
for (idx, value) in data.iter().enumerate() {
load[idx] = *value;
}
Self { load, size: data.len() }
}
fn get(&self, idx: usize) -> i32 {
self.load[idx]
}
/// Converts to vector representation.
pub fn as_vec(&self) -> Vec<i32> {
if self.size == 0 {
vec![0]
} else {
self.load[..self.size].to_vec()
}
}
}
impl Load for MultiDimLoad {
fn is_not_empty(&self) -> bool {
self.size == 0 || self.load.iter().any(|v| *v != 0)
}
fn max_load(self, other: Self) -> Self {
let mut result = self;
result.load.iter_mut().zip(other.load.iter()).for_each(|(a, b)| *a = (*a).max(*b));
result
}
fn can_fit(&self, other: &Self) -> bool {
self.load.iter().zip(other.load.iter()).all(|(a, b)| a >= b)
}
fn ratio(&self, other: &Self) -> f64 {
self.load.iter().zip(other.load.iter()).fold(0., |acc, (a, b)| (*a as f64 / *b as f64).max(acc))
}
}
impl Default for MultiDimLoad {
fn default() -> Self {
Self { load: [0; LOAD_DIMENSION_SIZE], size: 0 }
}
}
impl Add for MultiDimLoad {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
fn sum(acc: MultiDimLoad, rhs: &MultiDimLoad) -> MultiDimLoad {
let mut dimens = acc;
for (idx, value) in rhs.load.iter().enumerate() {
dimens.load[idx] += *value;
}
dimens.size = dimens.size.max(rhs.size);
dimens
}
if self.load.len() >= rhs.load.len() {
sum(self, &rhs)
} else {
sum(rhs, &self)
}
}
}
impl Sub for MultiDimLoad {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
let mut dimens = self;
for (idx, value) in rhs.load.iter().enumerate() {
dimens.load[idx] -= *value;
}
dimens.size = dimens.size.max(rhs.size);
dimens
}
}
impl Ord for MultiDimLoad {
fn cmp(&self, other: &Self) -> Ordering {
let size = self.load.len().max(other.load.len());
(0..size).fold(Ordering::Equal, |acc, idx| match acc {
Ordering::Greater => Ordering::Greater,
Ordering::Equal => self.get(idx).cmp(&other.get(idx)),
Ordering::Less => {
if self.get(idx) > other.get(idx) {
Ordering::Greater
} else {
Ordering::Less
}
}
})
}
}
impl PartialOrd for MultiDimLoad {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for MultiDimLoad {}
impl PartialEq for MultiDimLoad {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Mul<f64> for MultiDimLoad {
type Output = Self;
fn mul(self, value: f64) -> Self::Output {
let mut dimens = self;
dimens.load.iter_mut().for_each(|item| {
*item = (*item as f64 * value).round() as i32;
});
dimens
}
}
impl Sum for MultiDimLoad {
fn sum<I: Iterator<Item = MultiDimLoad>>(iter: I) -> Self {
iter.fold(MultiDimLoad::default(), |acc, item| item + acc)
}
}
| true |
99dbc187a9b4dcacd3a9134ed884b8a22db1d95f
|
Rust
|
dpchamps/rust-exercism
|
/raindrops/src/lib.rs
|
UTF-8
| 459 | 3.125 | 3 |
[] |
no_license
|
pub fn raindrops(n: u32) -> String {
let result = vec![3, 5, 7].iter().fold(String::new(), |str, factor| {
if n % factor != 0 {
return str;
}
let noise = match factor {
3 => "Pling",
5 => "Plang",
7 => "Plong",
_ => unreachable!(),
};
format!("{}{}", str, noise)
});
if &result == "" {
n.to_string()
} else {
result
}
}
| true |
7104fc0ed3eb38c354b90eb680965622f46fc511
|
Rust
|
RedEyedMars/AutoClaw
|
/src/game/entities/combat.rs
|
UTF-8
| 5,528 | 2.890625 | 3 |
[] |
no_license
|
use crate::game::battle::system::movement::MovementPath;
use crate::game::entities::skills::Skill;
use crate::game::entities::traits::TraitId;
use crate::game::entities::{Change, Entity, Idable, State};
use crate::game::{Event, Events, GameParts};
use generational_arena::Index;
#[derive(Debug, Clone, Copy)]
pub enum CombatStance {
FindingTarget,
MovingCloser(Index, MovementPath),
UsingSkill(Skill, Index),
}
impl CombatStance {
pub fn pump<'a>(&self, entity: &Entity, parts: &GameParts, events: &mut Events) {
if let Some(board) = parts.get_board() {
match self {
CombatStance::FindingTarget => {
if let Some(target) = board.get_target(entity, parts) {
events.push(
2,
Event::ChangeEntity(
entity.id(),
Change::State(State::Fighting {
stance: CombatStance::UsingSkill(target.1, target.0.id()),
}),
),
);
} else {
if entity.has_trait(&TraitId::Priest) {
if let Some(target) = board.get_closest_ally(entity.id(), parts) {
events.push(
3,
Event::ChangeEntity(
entity.id(),
Change::State(State::Fighting {
stance: CombatStance::MovingCloser(
target,
board.get_path_to_target(
entity.id(),
target,
parts,
),
),
}),
),
);
}
} else {
if let Some(target) = board.get_closest_enemy(entity.id(), parts) {
events.push(
3,
Event::ChangeEntity(
entity.id(),
Change::State(State::Fighting {
stance: CombatStance::MovingCloser(
target,
board.get_path_to_target(
entity.id(),
target,
parts,
),
),
}),
),
);
}
}
}
}
CombatStance::UsingSkill(skill, target) => {
skill.act(parts, events, entity.id(), *target);
events.push(
2,
Event::ChangeEntity(
entity.id(),
Change::State(State::Fighting {
stance: CombatStance::FindingTarget,
}),
),
);
}
CombatStance::MovingCloser(target, path) => {
if let Some(new_path) = board.move_entity(entity.id(), path, events) {
events.push(
2,
Event::ChangeEntity(
entity.id(),
Change::State(State::Fighting {
stance: CombatStance::MovingCloser(*target, new_path),
}),
),
);
} else {
if let Some(target) = board.get_target(entity, parts) {
events.push(
2,
Event::ChangeEntity(
entity.id(),
Change::State(State::Fighting {
stance: CombatStance::UsingSkill(target.1, target.0.id()),
}),
),
);
} else {
events.push(
2,
Event::ChangeEntity(
entity.id(),
Change::State(State::Fighting {
stance: CombatStance::FindingTarget,
}),
),
);
}
}
}
}
}
}
}
| true |
5d5ec2b359cb4beaa13d08839ba6057d8492bd46
|
Rust
|
mkeeter/advent-of-code
|
/2021/15/src/main.rs
|
UTF-8
| 2,164 | 3.0625 | 3 |
[] |
no_license
|
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::io::BufRead;
#[derive(Ord, PartialOrd, Eq, PartialEq)]
struct Task {
score: Reverse<usize>,
pos: (usize, usize),
}
struct Tile {
weight: usize,
score: Option<usize>,
}
fn search(map: &[Vec<u8>]) -> usize {
let mut map: Vec<Vec<Tile>> = map
.iter()
.map(|row| {
row.iter()
.map(|weight| Tile {
weight: *weight as usize,
score: None,
})
.collect()
})
.collect();
let mut todo = BinaryHeap::new();
todo.push(Task {
score: Reverse(0),
pos: (0, 0),
});
let xmax = map[0].len() as i64 - 1;
let ymax = map.len() as i64 - 1;
while let Some(task) = todo.pop() {
let (x, y) = task.pos;
let tile = &mut map[y][x];
if let Some(s) = tile.score {
assert!(s <= task.score.0);
continue;
}
tile.score = Some(task.score.0);
for (dx, dy) in &[(-1, 0), (1, 0), (0, 1), (0, -1)] {
let (x, y) = (x as i64 + dx, y as i64 + dy);
if x < 0 || y < 0 || x > xmax || y > ymax {
continue;
}
let (x, y) = (x as usize, y as usize);
todo.push(Task {
score: Reverse(task.score.0 + map[y][x].weight),
pos: (x, y),
});
}
}
map[ymax as usize][ymax as usize].score.unwrap()
}
fn main() {
let minimap = std::io::stdin()
.lock()
.lines()
.map(|line| line.unwrap().bytes().map(|c| c - b'0').collect())
.collect::<Vec<Vec<u8>>>();
println!("Part 1: {}", search(&minimap));
let xsize = minimap[0].len();
let ysize = minimap.len();
let mut megamap = vec![vec![0; xsize * 5]; xsize * 5];
for (y, row) in megamap.iter_mut().enumerate() {
for (x, c) in row.iter_mut().enumerate() {
let risk = minimap[y % ysize][x % xsize];
*c = ((risk + (x / xsize + y / ysize) as u8 - 1) % 9) + 1;
}
}
println!("Part 2: {}", search(&megamap));
}
| true |
2767ab826e2d1bf764a4c81631511d7641d4c003
|
Rust
|
Deskbot/Advent-of-Code-2020
|
/src/day/day07.rs
|
UTF-8
| 5,480 | 3.203125 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use std::fs;
use substring::Substring;
#[derive(std::fmt::Debug)]
struct Rule<'a> (i32, &'a str);
pub fn day07() {
let file = fs::read_to_string("input/day07.txt").expect("input not found");
println!("Part 1: {}", part1(&file));
println!("Part 2: {}", part2(&file));
}
fn part1(input: &str) -> i32 {
let bag_to_rules = parse_input(input);
let mut contains_golden = HashMap::new() as HashMap<&str, bool>;
for &bag in bag_to_rules.keys() {
let bag_deep_contains_golden = must_contain(bag, &bag_to_rules, &contains_golden);
contains_golden.insert(bag, bag_deep_contains_golden);
}
return contains_golden
.values()
.filter(|&&b| b)
.count() as i32;
}
fn must_contain(bag: &str, bag_to_rules: &HashMap<&str, Vec<Rule>>, memo: &HashMap<&str, bool>) -> bool {
return bag_to_rules
.get(bag)
.unwrap()
.iter()
.any(|&Rule(_, rule)| {
if rule == "shiny gold" {
return true;
}
if let Some(&this_was_less_annoying_than_unwrap_or_else) = memo.get(bag) {
return this_was_less_annoying_than_unwrap_or_else;
}
return must_contain(rule, bag_to_rules, memo); // this ain't memoised :((((((((((
// need to learn lifetime parameters
});
}
fn part2(input: &str) -> i32 {
let bag_to_rules = parse_input(input);
// let mut memo = HashMap::new() as HashMap<&str, i32>;
return contains("shiny gold", &bag_to_rules, /*&mut memo*/);
}
fn contains(colour: &str, bag_to_rules: &HashMap<&str, Vec<Rule>>, /*memo: &mut HashMap<&str, i32>*/) -> i32 {
// if let Some(&result) = memo.get(bag) {
// return result;
// }
let rules = bag_to_rules
.get(colour)
.unwrap()
.into_iter();
let poop = rules.map(|Rule(rule_count, rule_colour)| {
return rule_count // this many bags directly inside
+ rule_count * contains(rule_colour, bag_to_rules, /*memo*/) // and each of those bags contains bags
});
return poop.fold(0, |sum, next| sum + next);
}
fn parse_input(input: &str) -> HashMap<&str, Vec<Rule>>{
input
.lines()
.map(|line| {
let mut split = line.split(" contain ");
let bag = split.next().unwrap();
let rules = split.next().unwrap();
return (remove_last_word(bag), parse_rules(rules));
})
.collect()
}
fn parse_rules(rules: &str) -> Vec<Rule> {
if rules == "no other bags." {
return Vec::new();
}
// remove the trailing full-stop
let rules = rules.substring(0, rules.len() - 1);
return rules
.split(", ")
.map(|rule| {
let space = rule.find(" ").unwrap();
let number = rule.substring(0, space).parse::<i32>().unwrap();
let non_number_part = rule.substring(space + 1, rule.len());
return Rule(number, remove_last_word(non_number_part));
})
.collect();
}
fn remove_last_word(string: &str) -> &str {
let last_space = string.rfind(" ").unwrap();
return string.substring(0, last_space);
}
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLE_INPUT: &str = "light red bags contain 1 bright white bag, 2 muted yellow bags.\n\
dark orange bags contain 3 bright white bags, 4 muted yellow bags.\n\
bright white bags contain 1 shiny gold bag.\n\
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\n\
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\n\
dark olive bags contain 3 faded blue bags, 4 dotted black bags.\n\
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\n\
faded blue bags contain no other bags.\n\
dotted black bags contain no other bags.";
const EXAMPLE_PART2_INPUT: &str = "shiny gold bags contain 2 dark red bags.\n\
dark red bags contain 2 dark orange bags.\n\
dark orange bags contain 2 dark yellow bags.\n\
dark yellow bags contain 2 dark green bags.\n\
dark green bags contain 2 dark blue bags.\n\
dark blue bags contain 2 dark violet bags.\n\
dark violet bags contain no other bags.";
#[test]
fn part1_example() {
assert_eq!(part1(EXAMPLE_INPUT), 4);
}
#[test]
fn part2_example_1() {
assert_eq!(part2(EXAMPLE_INPUT), 32);
}
#[test]
fn part2_example_2() {
assert_eq!(part2(EXAMPLE_PART2_INPUT), 126);
}
#[test]
fn test() {
assert_eq!(part1("bright white bags contain 1 shiny gold bag.\n"), 1);
}
#[test]
fn test2() {
let bag_to_rules = parse_input(EXAMPLE_INPUT);
assert_eq!(contains("faded blue", &bag_to_rules), 0);
assert_eq!(contains("dotted black", &bag_to_rules), 0);
assert_eq!(contains("dark olive", &bag_to_rules), 7);
assert_eq!(contains("vibrant plum", &bag_to_rules), 11);
assert_eq!(contains("shiny gold", &bag_to_rules), 32);
}
}
| true |
d122241b1a5f2da0c0458e989b8813720783add5
|
Rust
|
nampdn/prisma-engines
|
/query-engine/core/src/executor/interpreting_executor.rs
|
UTF-8
| 2,339 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use super::{pipeline::QueryPipeline, QueryExecutor};
use crate::{Operation, QueryGraphBuilder, QueryInterpreter, QuerySchemaRef, Response, Responses};
use async_trait::async_trait;
use connector::{ConnectionLike, Connector};
/// Central query executor and main entry point into the query core.
pub struct InterpretingExecutor<C> {
connector: C,
primary_connector: &'static str,
force_transactions: bool,
}
// Todo:
// - Partial execution semantics?
impl<C> InterpretingExecutor<C>
where
C: Connector + Send + Sync,
{
pub fn new(connector: C, primary_connector: &'static str, force_transactions: bool) -> Self {
InterpretingExecutor {
connector,
primary_connector,
force_transactions,
}
}
}
#[async_trait]
impl<C> QueryExecutor for InterpretingExecutor<C>
where
C: Connector + Send + Sync,
{
async fn execute(&self, operation: Operation, query_schema: QuerySchemaRef) -> crate::Result<Responses> {
let conn = self.connector.get_connection().await?;
// Parse, validate, and extract query graphs from query document.
let (query, info) = QueryGraphBuilder::new(query_schema).build(operation)?;
// Create pipelines for all separate queries
let mut responses = Responses::with_capacity(1);
let needs_transaction = self.force_transactions || query.needs_transaction();
let result = if needs_transaction {
let tx = conn.start_transaction().await?;
let interpreter = QueryInterpreter::new(ConnectionLike::Transaction(tx.as_ref()));
let result = QueryPipeline::new(query, interpreter, info).execute().await;
if result.is_ok() {
tx.commit().await?;
} else {
tx.rollback().await?;
}
result?
} else {
let interpreter = QueryInterpreter::new(ConnectionLike::Connection(conn.as_ref()));
QueryPipeline::new(query, interpreter, info).execute().await?
};
match result {
Response::Data(key, item) => responses.insert_data(key, item),
Response::Error(error) => responses.insert_error(error),
}
Ok(responses)
}
fn primary_connector(&self) -> &'static str {
self.primary_connector
}
}
| true |
04b6682d49dbf63b9576fb241f686404d1a04d3f
|
Rust
|
manuelleduc/awesome-software-language-engineering
|
/ci/src/lib.rs
|
UTF-8
| 4,816 | 2.953125 | 3 |
[
"CC0-1.0"
] |
permissive
|
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate failure;
#[macro_use]
extern crate lazy_static;
extern crate regex;
use failure::{Error, err_msg};
use regex::Regex;
use std::fmt;
use std::cmp::Ordering;
lazy_static! {
static ref TOOL_REGEX: Regex = Regex::new(r"\*\s\[(?P<name>.*)\]\((?P<link>http[s]?://.*)\)\s(:copyright:\s)?\-\s(?P<desc>.*)").unwrap();
static ref SUBSECTION_HEADLINE_REGEX: Regex = Regex::new(r"[A-Za-z\s]*").unwrap();
}
struct Tool {
name: String,
link: String,
desc: String,
}
impl Tool {
fn new<T: Into<String>>(name: T, link: T, desc: T) -> Self {
Tool {
name: name.into(),
link: link.into(),
desc: desc.into(),
}
}
}
impl PartialEq for Tool {
fn eq(&self, other: &Tool) -> bool {
self.name.to_lowercase() == other.name.to_lowercase()
}
}
impl Eq for Tool {}
impl PartialOrd for Tool {
fn partial_cmp(&self, other: &Tool) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Tool {
fn cmp(&self, other: &Tool) -> Ordering {
self.name.to_lowercase().cmp(&other.name.to_lowercase())
}
}
fn check_tool(tool: &str) -> Result<Tool, Error> {
println!("Checking `{}`", tool);
// NoneError can not implement Fail at this time. That's why we use ok_or
// See https://github.com/rust-lang-nursery/failure/issues/61
let captures = TOOL_REGEX.captures(tool).ok_or(err_msg(format!("Tool does not match regex: {}", tool)))?;
let name = captures["name"].to_string();
let link = captures["link"].to_string();
let desc = captures["desc"].to_string();
if name.len() > 50 {
bail!("Name of tool is suspiciously long: `{}`", name);
}
// A somewhat arbitrarily chosen description length.
// Note that this includes any markdown formatting
// like links. Therefore we are quite generous for now.
if desc.len() > 200 {
bail!("Desription of `{}` is too long: {}", name, desc);
}
Ok(Tool::new(name, link, desc))
}
fn check_section(section: String) -> Result<(), Error> {
// Ignore license section
if section.starts_with("License") {
return Ok(());
}
// Skip section headline
let lines: Vec<_> = section.split('\n').skip(1).collect();
if lines.is_empty() {
bail!("Empty section: {}", section)
};
let mut tools = vec![];
for line in lines {
if line.is_empty() {
continue;
}
// Exception for subsection headlines
if !line.starts_with("*") && line.ends_with(":") &&
SUBSECTION_HEADLINE_REGEX.is_match(line)
{
continue;
}
tools.push(check_tool(line)?);
}
// Tools need to be alphabetically ordered
check_ordering(tools)
}
fn check_ordering(tools: Vec<Tool>) -> Result<(), Error> {
match tools.windows(2).find(|t| t[0] > t[1]) {
Some(tools) => bail!("`{}` does not conform to alphabetical ordering", tools[0].name),
None => Ok(()),
}
}
fn check(text: String) -> Result<(), Error> {
let sections = text.split("\n# ");
// Skip first two sections,
// as they contain the prelude and the table of contents.
for section in sections.skip(2) {
let subsections = section.split("## ");
for subsection in subsections.skip(1) {
check_section(subsection.into())?;
}
}
Ok(())
}
mod tests {
use super::*;
use std::fs::File;
use std::io::Read;
#[test]
fn test_complete_file() {
let mut file = File::open("../README.md").expect("Can't open testfile");
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Can't read testfile contents");
let result = check(contents);
if result.is_err() {
println!("Error: {:?}", result.err());
assert!(false);
} else {
assert!(true);
}
}
#[test]
fn test_correct_ordering() {
assert!(check_ordering(vec![]).is_ok());
assert!(check_ordering(vec![Tool::new("a", "url", "desc")]).is_ok());
assert!(
check_ordering(vec![
Tool::new("0", "", ""),
Tool::new("1", "", ""),
Tool::new("a", "", ""),
Tool::new("Axx", "", ""),
Tool::new("B", "", ""),
Tool::new("b", "", ""),
Tool::new("c", "", ""),
]).is_ok()
);
}
#[test]
fn test_incorrect_ordering() {
assert!(
check_ordering(vec![
Tool::new("b", "", ""),
Tool::new("a", "", ""),
Tool::new("c", "", ""),
]).is_err()
);
}
}
| true |
7e359a5fc15b6bc0d512244d9217e24a8923a440
|
Rust
|
abhijat/invalidator
|
/benches/benchmark.rs
|
UTF-8
| 953 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
#[macro_use]
extern crate criterion;
use std::collections::HashSet;
use criterion::Criterion;
use rand::distributions::Alphanumeric;
use rand::Rng;
use rand::thread_rng;
use bloom_filter::BloomFilter;
fn data_set_of_size(size: usize, word_size: usize) -> HashSet<String> {
let mut data = HashSet::with_capacity(size);
for _ in 0..size {
let s: String = thread_rng().sample_iter(&Alphanumeric).take(word_size).collect();
data.insert(s);
}
data
}
fn false_negative_benchmark(c: &mut Criterion) {
let data = data_set_of_size(1 * 100 * 100, 16);
let mut filter = BloomFilter::new();
data.iter().for_each(|w| filter.put(w));
c.bench_function(
"false-negatives 100 * 100 problem size, 16 char words",
move |b| b.iter(|| {
data.iter().for_each(|w| if !filter.get(w) { panic!(); });
}));
}
criterion_group!(benches, false_negative_benchmark);
criterion_main!(benches);
| true |
91b02a5a09ad5a9979113b7dfd51da71b27a4cdc
|
Rust
|
tobisako/rust-memo
|
/rust_tutorial/s414/src/main.rs
|
UTF-8
| 5,053 | 4.3125 | 4 |
[] |
no_license
|
struct Point {
x: i32,
y: i32,
}
// use std::result::Result;
fn main() {
// パターン
// パターンには一つ落とし穴があります。
// 新しい束縛を導入する他の構文と同様、パターンはシャドーイングをします。例えば:
let x = 'x';
let c = 'c';
match c {
x => println!("x: {} c: {}", x, c), // 元のxがシャドーイングされて、別のxとして動作している。
}
println!("x: {}", x);
// x => は値をパターンにマッチさせ、マッチの腕内で有効な x という名前の束縛を導入します。
// 既に x という束縛が存在していたので、新たに導入した x は、その古い x をシャドーイングします。
// 複式パターン
let x2 = 1;
match x2 {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
// 分配束縛
let origin = Point { x: 0, y: 0 };
match origin {
Point { x, y } => println!("({},{})", x, y),
}
// 値に別の名前を付けたいときは、 : を使うことができます。
let origin2 = Point { x: 0, y: 0 };
match origin2 {
Point { x: x1, y: y1 } => println!("({},{})", x1, y1),
}
// 値の一部にだけ興味がある場合は、値のすべてに名前を付ける必要はありません。
let origin = Point { x: 0, y: 0 };
match origin {
Point { x, .. } => println!("x is {}", x),
}
// 最初のメンバだけでなく、どのメンバに対してもこの種のマッチを行うことができます。
let origin = Point { x: 0, y: 0 };
match origin {
Point { y, .. } => println!("y is {}", y),
}
// 束縛の無視
let some_value: Result<i32, &'static str> = Err("There was an error");
match some_value {
Ok(value) => println!("got a value: {}", value),
Err(_) => println!("an error occurred"),
}
// ここでは、タプルの最初と最後の要素に x と z を束縛します。
fn coordinate() -> (i32, i32, i32) {
// generate and return some sort of triple tuple
// 3要素のタプルを生成して返す
(1, 2, 3)
}
let (x, _, z) = coordinate();
// 同様に .. でパターン内の複数の値を無視することができます。
enum OptionalTuple {
Value(i32, i32, i32),
Missing,
}
let x = OptionalTuple::Value(5, -2, 3);
match x {
OptionalTuple::Value(..) => println!("Got a tuple!"),
OptionalTuple::Missing => println!("No such luck."),
}
// ref と ref mut
// 参照 を取得したいときは ref キーワードを使いましょう。
let x3 = 5;
match x3 {
ref r => println!("Got a reference to {}", r),
}
// ミュータブルな参照が必要な場合は、同様に ref mut を使います。
let mut x = 5;
match x {
ref mut mr => {
*mr += 1;
println!("Got a mutable reference to {}", mr);
},
}
println!("x = {}", x); // 値が書き換わっている。
// 範囲
let x = 1;
match x {
1 ... 5 => println!("one through five"),
_ => println!("anything"),
}
// 範囲は多くの場合、整数か char 型で使われます:
let x = '💅';
match x {
'a' ... 'j' => println!("early letter"),
'k' ... 'z' => println!("late letter"),
_ => println!("something else"),
}
// 束縛
let x = 1;
match x {
e @ 1 ... 5 => println!("got a range element {}", e),
_ => println!("anything"),
}
// 内側の name の値への参照に a を束縛します。
#[derive(Debug)]
struct Person {
name: Option<String>,
}
let name = "Steve".to_string();
let mut x: Option<Person> = Some(Person { name: Some(name) });
match x {
Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
_ => {}
}
// @ を | と組み合わせて使う場合は、それぞれのパターンで同じ名前が束縛されるようにする必要があります:
let x = 5;
match x {
e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
_ => println!("anything"),
}
// ガード
// if を使うことでマッチガードを導入することができます:
enum OptionalInt {
Value(i32),
Missing,
}
let x = OptionalInt::Value(5);
match x {
OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
OptionalInt::Value(..) => println!("Got an int!"),
OptionalInt::Missing => println!("No such luck."),
}
// 複式パターンで if を使うと、 if は | の両側に適用されます:
let x = 4;
let y = false;
match x {
4 | 5 if y => println!("yes"),
_ => println!("no"),
}
// イメージ: (4 | 5) if y => ...
// 混ぜてマッチ
// やりたいことに応じて、それらを混ぜてマッチさせることもできます:
// match x {
// Foo { x: Some(ref name), y: None } => { println!("foo"); },
// }
// パターンはとても強力です。上手に使いましょう。
}
| true |
8926b758fe04817f945d6b6738733e09b81a05ed
|
Rust
|
elipmoc/Ruscall
|
/src/compile/semantic_analysis/variable_table.rs
|
UTF-8
| 1,738 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
#[derive(Clone)]
pub struct VariableTable {
local_var_names: Vec<Vec<String>>,
global_var_names: HashMap<String, ()>,
nest_level: usize,
}
use super::super::ir::ast::VariableAST;
use super::type_inference::type_env::TypeEnv;
use super::mir::ExprMir;
//変数の管理
impl VariableTable {
pub fn new(global_var_names: HashMap<String, ()>) -> VariableTable {
VariableTable { global_var_names, local_var_names: vec![], nest_level: 0 }
}
//de bruijn indexを割り当てたVariableIrの生成
//またはGlobalVariableIrの生成
pub fn get_variable_ir(&self, var: VariableAST, ty_env: &mut TypeEnv) -> Option<ExprMir> {
let a = self.local_var_names[self.nest_level - 1]
.iter().rev().enumerate()
.find(|(_, name)| *name == &var.id)
.map(|(id, _)| id);
match a {
Some(id) => Some(ExprMir::create_variable_mir(id, var.pos, ty_env.fresh_type_id())),
_ => {
if self.global_var_names.contains_key(&var.id) {
Some(ExprMir::create_global_variable_mir(var.id, var.pos, ty_env.fresh_type_id()))
} else {
None
}
}
}
}
pub fn in_nest<T>(&mut self, iter: T)
where T: IntoIterator<Item=String> {
if self.local_var_names.len() <= self.nest_level {
self.local_var_names.push(iter.into_iter().collect());
} else {
self.local_var_names[self.nest_level].clear();
self.local_var_names[self.nest_level].extend(iter);
}
self.nest_level += 1;
}
pub fn out_nest(&mut self) {
self.nest_level -= 1;
}
}
| true |
194d5312513ad7060b2c4dc623f33fbdf1ae4875
|
Rust
|
pwwolff/RussianRust
|
/src/settings_factory.rs
|
UTF-8
| 474 | 2.625 | 3 |
[] |
no_license
|
extern crate glob;
extern crate config;
use std::collections::HashMap;
use config::*;
use glob::glob;
pub fn get_settings() -> HashMap<String, String>{
let mut settings = Config::default();
settings
.merge(glob("config/*")
.unwrap()
.map(|path| File::from(path.unwrap()))
.collect::<Vec<_>>())
.unwrap();
// Print out our settings (as a HashMap)
settings.try_into::<HashMap<String, String>>().unwrap()
}
| true |
dad6bfdbdf27b7f5223322bdee6c1fbc32195b04
|
Rust
|
payload/asciii-rs
|
/src/actions/mod.rs
|
UTF-8
| 11,758 | 2.53125 | 3 |
[] |
no_license
|
//! General actions
#![allow(unused_imports)]
#![allow(dead_code)]
use chrono::*;
use std::{env,fs};
use std::time;
use std::fmt::Write;
use std::path::{Path,PathBuf};
use util;
use super::BillType;
use storage::{Storage,StorageDir,Storable,StorageResult};
use project::Project;
#[cfg(feature="document_export")]
use fill_docs::fill_template;
pub mod error;
use self::error::*;
/// Sets up an instance of `Storage`.
pub fn setup_luigi() -> Result<Storage<Project>> {
trace!("setup_luigi()");
let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value"));
let archive = try!(::CONFIG.get_str("dirs/archive").ok_or("Faulty config: dirs/archive does not contain a value"));
let templates = try!(::CONFIG.get_str("dirs/templates").ok_or("Faulty config: dirs/templates does not contain a value"));
let storage = try!(Storage::new(util::get_storage_path(), working, archive, templates));
Ok(storage)
}
/// Sets up an instance of `Storage`, with git turned on.
pub fn setup_luigi_with_git() -> Result<Storage<Project>> {
trace!("setup_luigi()");
let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value"));
let archive = try!(::CONFIG.get_str("dirs/archive").ok_or("Faulty config: dirs/archive does not contain a value"));
let templates = try!(::CONFIG.get_str("dirs/templates").ok_or("Faulty config: dirs/templates does not contain a value"));
let storage = try!(Storage::new_with_git(util::get_storage_path(), working, archive, templates));
Ok(storage)
}
pub fn simple_with_projects<F>(dir:StorageDir, search_terms:&[&str], f:F)
where F:Fn(&Project)
{
match with_projects(dir, search_terms, |p| {f(p);Ok(())}){
Ok(_) => {},
Err(e) => error!("{}",e)
}
}
/// Helper method that passes projects matching the `search_terms` to the passt closure `f`
pub fn with_projects<F>(dir:StorageDir, search_terms:&[&str], f:F) -> Result<()>
where F:Fn(&Project)->Result<()>
{
trace!("with_projects({:?})", search_terms);
let luigi = try!(setup_luigi());
let projects = try!(luigi.search_projects_any(dir, search_terms));
if projects.is_empty() {
return Err(format!("Nothing found for {:?}", search_terms).into())
}
for project in &projects{
try!(f(project));
}
Ok(())
}
pub fn csv(year:i32) -> Result<String> {
let luigi = try!(setup_luigi());
let mut projects = try!(luigi.open_projects(StorageDir::Year(year)));
projects.sort_by(|pa,pb| pa.index().unwrap_or_else(||"zzzz".to_owned()).cmp( &pb.index().unwrap_or("zzzz".to_owned())));
projects_to_csv(&projects)
}
/// Produces a csv string from a list of `Project`s
/// TODO this still contains german terms
pub fn projects_to_csv(projects:&[Project]) -> Result<String>{
let mut string = String::new();
let splitter = ";";
try!(writeln!(&mut string, "{}", [ "Rnum", "Bezeichnung", "Datum", "Rechnungsdatum", "Betreuer", "Verantwortlich", "Bezahlt am", "Betrag", "Canceled"].join(splitter)));
for project in projects{
try!(writeln!(&mut string, "{}", [
project.get("InvoiceNumber").unwrap_or_else(|| String::from(r#""""#)),
project.get("Name").unwrap_or_else(|| String::from(r#""""#)),
project.get("event/dates/0/begin").unwrap_or_else(|| String::from(r#""""#)),
project.get("invoice/date").unwrap_or_else(|| String::from(r#""""#)),
project.get("Caterers").unwrap_or_else(|| String::from(r#""""#)),
project.get("Responsible").unwrap_or_else(|| String::from(r#""""#)),
project.get("invoice/payed_date").unwrap_or_else(|| String::from(r#""""#)),
project.get("Final").unwrap_or_else(|| String::from(r#""""#)),
project.canceled_string().to_owned()
].join(splitter)));
}
Ok(string)
}
/// Creates the latex files within each projects directory, either for Invoice or Offer.
#[cfg(feature="document_export")]
pub fn project_to_doc(project: &Project, template_name:&str, bill_type:&Option<BillType>, dry_run:bool, force:bool) -> Result<()> {
let template_ext = ::CONFIG.get_str("extensions/output_template").expect("Faulty default config");
let output_ext = ::CONFIG.get_str("extensions/output_file").expect("Faulty default config");
let convert_ext = ::CONFIG.get_str("convert/output_extension").expect("Faulty default config");
let trash_exts = ::CONFIG.get("convert/trash_extensions") .expect("Faulty default config")
.as_vec().expect("Faulty default config")
.into_iter()
.map(|v|v.as_str()).collect::<Vec<_>>();
let mut template_path = PathBuf::new();
template_path.push(util::get_storage_path());
template_path.push(::CONFIG.get_str("dirs/templates").expect("Faulty config: dirs/templates does not contain a value"));
template_path.push(template_name);
template_path.set_extension(template_ext);
debug!("template file={:?} exists={}", template_path, template_path.exists());
if !template_path.exists() {
return Err(format!("Template not found at {}", template_path.display()).into())
}
let convert_tool = ::CONFIG.get_str("convert/tool");
let output_folder = ::CONFIG.get_str("output_path").and_then(util::get_valid_path).expect("Faulty config \"output_path\"");
let ready_for_offer = project.is_ready_for_offer();
let ready_for_invoice = project.is_ready_for_invoice();
let project_file = project.file();
// tiny little helper
let to_local_file = |file:&Path, ext| {
let mut _tmpfile = file.to_owned();
_tmpfile.set_extension(ext);
Path::new(_tmpfile.file_name().unwrap().into()).to_owned()
};
use BillType::*;
let (dyn_bill_type, outfile_tex):
(Option<BillType>, Option<PathBuf>) =
match (bill_type, ready_for_offer, ready_for_invoice)
{
(&Some(Offer), Ok(_), _ ) |
(&None, Ok(_), Err(_)) => (Some(Offer), Some(project.dir().join(project.offer_file_name(output_ext).expect("this should have been cought by ready_for_offer()")))),
(&Some(Invoice), _, Ok(_)) |
(&None, _, Ok(_)) => (Some(Invoice), Some(project.dir().join(project.invoice_file_name(output_ext).expect("this should have been cought by ready_for_invoice()")))),
(&Some(Offer), Err(e), _ ) => {error!("cannot create an offer, check out:{:#?}",e);(None,None)},
(&Some(Invoice), _, Err(e)) => {error!("cannot create an invoice, check out:{:#?}",e);(None,None)},
(_, Err(e), Err(_)) => {error!("Neither an Offer nor an Invoice can be created from this project\n please check out {:#?}", e);(None,None)}
};
//debug!("{:?} -> {:?}",(bill_type, project.is_ready_for_offer(), project.is_ready_for_invoice()), (dyn_bill_type, outfile_tex));
if let (Some(outfile), Some(dyn_bill)) = (outfile_tex, dyn_bill_type) {
let filled = try!(fill_template(project, &dyn_bill, &template_path));
let pdffile = to_local_file(&outfile, convert_ext);
let target = output_folder.join(&pdffile);
// ok, so apparently we can create a tex file, so lets do it
if !force && target.exists() && try!(file_age(&target)) < try!(file_age(&project_file)){
// no wait, nothing has changed, so lets save ourselves the work
info!("nothing to be done, {} is younger than {}\n use -f if you don't agree", target.display(), project_file.display());
} else {
// \o/ we created a tex file
if dry_run{
warn!("Dry run! This does not produce any output:\n * {}\n * {}", outfile.display(), pdffile.display());
} else {
let outfileb = try!(project.write_to_file(&filled,&dyn_bill,output_ext));
debug!("{} vs\n {}", outfile.display(), outfileb.display());
util::pass_to_command(&convert_tool, &[&outfileb]);
}
// clean up expected trash files
for trash_ext in trash_exts.iter().filter_map(|x|*x){
let trash_file = to_local_file(&outfile, trash_ext);
if trash_file.exists() {
try!(fs::remove_file(&trash_file));
debug!("just deleted: {}", trash_file.display())
}
else {
debug!("I expected there to be a {}, but there wasn't any ?", trash_file.display())
}
}
if pdffile.exists(){
debug!("now there is be a {:?} -> {:?}", pdffile, target);
try!(fs::rename(&pdffile, &target));
}
}
}
Ok(())
}
/// Creates the latex files within each projects directory, either for Invoice or Offer.
#[cfg(feature="document_export")]
pub fn projects_to_doc(dir:StorageDir, search_term:&str, template_name:&str, bill_type:&Option<BillType>, dry_run:bool, force:bool) -> Result<()> {
with_projects(dir, &[search_term], |p| project_to_doc(p, template_name, bill_type, dry_run, force) )
}
fn file_age(path:&Path) -> Result<time::Duration> {
let metadata = try!(fs::metadata(path));
let accessed = try!(metadata.accessed());
Ok(try!(accessed.elapsed()))
}
/// Testing only, tries to run complete spec on all projects.
/// TODO make this not panic :D
/// TODO move this to `spec::all_the_things`
pub fn spec() -> Result<()> {
use project::spec::*;
let luigi = try!(setup_luigi());
//let projects = super::execute(||luigi.open_projects(StorageDir::All));
let projects = try!(luigi.open_projects(StorageDir::Working));
for project in projects{
info!("{}", project.dir().display());
let yaml = project.yaml();
client::validate(&yaml).map_err(|errors|for error in errors{
println!(" error: {}", error);
}).unwrap();
client::full_name(&yaml);
client::first_name(&yaml);
client::title(&yaml);
client::email(&yaml);
hours::caterers_string(&yaml);
invoice::number_long_str(&yaml);
invoice::number_str(&yaml);
offer::number(&yaml);
project.age().map(|a|format!("{} days", a)).unwrap();
project.date().map(|d|d.year().to_string()).unwrap();
project.sum_sold().map(|c|util::currency_to_string(&c)).unwrap();
project::manager(&yaml).map(|s|s.to_owned()).unwrap();
project::name(&yaml).map(|s|s.to_owned()).unwrap();
}
Ok(())
}
pub fn delete_project_confirmation(dir: StorageDir, search_terms:&[&str]) -> Result<()> {
let luigi = try!(setup_luigi());
for project in try!(luigi.search_projects_any(dir, search_terms)) {
try!(project.delete_project_dir_if(
|| util::really(&format!("you want me to delete {:?} [y/N]", project.dir())) && util::really("really? [y/N]")
))
}
Ok(())
}
pub fn archive_projects(search_terms:&[&str], manual_year:Option<i32>, force:bool) -> Result<Vec<PathBuf>>{
trace!("archive_projects matching ({:?},{:?},{:?})", search_terms, manual_year,force);
let luigi = try!(setup_luigi_with_git());
Ok(try!( luigi.archive_projects_if(search_terms, manual_year, || force) ))
}
/// Command UNARCHIVE <YEAR> <NAME>
/// TODO: return a list of files that have to be updated in git
pub fn unarchive_projects(year:i32, search_terms:&[&str]) -> Result<Vec<PathBuf>> {
let luigi = try!(setup_luigi_with_git());
Ok(try!( luigi.unarchive_projects(year, search_terms) ))
}
| true |
26801c3acd5afe03a2f81242e2d991bf6fc3b719
|
Rust
|
Strum355/lsif-lang-server
|
/src/reader/interner.rs
|
UTF-8
| 5,093 | 3.734375 | 4 |
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
use std::marker::Sync;
use std::sync::{Arc, Mutex};
/// Interner converts strings into unique identifers. Submitting the same byte value to
/// the interner will result in the same identifier being produced. Each unique input is
/// guaranteed to have a unique output (no two inputs share the same identifier). The
/// identifier space of two distinct interner instances may overlap.
///
/// Assumption: The output of LSIF indexers will not generally mix types of identifiers.
/// If integers are used, they are used for all ids. If strings are used, they are used
/// for all ids.
#[derive(Clone)]
pub struct Interner {
map: Arc<Mutex<HashMap<String, u64>>>,
}
unsafe impl Sync for Interner {}
impl Interner {
pub fn new() -> Interner {
Interner {
map: Arc::new(Mutex::new(HashMap::new())),
}
}
/// Intern returns the unique identifier for the given byte value. The byte value should
/// be a raw LSIF input identifier, which should be a JSON-encoded number or quoted string.
/// This method is safe to call from multiple goroutines.
pub fn intern(&self, raw: &[u8]) -> Result<u64, std::num::ParseIntError> {
if raw.is_empty() {
return Ok(0);
}
if raw[0] != b'"' {
unsafe { return String::from_utf8_unchecked(raw.to_vec()).parse::<u64>() }
}
let s = unsafe { String::from_utf8_unchecked(raw[1..raw.len() - 1].to_vec()) };
match s.parse::<u64>() {
Ok(num) => return Ok(num),
Err(_) => {}
}
let mut map = self.map.lock().unwrap();
if map.contains_key(&s) {
return Ok(*map.get(&s).unwrap());
}
let id: u64 = (map.len() + 1) as u64;
map.insert(s, id);
Ok(id)
}
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::{format_err, Result};
use std::collections::HashSet;
fn compare_from_vec(input: &[Vec<u8>]) -> Result<HashSet<u64>> {
let mut results = HashSet::with_capacity(input.len());
let interner = Interner::new();
for num in input {
let x = interner.intern(num).unwrap();
results.insert(x);
}
for num in input {
let x = interner.intern(num).unwrap();
results
.get(&x)
.ok_or(format_err!("result not found in previous set"))?;
}
Ok(results)
}
fn string_vec_to_bytes(values: Vec<&str>) -> Vec<Vec<u8>> {
values.iter().map(|s| s.as_bytes().to_vec()).collect()
}
#[test]
fn empty_data_doesnt_throw() {
let interner = Interner::new();
assert_eq!(interner.intern(&Vec::new()).unwrap(), 0);
}
#[test]
fn numbers_test() {
let values = string_vec_to_bytes(vec!["1", "2", "3", "4", "100", "500"]);
let results = compare_from_vec(&values).unwrap();
assert_eq!(results.len(), values.len());
}
#[test]
fn numbers_in_strings_test() {
let values = string_vec_to_bytes(vec![
r#""1""#, r#""2""#, r#""3""#, r#""4""#, r#""100""#, r#""500""#,
]);
let results = compare_from_vec(&values).unwrap();
assert_eq!(results.len(), values.len());
}
#[test]
fn normal_strings_test() {
let values = string_vec_to_bytes(vec![
r#""assert_eq!(results.len(), values.len());""#,
r#""sample text""#,
r#""why must this be utf16. Curse you javascript""#,
r#""I'd just like to interject for a moment. What you're referring to as Linux,
is in fact, GNU/Linux, or as I've recently taken to calling it, GNU plus Linux.
Linux is not an operating system unto itself, but rather another free component
of a fully functioning GNU system made useful by the GNU corelibs, shell
utilities and vital system components comprising a full OS as defined by POSIX.""#,
]);
let results = compare_from_vec(&values).unwrap();
assert_eq!(results.len(), values.len());
}
#[test]
fn duplicate_string() {
let values = string_vec_to_bytes(vec![
r#""assert_eq!(results.len(), values.len());""#,
r#""sample text""#,
r#""why must this be utf16. Curse you javascript""#,
r#""why must this be utf16. Curse you javascript""#,
r#""why must this be utf16. Curse you javascript""#,
r#""I'd just like to interject for a moment. What you're referring to as Linux,
is in fact, GNU/Linux, or as I've recently taken to calling it, GNU plus Linux.
Linux is not an operating system unto itself, but rather another free component
of a fully functioning GNU system made useful by the GNU corelibs, shell
utilities and vital system components comprising a full OS as defined by POSIX.""#,
]);
let results = compare_from_vec(&values).unwrap();
assert_eq!(results.len(), values.len() - 2);
}
}
| true |
d04135f099f39bfa1d16d4b9fd189ce9e97ad955
|
Rust
|
JesterOrNot/Rust-Playground
|
/functimer.rs
|
UTF-8
| 299 | 2.859375 | 3 |
[] |
no_license
|
fn main() {
timeFunction(&printer);
}
fn timeFunction(func: &dyn Fn()) {
let time1 = std::time::Instant::now();
func();
let time2 = std::time::Instant::now().duration_since(time1);
println!("{:?}", time2);
}
fn printer() {
for i in 0..100 {
println!("{}", i);
}
}
| true |
fdbfd5baeee2106b2b6fc3e9f75a672229b84644
|
Rust
|
IGBC/Cursive
|
/src/backend/mod.rs
|
UTF-8
| 1,176 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
use event;
use theme;
#[cfg(feature = "termion")]
mod termion;
#[cfg(feature = "bear-lib-terminal")]
mod blt;
#[cfg(any(feature = "ncurses", feature = "pancurses"))]
mod curses;
#[cfg(feature = "bear-lib-terminal")]
pub use self::blt::*;
#[cfg(any(feature = "ncurses", feature = "pancurses"))]
pub use self::curses::*;
#[cfg(feature = "termion")]
pub use self::termion::*;
pub trait Backend {
fn init() -> Box<Self> where Self: Sized;
// TODO: take `self` by value?
// Or implement Drop?
fn finish(&mut self);
fn refresh(&mut self);
fn has_colors(&self) -> bool;
fn screen_size(&self) -> (usize, usize);
/// Main input method
fn poll_event(&mut self) -> event::Event;
/// Main method used for printing
fn print_at(&self, (usize, usize), &str);
fn clear(&self, color: theme::Color);
fn set_refresh_rate(&mut self, fps: u32);
// This sets the Colours and returns the previous colours
// to allow you to set them back when you're done.
fn set_color(&self, colors: theme::ColorPair) -> theme::ColorPair;
fn set_effect(&self, effect: theme::Effect);
fn unset_effect(&self, effect: theme::Effect);
}
| true |
c7fc2c95c9f9f77f9516ad734f36661fd188d607
|
Rust
|
Agile-Llama/Ackermann
|
/ackermann.rs
|
UTF-8
| 1,727 | 3.453125 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use std::cmp::max;
// Naive approach
fn ack(m: isize, n: isize) -> isize {
if m == 0 {
n + 1
} else if n == 0 {
ack(m - 1, 1)
} else {
ack(m - 1, ack(m, n - 1))
}
}
// More optimzed approach using a cache
fn ack_with_cache(m: u64, n: u64) -> u64 {
let mut cache: HashMap<(u64, u64), u64> = HashMap::new();
_ack_with_cache(&mut cache, m, n)
}
fn _ack_with_cache(cache: &mut HashMap<(u64, u64), u64>, m: u64, n: u64) -> u64 {
match (m, n) {
(0, n) => n + 1,
(1, n) => n + 2,
(m, 0) => _ack_with_cache(cache, m - 1, 1),
(m, 1) => {
let n = _ack_with_cache(cache, m - 1, 1);
_ack_with_cache(cache, m - 1, n)
}
(m, n) => {
if cache.contains_key(&(m, n)) {
*cache.get(&(m, n)).unwrap()
} else {
let s = _ack_with_cache(cache, m, n - 2);
let t = _ack_with_cache(cache, m, n - 1);
let res = (s..(t + 1)).fold(0, |acc, x| _ack_comparator(cache, m, acc, x));
cache.insert((m, n), res);
res
}
}
}
}
fn _ack_comparator(cache: &mut HashMap<(u64, u64), u64>, m: u64, acc: u64, x: u64) -> u64 {
let c = _ack_with_cache(cache, m - 1, x);
max(acc, c)
}
fn main() {
use std::time::Instant;
//let before_naive = Instant::now();
//let a = ack(4, 1);
//println!("Naive Elapsed time: {:.2?}", before_naive.elapsed());
//println!("Answer: {}", a);
let before = Instant::now();
let b = ack_with_cache(4, 2);
println!("Optimzed Elapsed time: {:.2?}", before.elapsed());
println!("Answer: {}", b);
}
| true |
8f476860cad08c7542d752279426b2b2e2708f58
|
Rust
|
mfarzamalam/Rust
|
/Rust_challenge/divisible/src/main.rs
|
UTF-8
| 587 | 3.171875 | 3 |
[] |
no_license
|
use read_input::prelude::*;
fn main() {
let number = input::<u32>()
.msg("Enter numerator : ")
.err("Please input positive integer")
.get();
let divisible = input::<u32>()
.msg("Enter denominator : ")
.err("Please input positive integer")
.get();
if number % divisible == 0 {
println!("Number {} is completely divisible by {} ! ",number,divisible);
}
else {
println!("Number {} is not completely divisible by {} ! ",number,divisible);
}
}
| true |
a5320d31e9d5b7833e7236c58c84865f0c51b007
|
Rust
|
zhaoyao/rust-lab
|
/dns-server/src/packet/record_type.rs
|
UTF-8
| 1,199 | 2.890625 | 3 |
[] |
no_license
|
use super::error::*;
#[derive(Debug)]
pub enum RecordType {
A,
NS,
MD,
MF,
CNAME,
SOA,
MB,
MG,
MR,
NULL,
WKS,
PTR,
HINFO,
MINFO,
MX,
TXT,
AXFR,
MAILB,
MAILA,
Any
}
impl RecordType {
pub fn from_u16(i: u16) -> Result<RecordType> {
match i {
1 => Ok(RecordType::A),
2 => Ok(RecordType::NS),
3 => Ok(RecordType::MD),
4 => Ok(RecordType::MF),
5 => Ok(RecordType::CNAME),
6 => Ok(RecordType::SOA),
7 => Ok(RecordType::MB),
8 => Ok(RecordType::MG),
9 => Ok(RecordType::MR),
10 => Ok(RecordType::NULL),
11 => Ok(RecordType::WKS),
12 => Ok(RecordType::PTR),
13 => Ok(RecordType::HINFO),
14 => Ok(RecordType::MINFO),
15 => Ok(RecordType::MX),
16 => Ok(RecordType::TXT),
252 => Ok(RecordType::AXFR),
253 => Ok(RecordType::MAILA),
255 => Ok(RecordType::Any),
_ => Err(ErrorKind::InvalidRecordType(i).into())
}
}
}
| true |
0feafd9f6d9c3cad0a2254ecfa847e5ee4146f30
|
Rust
|
angelini/entity-query
|
/src/csv_parser.rs
|
UTF-8
| 5,337 | 2.6875 | 3 |
[] |
no_license
|
use csv;
use scoped_threadpool::Pool;
use std::collections::HashMap;
use ast::AstNode;
use cli::Join;
use data::{Datum, Db, Ref, Error};
use filter::Filter;
#[derive(Debug)]
pub struct CsvParser<'a> {
filename: &'a str,
entity: &'a str,
time: &'a str,
joins: &'a [Join],
}
impl<'a> CsvParser<'a> {
pub fn new(filename: &'a str, entity: &'a str, time: &'a str, joins: &'a [Join]) -> CsvParser<'a> {
CsvParser {
filename: filename,
entity: entity,
time: time,
joins: joins,
}
}
pub fn parse(self, db: &Db, pool: &mut Pool) -> Result<(Vec<Datum>, Vec<Ref>, usize), Error> {
let mut rdr = try!(csv::Reader::from_file(self.filename));
let headers = rdr.headers().expect("headers required to convert CSV");
let time_index = match headers.iter()
.enumerate()
.find(|&(_, h)| h == self.time) {
Some((idx, _)) => idx,
None => return Err(Error::MissingTimeHeader(self.time.to_owned())),
};
let mut eid = db.offset;
let datums_res = rdr.records()
.map(|row_res| {
let row = try!(row_res);
eid += 1;
let datums = try!(Self::parse_row(row,
&headers,
time_index,
eid,
self.entity));
Ok(datums)
})
.collect::<Result<Vec<Vec<Datum>>, Error>>();
let datums = match datums_res {
Ok(d) => d.into_iter().flat_map(|v| v).collect::<Vec<Datum>>(),
Err(e) => return Err(e),
};
let refs = self.find_refs(&datums, &db, pool);
Ok((datums, refs, eid))
}
fn find_refs(&self, datums: &[Datum], db: &Db, pool: &mut Pool) -> Vec<Ref> {
self.joins
.iter()
.flat_map(|join| {
let (column, query) = (&join.0, &join.1);
let filter = Filter::new(&db, pool);
self.find_refs_for_join(datums, column, query, filter)
})
.collect::<Vec<Ref>>()
}
fn find_refs_for_join(&self, datums: &[Datum], column: &str, query: &str, filter: Filter)
-> Vec<Ref> {
let attribute = format!("{}/{}", self.entity, robotize(&column));
let ast = AstNode::parse(&query).unwrap();
let new_datums = datums.iter()
.filter(|d| d.a == attribute)
.cloned()
.collect::<Vec<Datum>>();
let old_datums = filter.execute(&ast).datums;
let index = index_by_value(old_datums);
new_datums.iter()
.flat_map(|new| Self::generate_refs(new, &index))
.filter(|o| o.is_some())
.map(|o| o.unwrap())
.collect()
}
fn generate_refs(new: &Datum, index: &HashMap<&str, Vec<&Datum>>) -> Vec<Option<Ref>> {
let new_entity = new.a.split('/').next().unwrap();
match index.get(new.v.as_str()) {
Some(old_matches) => {
old_matches.iter()
.map(|old| {
let old_entity = old.a.split('/').next().unwrap();
Some(Ref::new(new.e,
format!("{}/{}", new_entity, old_entity),
old.e,
new.t))
})
.collect()
}
None => vec![None],
}
}
fn parse_row(row: Vec<String>, headers: &[String], time_index: usize, eid: usize, entity: &str)
-> Result<Vec<Datum>, Error> {
let time = match row[time_index].parse::<usize>() {
Ok(t) => t,
Err(_) => return Err(Error::TimeColumnTypeError(row[time_index].to_owned())),
};
let datums = headers.iter()
.enumerate()
.filter(|&(i, _)| i != time_index)
.map(|(_, h)| h)
.zip(row)
.map(|(header, val)| {
Datum::new(eid,
format!("{}/{}", entity, robotize(header)),
val,
time)
})
.collect();
Ok(datums)
}
}
fn robotize(string: &str) -> String {
string.replace(" ", "_")
.to_lowercase()
}
fn index_by_value(datums: Vec<&Datum>) -> HashMap<&str, Vec<&Datum>> {
let mut index = HashMap::new();
for datum in datums {
if let Some(mut foo) = index.insert(datum.v.as_str(), vec![datum]) {
foo.push(datum)
}
}
index
}
| true |
032882d7e5d528a62e79500f5598b67488a2df6f
|
Rust
|
luqmana/cgmath-rs
|
/src/cgmath/vector.rs
|
UTF-8
| 11,652 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright 2013 The CGMath Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt;
use std::num::{Zero, zero, One, one};
use angle::{Rad, atan2, acos};
use approx::ApproxEq;
use array::{Array, build};
use partial_ord::{PartOrdPrim, PartOrdFloat};
/// A trait that specifies a range of numeric operations for vectors. Not all
/// of these make sense from a linear algebra point of view, but are included
/// for pragmatic reasons.
pub trait Vector
<
S: PartOrdPrim,
Slice
>
: Array<S, Slice>
+ Neg<Self>
+ Zero + One
{
#[inline] fn add_s(&self, s: S) -> Self { build(|i| self.i(i).add(&s)) }
#[inline] fn sub_s(&self, s: S) -> Self { build(|i| self.i(i).sub(&s)) }
#[inline] fn mul_s(&self, s: S) -> Self { build(|i| self.i(i).mul(&s)) }
#[inline] fn div_s(&self, s: S) -> Self { build(|i| self.i(i).div(&s)) }
#[inline] fn rem_s(&self, s: S) -> Self { build(|i| self.i(i).rem(&s)) }
#[inline] fn add_v(&self, other: &Self) -> Self { build(|i| self.i(i).add(other.i(i))) }
#[inline] fn sub_v(&self, other: &Self) -> Self { build(|i| self.i(i).sub(other.i(i))) }
#[inline] fn mul_v(&self, other: &Self) -> Self { build(|i| self.i(i).mul(other.i(i))) }
#[inline] fn div_v(&self, other: &Self) -> Self { build(|i| self.i(i).div(other.i(i))) }
#[inline] fn rem_v(&self, other: &Self) -> Self { build(|i| self.i(i).rem(other.i(i))) }
#[inline] fn neg_self(&mut self) { self.each_mut(|_, x| *x = x.neg()) }
#[inline] fn add_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.add(&s)) }
#[inline] fn sub_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.sub(&s)) }
#[inline] fn mul_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.mul(&s)) }
#[inline] fn div_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.div(&s)) }
#[inline] fn rem_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.rem(&s)) }
#[inline] fn add_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.add(other.i(i))) }
#[inline] fn sub_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.sub(other.i(i))) }
#[inline] fn mul_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.mul(other.i(i))) }
#[inline] fn div_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.div(other.i(i))) }
#[inline] fn rem_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.rem(other.i(i))) }
/// The sum of each component of the vector.
#[inline] fn comp_add(&self) -> S { self.fold(|a, b| a.add(b)) }
/// The product of each component of the vector.
#[inline] fn comp_mul(&self) -> S { self.fold(|a, b| a.mul(b)) }
/// Vector dot product.
#[inline] fn dot(&self, other: &Self) -> S { self.mul_v(other).comp_add() }
/// The minimum component of the vector.
#[inline] fn comp_min(&self) -> S { self.fold(|a, b| if *a < *b { *a } else {*b }) }
/// The maximum component of the vector.
#[inline] fn comp_max(&self) -> S { self.fold(|a, b| if *a > *b { *a } else {*b }) }
}
#[inline] pub fn dot<S: PartOrdPrim, Slice, V: Vector<S, Slice>>(a: V, b: V) -> S { a.dot(&b) }
// Utility macro for generating associated functions for the vectors
macro_rules! vec(
($Self:ident <$S:ident> { $($field:ident),+ }, $n:expr) => (
#[deriving(Eq, TotalEq, Clone, Hash)]
pub struct $Self<S> { $(pub $field: S),+ }
impl<$S: Primitive> $Self<$S> {
#[inline]
pub fn new($($field: $S),+) -> $Self<$S> {
$Self { $($field: $field),+ }
}
/// Construct a vector from a single value.
#[inline]
pub fn from_value(value: $S) -> $Self<$S> {
$Self { $($field: value.clone()),+ }
}
/// The additive identity of the vector.
#[inline]
pub fn zero() -> $Self<$S> { $Self::from_value(zero()) }
/// The multiplicative identity of the vector.
#[inline]
pub fn ident() -> $Self<$S> { $Self::from_value(one()) }
}
impl<S: PartOrdPrim> Add<$Self<S>, $Self<S>> for $Self<S> {
#[inline] fn add(&self, other: &$Self<S>) -> $Self<S> { self.add_v(other) }
}
impl<S: PartOrdPrim> Sub<$Self<S>, $Self<S>> for $Self<S> {
#[inline] fn sub(&self, other: &$Self<S>) -> $Self<S> { self.sub_v(other) }
}
impl<S: PartOrdPrim> Zero for $Self<S> {
#[inline] fn zero() -> $Self<S> { $Self::from_value(zero()) }
#[inline] fn is_zero(&self) -> bool { *self == zero() }
}
impl<S: PartOrdPrim> Neg<$Self<S>> for $Self<S> {
#[inline] fn neg(&self) -> $Self<S> { build(|i| self.i(i).neg()) }
}
impl<S: PartOrdPrim> Mul<$Self<S>, $Self<S>> for $Self<S> {
#[inline] fn mul(&self, other: &$Self<S>) -> $Self<S> { self.mul_v(other) }
}
impl<S: PartOrdPrim> One for $Self<S> {
#[inline] fn one() -> $Self<S> { $Self::from_value(one()) }
}
impl<S: PartOrdPrim> Vector<S, [S, ..$n]> for $Self<S> {}
)
)
vec!(Vector2<S> { x, y }, 2)
vec!(Vector3<S> { x, y, z }, 3)
vec!(Vector4<S> { x, y, z, w }, 4)
array!(impl<S> Vector2<S> -> [S, ..2] _2)
array!(impl<S> Vector3<S> -> [S, ..3] _3)
array!(impl<S> Vector4<S> -> [S, ..4] _4)
/// Operations specific to numeric two-dimensional vectors.
impl<S: Primitive> Vector2<S> {
#[inline] pub fn unit_x() -> Vector2<S> { Vector2::new(one(), zero()) }
#[inline] pub fn unit_y() -> Vector2<S> { Vector2::new(zero(), one()) }
/// The perpendicular dot product of the vector and `other`.
#[inline]
pub fn perp_dot(&self, other: &Vector2<S>) -> S {
(self.x * other.y) - (self.y * other.x)
}
#[inline]
pub fn extend(&self, z: S)-> Vector3<S> {
Vector3::new(self.x.clone(), self.y.clone(), z)
}
}
/// Operations specific to numeric three-dimensional vectors.
impl<S: Primitive> Vector3<S> {
#[inline] pub fn unit_x() -> Vector3<S> { Vector3::new(one(), zero(), zero()) }
#[inline] pub fn unit_y() -> Vector3<S> { Vector3::new(zero(), one(), zero()) }
#[inline] pub fn unit_z() -> Vector3<S> { Vector3::new(zero(), zero(), one()) }
/// Returns the cross product of the vector and `other`.
#[inline]
pub fn cross(&self, other: &Vector3<S>) -> Vector3<S> {
Vector3::new((self.y * other.z) - (self.z * other.y),
(self.z * other.x) - (self.x * other.z),
(self.x * other.y) - (self.y * other.x))
}
/// Calculates the cross product of the vector and `other`, then stores the
/// result in `self`.
#[inline]
pub fn cross_self(&mut self, other: &Vector3<S>) {
*self = self.cross(other)
}
#[inline]
pub fn extend(&self, w: S)-> Vector4<S> {
Vector4::new(self.x.clone(), self.y.clone(), self.z.clone(), w)
}
#[inline]
pub fn truncate(&self)-> Vector2<S> {
Vector2::new(self.x.clone(), self.y.clone()) //ignore Z
}
}
/// Operations specific to numeric four-dimensional vectors.
impl<S: Primitive> Vector4<S> {
#[inline] pub fn unit_x() -> Vector4<S> { Vector4::new(one(), zero(), zero(), zero()) }
#[inline] pub fn unit_y() -> Vector4<S> { Vector4::new(zero(), one(), zero(), zero()) }
#[inline] pub fn unit_z() -> Vector4<S> { Vector4::new(zero(), zero(), one(), zero()) }
#[inline] pub fn unit_w() -> Vector4<S> { Vector4::new(zero(), zero(), zero(), one()) }
#[inline]
pub fn truncate(&self)-> Vector3<S> {
Vector3::new(self.x.clone(), self.y.clone(), self.z.clone()) //ignore W
}
}
/// Specifies geometric operations for vectors. This is only implemented for
/// 2-dimensional and 3-dimensional vectors.
pub trait EuclideanVector
<
S: PartOrdFloat<S>,
Slice
>
: Vector<S, Slice>
+ ApproxEq<S>
{
/// Returns `true` if the vector is perpendicular (at right angles to)
/// the other vector.
fn is_perpendicular(&self, other: &Self) -> bool {
self.dot(other).approx_eq(&zero())
}
/// Returns the squared length of the vector. This does not perform an
/// expensive square root operation like in the `length` method and can
/// therefore be more efficient for comparing the lengths of two vectors.
#[inline]
fn length2(&self) -> S {
self.dot(self)
}
/// The norm of the vector.
#[inline]
fn length(&self) -> S {
self.dot(self).sqrt()
}
/// The angle between the vector and `other`.
fn angle(&self, other: &Self) -> Rad<S>;
/// Returns a vector with the same direction, but with a `length` (or
/// `norm`) of `1`.
#[inline]
fn normalize(&self) -> Self {
self.normalize_to(one::<S>())
}
/// Returns a vector with the same direction and a given `length`.
#[inline]
fn normalize_to(&self, length: S) -> Self {
self.mul_s(length / self.length())
}
/// Returns the result of linarly interpolating the length of the vector
/// towards the length of `other` by the specified amount.
#[inline]
fn lerp(&self, other: &Self, amount: S) -> Self {
self.add_v(&other.sub_v(self).mul_s(amount))
}
/// Normalises the vector to a length of `1`.
#[inline]
fn normalize_self(&mut self) {
let rlen = self.length().recip();
self.mul_self_s(rlen);
}
/// Normalizes the vector to `length`.
#[inline]
fn normalize_self_to(&mut self, length: S) {
let n = length / self.length();
self.mul_self_s(n);
}
/// Linearly interpolates the length of the vector towards the length of
/// `other` by the specified amount.
fn lerp_self(&mut self, other: &Self, amount: S) {
let v = other.sub_v(self).mul_s(amount);
self.add_self_v(&v);
}
}
impl<S: PartOrdFloat<S>>
EuclideanVector<S, [S, ..2]> for Vector2<S> {
#[inline]
fn angle(&self, other: &Vector2<S>) -> Rad<S> {
atan2(self.perp_dot(other), self.dot(other))
}
}
impl<S: PartOrdFloat<S>>
EuclideanVector<S, [S, ..3]> for Vector3<S> {
#[inline]
fn angle(&self, other: &Vector3<S>) -> Rad<S> {
atan2(self.cross(other).length(), self.dot(other))
}
}
impl<S: PartOrdFloat<S>>
EuclideanVector<S, [S, ..4]> for Vector4<S> {
#[inline]
fn angle(&self, other: &Vector4<S>) -> Rad<S> {
acos(self.dot(other) / (self.length() * other.length()))
}
}
impl<S: fmt::Show> fmt::Show for Vector2<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "[{}, {}]", self.x, self.y)
}
}
impl<S: fmt::Show> fmt::Show for Vector3<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "[{}, {}, {}]", self.x, self.y, self.z)
}
}
impl<S: fmt::Show> fmt::Show for Vector4<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
}
}
| true |
aa2133a0602ed220752e77bbc052bd17dd1913e8
|
Rust
|
mac-l1/RemarkableFramebuffer
|
/rust-implementation/librustpad/src/ev.rs
|
UTF-8
| 1,309 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
use evdev;
use epoll;
use std;
pub trait EvdevHandler {
fn on_init(&mut self, name: String, device: &mut evdev::Device);
fn on_event(&mut self, device: &String, event: evdev::raw::input_event);
}
pub fn start_evdev<H: EvdevHandler>(path: String, handler: &mut H) {
let mut dev = evdev::Device::open(&path).unwrap();
let devn = unsafe {
let mut ptr = std::mem::transmute(dev.name().as_ptr());
std::ffi::CString::from_raw(ptr).into_string().unwrap()
};
let mut v = vec![
epoll::Event {
events: (epoll::Events::EPOLLET | epoll::Events::EPOLLIN | epoll::Events::EPOLLPRI)
.bits(),
data: 0,
},
];
let epfd = epoll::create(false).unwrap();
epoll::ctl(epfd, epoll::ControlOptions::EPOLL_CTL_ADD, dev.fd(), v[0]).unwrap();
// init callback
handler.on_init(devn.clone(), &mut dev);
loop {
// -1 indefinite wait but it is okay because our EPOLL FD is watching on ALL input devices at once
let res = epoll::wait(epfd, -1, &mut v[0..1]).unwrap();
if res != 1 {
println!("WARN: epoll_wait returned {0}", res);
}
for ev in dev.events_no_sync().unwrap() {
// event callback
handler.on_event(&devn, ev);
}
}
}
| true |
3bde34b786d73b595b467dc049cf9385c9d19032
|
Rust
|
scottschroeder/storyestimate
|
/src/webapp/apikey.rs
|
UTF-8
| 2,398 | 3.25 | 3 |
[] |
no_license
|
use hyper::header::Basic;
use rocket::Outcome;
use rocket::http::Status;
use rocket::request::{self, FromRequest, Request};
use std::str::FromStr;
#[derive(Serialize, Deserialize)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct APIKey {
pub user_id: String,
pub user_key: Option<String>,
}
impl<'a, 'r> FromRequest<'a, 'r> for APIKey {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<APIKey, ()> {
let basic_auth = get_basic_auth(request);
let token_auth = get_token_auth(request);
match (basic_auth, token_auth) {
(None, None) => Outcome::Failure((Status::Unauthorized, ())),
(Some(_), Some(_)) => {
warn!("User passed both a TOK header and HTTP Basic Auth");
Outcome::Failure((Status::Unauthorized, ()))
},
(Some(auth), None) => Outcome::Success(auth),
(None, Some(auth)) => Outcome::Success(auth),
}
}
}
fn get_basic_auth<'a, 'r>(request: &'a Request<'r>) -> Option<APIKey> {
let user_auth: String = match request.headers().get_one("Authorization") {
Some(auth_data) => auth_data.to_string(),
None => return None,
};
let base64_encoded_auth = user_auth.replace("Basic ", "");
let authdata: Basic = match Basic::from_str(&base64_encoded_auth) {
Ok(authdata) => authdata,
Err(_) => return None,
};
Some(APIKey {
user_id: authdata.username,
user_key: authdata.password,
})
}
fn get_token_auth<'a, 'r>(request: &'a Request<'r>) -> Option<APIKey> {
let user_token: String = match request.headers().get_one("X-API-Key") {
Some(auth_data) => auth_data.to_string(),
None => return None,
};
let user_data: Vec<&str> = user_token.split(':').collect();
match user_data.len() {
0 => {
warn!("User passed empty token");
None
},
1 => {
Some(APIKey {
user_id: user_data[0].to_string(),
user_key: None,
})
},
2 => {
Some(APIKey {
user_id: user_data[0].to_string(),
user_key: Some(user_data[1].to_string()),
})
},
x => {
warn!("User passed token with too many fields ({})", x);
None
},
}
}
| true |
61759363a0b5888bd9ee9423e9cd5a7d9ebab4a3
|
Rust
|
lutostag/pincers
|
/src/read.rs
|
UTF-8
| 1,110 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
use anyhow::Result;
use reqwest;
use std::collections::HashSet;
use std::fs::File;
use std::io::{self, Read};
lazy_static! {
static ref REMOTE_SCHEMES: HashSet<&'static str> = hashset! {
"https", "http", "ftps", "ftp"
};
}
pub fn is_remote(url: &str) -> bool {
if let Ok(url) = reqwest::Url::parse(url) {
return REMOTE_SCHEMES.contains(&url.scheme());
}
false
}
pub fn download(url: &str) -> Result<Vec<u8>> {
info!("Getting script: {}", url);
let mut body = Vec::<u8>::new();
if url == "-" {
debug!("Trying to read from stdin");
io::stdin().read_to_end(&mut body)?;
} else if is_remote(&url) {
debug!("Trying to read from remote {}", &url);
reqwest::get(url)?
.error_for_status()?
.read_to_end(&mut body)?;
} else {
debug!("Trying to read from local {}", &url);
File::open(url)?.read_to_end(&mut body)?;
};
match std::str::from_utf8(&body) {
Ok(val) => debug!("Read contents\n{}", val),
Err(_) => debug!("Read content is binary"),
}
Ok(body)
}
| true |
d5ad882aa012e47f2a4a629d9c9b00c41c9215b8
|
Rust
|
sdenel/tiny-static-web-server
|
/src/path_to_key.rs
|
UTF-8
| 1,707 | 3.40625 | 3 |
[] |
no_license
|
use std::collections::HashSet;
use std::sync::Mutex;
// TODO: this function should return the nearest existing index.html, not root
// TODO: Should the webapp behavior be activated with a flag? Currently, 404 requests are redirected to /index.html with no warning even for non webapps.
pub fn path_to_key(path: &str, known_keys: &Mutex<HashSet<String>>) -> String {
let key = path.to_string();
if key.ends_with("/") {
let key_with_index = key.to_owned() + "index.html";
if known_keys.lock().unwrap().contains(&key_with_index) {
return key_with_index;
}
}
if !key.contains(".") {
// We suppose that is the request is not for a file, and we can't find the associated /index.html, then the path is aimed for a webapp in index.html
return "/index.html".to_string();
}
return key;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn path_to_key1() {
assert_eq!(
"/hello.html",
path_to_key("/hello.html", &Mutex::new(HashSet::new()))
);
}
#[test]
fn path_to_key2() {
assert_eq!(
"/index.html",
path_to_key("/", &Mutex::new(HashSet::new()))
);
}
#[test]
fn path_to_key3() {
assert_eq!(
"/index.html",
path_to_key("/stuart/", &Mutex::new(HashSet::new()))
);
}
#[test]
fn path_to_key4() {
assert_eq!(
"/stuart/index.html",
path_to_key(
"/stuart/",
&Mutex::new(
vec!("/stuart/index.html".to_string())
.into_iter().collect()),
)
);
}
}
| true |
9bd150b9f60cc944de9853f6f305b8a9e3e2f106
|
Rust
|
iamparnab/rusty-tree
|
/src/main.rs
|
UTF-8
| 1,261 | 3.375 | 3 |
[] |
no_license
|
fn main() {
for i in 1..4 {
draw_tree_segment(i);
}
draw_stem();
draw_base();
}
const HEIGHT: i32 = 12;
const WIDTH: i32 = 1 + (HEIGHT - 1) * 2; // AP
const STEM_WIDTH: i32 = HEIGHT / 3;
const STEM_HEIGHT: i32 = HEIGHT / 3;
const BASE_WIDTH: i32 = WIDTH * 2;
fn draw_tree_segment(level: i32) {
let mut stars = 1;
for i in 1..(HEIGHT + 1) {
// Chop off the head if level is not 1
if !(level > 1 && i < HEIGHT * 10 / 15) {
add_padding();
// i - 1, because, we need zero space at last row
for _ in 1..((WIDTH / 2) - (i - 1) + 1) {
print!(" ");
}
for _ in 1..(stars + 1) {
print!("^");
}
println!();
}
stars += 2;
}
}
fn draw_stem() {
for _ in 1..(STEM_HEIGHT + 1) {
add_padding();
for _ in 1..(WIDTH / 2 - STEM_WIDTH / 2 + 1) {
print!(" ")
}
for _ in 1..(STEM_WIDTH + 1) {
print!("|")
}
println!()
}
}
fn draw_base() {
for _ in 1..(BASE_WIDTH + 1) {
print!("*")
}
println!()
}
fn add_padding() {
for _ in 1..BASE_WIDTH / 2 - WIDTH / 2 + 1 {
print!(" ")
}
}
| true |
1a7d103e7b9a678d8265489b1b92fb76d6a6420f
|
Rust
|
madskjeldgaard/nannou
|
/nannou_laser/src/ffi.rs
|
UTF-8
| 26,593 | 2.953125 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Expose a C compatible interface.
use std::collections::HashMap;
use std::ffi::CString;
use std::fmt;
use std::io;
use std::os::raw;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// Allows for detecting and enumerating laser DACs on a network and establishing new streams of
/// communication with them.
#[repr(C)]
pub struct Api {
inner: *mut ApiInner,
}
/// A handle to a non-blocking DAC detection thread.
#[repr(C)]
pub struct DetectDacsAsync {
inner: *mut DetectDacsAsyncInner,
}
/// Represents a DAC that has been detected on the network along with any information collected
/// about the DAC in the detection process.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct DetectedDac {
pub kind: DetectedDacKind,
}
/// A union for distinguishing between the kind of LASER DAC that was detected. Currently, only
/// EtherDream is supported, however this will gain more variants as more protocols are added (e.g.
/// AVB).
#[repr(C)]
#[derive(Clone, Copy)]
pub union DetectedDacKind {
pub ether_dream: DacEtherDream,
}
/// An Ether Dream DAC that was detected on the network.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct DacEtherDream {
pub broadcast: ether_dream::protocol::DacBroadcast,
pub source_addr: SocketAddr,
}
/// A set of stream configuration parameters applied to the initialisation of both `Raw` and
/// `Frame` streams.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct StreamConfig {
/// A valid pointer to a `DetectedDac` that should be targeted.
pub detected_dac: *const DetectedDac,
/// The rate at which the DAC should process points per second.
///
/// This value should be no greater than the detected DAC's `max_point_hz`.
pub point_hz: raw::c_uint,
/// The maximum latency specified as a number of points.
///
/// Each time the laser indicates its "fullness", the raw stream will request enough points
/// from the render function to fill the DAC buffer up to `latency_points`.
///
/// This value should be no greaterthan the DAC's `buffer_capacity`.
pub latency_points: raw::c_uint,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub enum IpAddrVersion {
V4,
V6,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct IpAddr {
pub version: IpAddrVersion,
/// 4 bytes used for `V4`, 16 bytes used for `V6`.
pub bytes: [raw::c_uchar; 16],
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct SocketAddr {
pub ip: IpAddr,
pub port: raw::c_ushort,
}
/// A handle to a stream that requests frames of LASER data from the user.
///
/// Each "frame" has an optimisation pass applied that optimises the path for inertia, minimal
/// blanking, point de-duplication and segment order.
#[repr(C)]
pub struct FrameStream {
inner: *mut FrameStreamInner,
}
/// A handle to a raw LASER stream that requests the exact number of points that the DAC is
/// awaiting in each call to the user's callback.
#[repr(C)]
pub struct RawStream {
inner: *mut RawStreamInner,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub enum Result {
Success = 0,
DetectDacFailed,
BuildStreamFailed,
DetectDacsAsyncFailed,
}
/// A set of stream configuration parameters unique to `Frame` streams.
#[repr(C)]
#[derive(Clone, Debug)]
pub struct FrameStreamConfig {
pub stream_conf: StreamConfig,
/// The rate at which the stream will attempt to present images via the DAC. This value is used
/// in combination with the DAC's `point_hz` in order to determine how many points should be
/// used to draw each frame. E.g.
///
/// ```ignore
/// let points_per_frame = point_hz / frame_hz;
/// ```
///
/// This is simply used as a minimum value. E.g. if some very simple geometry is submitted, this
/// allows the DAC to spend more time creating the path for the image. However, if complex geometry
/// is submitted that would require more than the ideal `points_per_frame`, the DAC may not be able
/// to achieve the desired `frame_hz` when drawing the path while also taking the
/// `distance_per_point` and `radians_per_point` into consideration.
pub frame_hz: u32,
/// Configuration options for eulerian circuit interpolation.
pub interpolation_conf: crate::stream::frame::opt::InterpolationConfig,
}
#[repr(C)]
pub struct Frame {
inner: *mut FrameInner,
}
#[repr(C)]
pub struct Buffer {
inner: *mut BufferInner,
}
struct FrameInner(*mut crate::stream::frame::Frame);
struct BufferInner(*mut crate::stream::raw::Buffer);
struct ApiInner {
inner: crate::Api,
last_error: Option<CString>,
}
struct DetectDacsAsyncInner {
_inner: crate::DetectDacsAsync,
dacs: Arc<Mutex<HashMap<crate::DacId, (Instant, crate::DetectedDac)>>>,
last_error: Arc<Mutex<Option<CString>>>,
}
struct FrameStreamModel(*mut raw::c_void, FrameRenderCallback, RawRenderCallback);
struct RawStreamModel(*mut raw::c_void, RawRenderCallback);
unsafe impl Send for FrameStreamModel {}
unsafe impl Send for RawStreamModel {}
struct FrameStreamInner(crate::FrameStream<FrameStreamModel>);
struct RawStreamInner(crate::RawStream<RawStreamModel>);
/// Cast to `extern fn(*mut raw::c_void, *mut Frame)` internally.
//pub type FrameRenderCallback = *const raw::c_void;
pub type FrameRenderCallback = extern "C" fn(*mut raw::c_void, *mut Frame);
/// Cast to `extern fn(*mut raw::c_void, *mut Buffer)` internally.
//pub type RawRenderCallback = *const raw::c_void;
pub type RawRenderCallback = extern "C" fn(*mut raw::c_void, *mut Buffer);
/// Given some uninitialized pointer to an `Api` struct, fill it with a new Api instance.
#[no_mangle]
pub unsafe extern "C" fn api_new(api: *mut Api) {
let inner = crate::Api::new();
let last_error = None;
let boxed_inner = Box::new(ApiInner { inner, last_error });
(*api).inner = Box::into_raw(boxed_inner);
}
/// Given some uninitialised pointer to a `DetectDacsAsync` struct, fill it with a new instance.
///
/// If the given `timeout_secs` is `0`, DAC detection will never timeout and detected DACs that no
/// longer broadcast will remain accessible in the device map.
#[no_mangle]
pub unsafe extern "C" fn detect_dacs_async(
api: *mut Api,
timeout_secs: raw::c_float,
detect_dacs: *mut DetectDacsAsync,
) -> Result {
let api: &mut ApiInner = &mut (*(*api).inner);
let duration = if timeout_secs == 0.0 {
None
} else {
let secs = timeout_secs as u64;
let nanos = ((timeout_secs - secs as raw::c_float) * 1_000_000_000.0) as u32;
Some(std::time::Duration::new(secs, nanos))
};
let boxed_detect_dacs_inner = match detect_dacs_async_inner(&api.inner, duration) {
Ok(detector) => Box::new(detector),
Err(err) => {
api.last_error = Some(err_to_cstring(&err));
return Result::DetectDacsAsyncFailed;
}
};
(*detect_dacs).inner = Box::into_raw(boxed_detect_dacs_inner);
Result::Success
}
/// Retrieve a list of the currently available DACs.
///
/// Calling this function should never block, and simply provide the list of DACs that have
/// broadcast their availability within the last specified DAC timeout duration.
#[no_mangle]
pub unsafe extern "C" fn available_dacs(
detect_dacs_async: *mut DetectDacsAsync,
first_dac: *mut *mut DetectedDac,
len: *mut raw::c_uint,
) {
let detect_dacs_async: &mut DetectDacsAsyncInner = &mut (*(*detect_dacs_async).inner);
*first_dac = std::ptr::null_mut();
*len = 0;
if let Ok(dacs) = detect_dacs_async.dacs.lock() {
if !dacs.is_empty() {
let mut dacs: Box<[_]> = dacs
.values()
.map(|&(_, ref dac)| detected_dac_to_ffi(dac.clone()))
.collect();
*len = dacs.len() as _;
*first_dac = dacs.as_mut_ptr();
std::mem::forget(dacs);
}
}
}
/// Block the current thread until a new DAC is detected and return it.
#[no_mangle]
pub unsafe extern "C" fn detect_dac(api: *mut Api, detected_dac: *mut DetectedDac) -> Result {
let api: &mut ApiInner = &mut (*(*api).inner);
let mut iter = match api.inner.detect_dacs() {
Err(err) => {
api.last_error = Some(err_to_cstring(&err));
return Result::DetectDacFailed;
}
Ok(iter) => iter,
};
match iter.next() {
None => return Result::DetectDacFailed,
Some(res) => match res {
Ok(dac) => {
*detected_dac = detected_dac_to_ffi(dac);
return Result::Success;
}
Err(err) => {
api.last_error = Some(err_to_cstring(&err));
return Result::DetectDacFailed;
}
},
}
}
/// Initialise the given frame stream configuration with default values.
#[no_mangle]
pub unsafe extern "C" fn frame_stream_config_default(conf: *mut FrameStreamConfig) {
let stream_conf = default_stream_config();
let frame_hz = crate::stream::DEFAULT_FRAME_HZ;
let interpolation_conf = crate::stream::frame::opt::InterpolationConfig::start().build();
*conf = FrameStreamConfig {
stream_conf,
frame_hz,
interpolation_conf,
};
}
/// Initialise the given raw stream configuration with default values.
#[no_mangle]
pub unsafe extern "C" fn stream_config_default(conf: *mut StreamConfig) {
*conf = default_stream_config();
}
/// Spawn a new frame rendering stream.
///
/// The `frame_render_callback` is called each time the stream is ready for a new `Frame` of laser
/// points. Each "frame" has an optimisation pass applied that optimises the path for inertia,
/// minimal blanking, point de-duplication and segment order.
///
/// The `process_raw_callback` allows for optionally processing the raw points before submission to
/// the DAC. This might be useful for:
///
/// - applying post-processing effects onto the optimised, interpolated points.
/// - monitoring the raw points resulting from the optimisation and interpolation processes.
/// - tuning brightness of colours based on safety zones.
///
/// The given function will get called right before submission of the optimised, interpolated
/// buffer.
#[no_mangle]
pub unsafe extern "C" fn new_frame_stream(
api: *mut Api,
stream: *mut FrameStream,
config: *const FrameStreamConfig,
callback_data: *mut raw::c_void,
frame_render_callback: FrameRenderCallback,
process_raw_callback: RawRenderCallback,
) -> Result {
let api: &mut ApiInner = &mut (*(*api).inner);
let model = FrameStreamModel(callback_data, frame_render_callback, process_raw_callback);
fn render_fn(model: &mut FrameStreamModel, frame: &mut crate::stream::frame::Frame) {
let FrameStreamModel(callback_data_ptr, frame_render_callback, _) = *model;
let mut inner = FrameInner(frame);
let mut frame = Frame { inner: &mut inner };
frame_render_callback(callback_data_ptr, &mut frame);
}
let mut builder = api
.inner
.new_frame_stream(model, render_fn)
.point_hz((*config).stream_conf.point_hz as _)
.latency_points((*config).stream_conf.latency_points as _)
.frame_hz((*config).frame_hz as _);
fn process_raw_fn(model: &mut FrameStreamModel, buffer: &mut crate::stream::raw::Buffer) {
let FrameStreamModel(callback_data_ptr, _, process_raw_callback) = *model;
let mut inner = BufferInner(buffer);
let mut buffer = Buffer { inner: &mut inner };
process_raw_callback(callback_data_ptr, &mut buffer);
}
builder = builder.process_raw(process_raw_fn);
if (*config).stream_conf.detected_dac != std::ptr::null() {
let ffi_dac = (*(*config).stream_conf.detected_dac).clone();
let detected_dac = detected_dac_from_ffi(ffi_dac);
builder = builder.detected_dac(detected_dac);
}
let inner = match builder.build() {
Err(err) => {
api.last_error = Some(err_to_cstring(&err));
return Result::BuildStreamFailed;
}
Ok(stream) => Box::new(FrameStreamInner(stream)),
};
(*stream).inner = Box::into_raw(inner);
Result::Success
}
/// Spawn a new frame rendering stream.
///
/// A raw LASER stream requests the exact number of points that the DAC is awaiting in each call to
/// the user's `process_raw_callback`. Keep in mind that no optimisation passes are applied. When
/// using a raw stream, this is the responsibility of the user.
#[no_mangle]
pub unsafe extern "C" fn new_raw_stream(
api: *mut Api,
stream: *mut RawStream,
config: *const StreamConfig,
callback_data: *mut raw::c_void,
process_raw_callback: RawRenderCallback,
) -> Result {
let api: &mut ApiInner = &mut (*(*api).inner);
let model = RawStreamModel(callback_data, process_raw_callback);
fn render_fn(model: &mut RawStreamModel, buffer: &mut crate::stream::raw::Buffer) {
let RawStreamModel(callback_data_ptr, raw_render_callback) = *model;
let mut inner = BufferInner(buffer);
let mut buffer = Buffer { inner: &mut inner };
raw_render_callback(callback_data_ptr, &mut buffer);
}
let mut builder = api
.inner
.new_raw_stream(model, render_fn)
.point_hz((*config).point_hz as _)
.latency_points((*config).latency_points as _);
if (*config).detected_dac != std::ptr::null() {
let ffi_dac = (*(*config).detected_dac).clone();
let detected_dac = detected_dac_from_ffi(ffi_dac);
builder = builder.detected_dac(detected_dac);
}
let inner = match builder.build() {
Err(err) => {
api.last_error = Some(err_to_cstring(&err));
return Result::BuildStreamFailed;
}
Ok(stream) => Box::new(RawStreamInner(stream)),
};
(*stream).inner = Box::into_raw(inner);
Result::Success
}
/// Update the rate at which the DAC should process points per second.
///
/// This value should be no greater than the detected DAC's `max_point_hz`.
///
/// By default this value is `stream::DEFAULT_POINT_HZ`.
///
/// Returns `true` on success or `false` if the communication channel was closed.
pub unsafe extern "C" fn frame_stream_set_point_hz(
stream: *const FrameStream,
point_hz: u32,
) -> bool {
let stream: &FrameStream = &*stream;
(*stream.inner).0.set_point_hz(point_hz).is_ok()
}
/// The maximum latency specified as a number of points.
///
/// Each time the laser indicates its "fullness", the raw stream will request enough points
/// from the render function to fill the DAC buffer up to `latency_points`.
///
/// This value should be no greaterthan the DAC's `buffer_capacity`.
///
/// Returns `true` on success or `false` if the communication channel was closed.
pub unsafe extern "C" fn frame_stream_set_latency_points(
stream: *const FrameStream,
points: u32,
) -> bool {
let stream: &FrameStream = &*stream;
(*stream.inner).0.set_latency_points(points).is_ok()
}
/// Update the `distance_per_point` field of the interpolation configuration used within the
/// optimisation pass for frames. This represents the minimum distance the interpolator can travel
/// along an edge before a new point is required.
///
/// The value will be updated on the laser thread prior to requesting the next frame.
///
/// Returns `true` on success or `false` if the communication channel was closed.
pub unsafe extern "C" fn frame_stream_set_distance_per_point(
stream: *const FrameStream,
distance_per_point: f32,
) -> bool {
let stream: &FrameStream = &*stream;
(*stream.inner)
.0
.set_distance_per_point(distance_per_point)
.is_ok()
}
/// Update the `blank_delay_points` field of the interpolation configuration. This represents the
/// number of points to insert at the end of a blank to account for light modulator delay.
///
/// The value will be updated on the laser thread prior to requesting the next frame.
///
/// Returns `true` on success or `false` if the communication channel was closed.
pub unsafe extern "C" fn frame_stream_set_blank_delay_points(
stream: *const FrameStream,
points: u32,
) -> bool {
let stream: &FrameStream = &*stream;
(*stream.inner).0.set_blank_delay_points(points).is_ok()
}
/// Update the `radians_per_point` field of the interpolation configuration. This represents the
/// amount of delay to add based on the angle of the corner in radians.
///
/// The value will be updated on the laser thread prior to requesting the next frame.
///
/// Returns `true` on success or `false` if the communication channel was closed.
pub unsafe extern "C" fn frame_stream_set_radians_per_point(
stream: *const FrameStream,
radians_per_point: f32,
) -> bool {
let stream: &FrameStream = &*stream;
(*stream.inner)
.0
.set_radians_per_point(radians_per_point)
.is_ok()
}
/// Update the rate at which the stream will attempt to present images via the DAC. This value is
/// used in combination with the DAC's `point_hz` in order to determine how many points should be
/// used to draw each frame. E.g.
///
/// ```ignore
/// let points_per_frame = point_hz / frame_hz;
/// ```
///
/// This is simply used as a minimum value. E.g. if some very simple geometry is submitted, this
/// allows the DAC to spend more time creating the path for the image. However, if complex geometry
/// is submitted that would require more than the ideal `points_per_frame`, the DAC may not be able
/// to achieve the desired `frame_hz` when drawing the path while also taking the
/// `distance_per_point` and `radians_per_point` into consideration.
///
/// The value will be updated on the laser thread prior to requesting the next frame.
///
/// Returns `true` on success or `false` if the communication channel was closed.
pub unsafe extern "C" fn frame_stream_set_frame_hz(
stream: *const FrameStream,
frame_hz: u32,
) -> bool {
let stream: &FrameStream = &*stream;
(*stream.inner).0.set_frame_hz(frame_hz).is_ok()
}
/// Update the rate at which the DAC should process points per second.
///
/// This value should be no greater than the detected DAC's `max_point_hz`.
///
/// By default this value is `stream::DEFAULT_POINT_HZ`.
///
/// Returns `true` on success or `false` if the communication channel was closed.
pub unsafe extern "C" fn raw_stream_set_point_hz(stream: *const RawStream, point_hz: u32) -> bool {
let stream: &RawStream = &*stream;
(*stream.inner).0.set_point_hz(point_hz).is_ok()
}
/// The maximum latency specified as a number of points.
///
/// Each time the laser indicates its "fullness", the raw stream will request enough points
/// from the render function to fill the DAC buffer up to `latency_points`.
///
/// This value should be no greaterthan the DAC's `buffer_capacity`.
///
/// Returns `true` on success or `false` if the communication channel was closed.
pub unsafe extern "C" fn raw_stream_set_latency_points(
stream: *const RawStream,
points: u32,
) -> bool {
let stream: &RawStream = &*stream;
(*stream.inner).0.set_latency_points(points).is_ok()
}
/// Add a sequence of consecutive points separated by blank space.
///
/// If some points already exist in the frame, this method will create a blank segment between the
/// previous point and the first point before appending this sequence.
#[no_mangle]
pub unsafe extern "C" fn frame_add_points(
frame: *mut Frame,
points: *const crate::Point,
len: usize,
) {
let frame = &mut *frame;
let points = std::slice::from_raw_parts(points, len);
(*(*frame.inner).0).add_points(points.iter().cloned());
}
/// Add a sequence of consecutive lines.
///
/// If some points already exist in the frame, this method will create a blank segment between the
/// previous point and the first point before appending this sequence.
#[no_mangle]
pub unsafe extern "C" fn frame_add_lines(
frame: *mut Frame,
points: *const crate::Point,
len: usize,
) {
let frame = &mut *frame;
let points = std::slice::from_raw_parts(points, len);
(*(*frame.inner).0).add_lines(points.iter().cloned());
}
/// Retrieve the current `frame_hz` at the time of rendering this `Frame`.
#[no_mangle]
pub unsafe extern "C" fn frame_hz(frame: *const Frame) -> u32 {
(*(*(*frame).inner).0).frame_hz()
}
/// Retrieve the current `point_hz` at the time of rendering this `Frame`.
#[no_mangle]
pub unsafe extern "C" fn frame_point_hz(frame: *const Frame) -> u32 {
(*(*(*frame).inner).0).point_hz()
}
/// Retrieve the current `latency_points` at the time of rendering this `Frame`.
#[no_mangle]
pub unsafe extern "C" fn frame_latency_points(frame: *const Frame) -> u32 {
(*(*(*frame).inner).0).latency_points()
}
/// Retrieve the current ideal `points_per_frame` at the time of rendering this `Frame`.
#[no_mangle]
pub unsafe extern "C" fn points_per_frame(frame: *const Frame) -> u32 {
(*(*(*frame).inner).0).latency_points()
}
/// Must be called in order to correctly clean up the frame stream.
#[no_mangle]
pub unsafe extern "C" fn frame_stream_drop(stream: FrameStream) {
if stream.inner != std::ptr::null_mut() {
Box::from_raw(stream.inner);
}
}
/// Must be called in order to correctly clean up the raw stream.
#[no_mangle]
pub unsafe extern "C" fn raw_stream_drop(stream: RawStream) {
if stream.inner != std::ptr::null_mut() {
Box::from_raw(stream.inner);
}
}
/// Must be called in order to correctly clean up the `DetectDacsAsync` resources.
#[no_mangle]
pub unsafe extern "C" fn detect_dacs_async_drop(detect: DetectDacsAsync) {
if detect.inner != std::ptr::null_mut() {
Box::from_raw(detect.inner);
}
}
/// Must be called in order to correctly clean up the API resources.
#[no_mangle]
pub unsafe extern "C" fn api_drop(api: Api) {
if api.inner != std::ptr::null_mut() {
Box::from_raw(api.inner);
}
}
/// Used for retrieving the last error that occurred from the API.
#[no_mangle]
pub unsafe extern "C" fn api_last_error(api: *const Api) -> *const raw::c_char {
let api: &ApiInner = &(*(*api).inner);
match api.last_error {
None => std::ptr::null(),
Some(ref cstring) => cstring.as_ptr(),
}
}
/// Used for retrieving the last error that occurred from the API.
#[no_mangle]
pub unsafe extern "C" fn detect_dacs_async_last_error(
detect: *const DetectDacsAsync,
) -> *const raw::c_char {
let detect_dacs_async: &DetectDacsAsyncInner = &(*(*detect).inner);
let mut s = std::ptr::null();
if let Ok(last_error) = detect_dacs_async.last_error.lock() {
if let Some(ref cstring) = *last_error {
s = cstring.as_ptr();
}
}
s
}
/// Begin asynchronous DAC detection.
///
/// The given timeout corresponds to the duration of time since the last DAC broadcast was received
/// before a DAC will be considered to be unavailable again.
fn detect_dacs_async_inner(
api: &crate::Api,
dac_timeout: Option<Duration>,
) -> io::Result<DetectDacsAsyncInner> {
let dacs = Arc::new(Mutex::new(HashMap::new()));
let last_error = Arc::new(Mutex::new(None));
let dacs2 = dacs.clone();
let last_error2 = last_error.clone();
let _inner = api.detect_dacs_async(
dac_timeout,
move |res: io::Result<crate::DetectedDac>| match res {
Ok(dac) => {
let now = Instant::now();
let mut dacs = dacs2.lock().unwrap();
dacs.insert(dac.id(), (now, dac));
if let Some(timeout) = dac_timeout {
dacs.retain(|_, (ref last_bc, _)| now.duration_since(*last_bc) < timeout);
}
}
Err(err) => match err.kind() {
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => {
dacs2.lock().unwrap().clear();
}
_ => {
*last_error2.lock().unwrap() = Some(err_to_cstring(&err));
}
},
},
)?;
Ok(DetectDacsAsyncInner {
_inner,
dacs,
last_error,
})
}
fn err_to_cstring(err: &dyn fmt::Display) -> CString {
string_to_cstring(format!("{}", err))
}
fn string_to_cstring(string: String) -> CString {
CString::new(string.into_bytes()).expect("`string` contained null bytes")
}
fn default_stream_config() -> StreamConfig {
let detected_dac = std::ptr::null();
let point_hz = crate::stream::DEFAULT_POINT_HZ;
let latency_points = crate::stream::raw::default_latency_points(point_hz);
StreamConfig {
detected_dac,
point_hz,
latency_points,
}
}
fn socket_addr_to_ffi(addr: std::net::SocketAddr) -> SocketAddr {
let port = addr.port();
let mut bytes = [0u8; 16];
let ip = match addr.ip() {
std::net::IpAddr::V4(ref ip) => {
for (byte, octet) in bytes.iter_mut().zip(&ip.octets()) {
*byte = *octet;
}
let version = IpAddrVersion::V4;
IpAddr { version, bytes }
}
std::net::IpAddr::V6(ref ip) => {
for (byte, octet) in bytes.iter_mut().zip(&ip.octets()) {
*byte = *octet;
}
let version = IpAddrVersion::V6;
IpAddr { version, bytes }
}
};
SocketAddr { ip, port }
}
fn socket_addr_from_ffi(addr: SocketAddr) -> std::net::SocketAddr {
let ip = match addr.ip.version {
IpAddrVersion::V4 => {
let b = &addr.ip.bytes;
std::net::IpAddr::from([b[0], b[1], b[2], b[3]])
}
IpAddrVersion::V6 => std::net::IpAddr::from(addr.ip.bytes),
};
std::net::SocketAddr::new(ip, addr.port)
}
fn detected_dac_to_ffi(dac: crate::DetectedDac) -> DetectedDac {
match dac {
crate::DetectedDac::EtherDream {
broadcast,
source_addr,
} => {
let source_addr = socket_addr_to_ffi(source_addr);
let ether_dream = DacEtherDream {
broadcast,
source_addr,
};
let kind = DetectedDacKind { ether_dream };
DetectedDac { kind }
}
}
}
fn detected_dac_from_ffi(ffi_dac: DetectedDac) -> crate::DetectedDac {
unsafe {
let broadcast = ffi_dac.kind.ether_dream.broadcast.clone();
let source_addr = socket_addr_from_ffi(ffi_dac.kind.ether_dream.source_addr);
crate::DetectedDac::EtherDream {
broadcast,
source_addr,
}
}
}
| true |
38620374925e4827eca77667c9eb13b68879f167
|
Rust
|
colingluwa/Creditcoin-Consensus-Rust
|
/src/primitives/hash.rs
|
UTF-8
| 2,508 | 2.703125 | 3 |
[] |
no_license
|
macro_rules! impl_hash {
($name:ident, $size:expr) => {
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct $name {
inner: [u8; $size],
}
impl $name {
pub const SIZE: usize = $size;
pub const MIN: Self = Self {
inner: [u8::min_value(); $size],
};
pub const MAX: Self = Self {
inner: [u8::max_value(); $size],
};
pub const fn new() -> Self {
Self { inner: [0; $size] }
}
pub fn random() -> Self {
let mut this: Self = Self::new();
::rand::Rng::fill(&mut ::rand::thread_rng(), &mut this[..]);
this
}
pub fn reversed(&self) -> Self {
let mut this: Self = *self;
this.reverse();
this
}
pub fn to_hex(&self) -> String {
$crate::utils::to_hex(self)
}
}
impl ::std::ops::Deref for $name {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl ::std::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl AsRef<[u8]> for $name {
fn as_ref(&self) -> &[u8] {
&self.inner
}
}
impl From<[u8; $size]> for $name {
fn from(inner: [u8; $size]) -> Self {
$name { inner }
}
}
impl From<$name> for [u8; $size] {
fn from(this: $name) -> Self {
this.inner
}
}
impl ::std::fmt::Debug for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.to_hex())
}
}
impl ::std::fmt::Display for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.to_hex())
}
}
impl Default for $name {
fn default() -> Self {
Self::new()
}
}
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
(&**self).eq(&**other)
}
}
impl Eq for $name {}
impl PartialOrd for $name {
fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
(&**self).partial_cmp(&**other)
}
}
impl Ord for $name {
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
(&**self).cmp(&**other)
}
}
impl ::std::hash::Hash for $name {
fn hash<H: ::std::hash::Hasher>(&self, hasher: &mut H) {
self.inner.hash(hasher)
}
}
};
}
impl_hash!(H256, 32);
| true |
1964af6946fc28cd363b40613e9e817d4617e63e
|
Rust
|
astral-sh/ruff
|
/crates/ruff_diagnostics/src/fix.rs
|
UTF-8
| 6,179 | 3.0625 | 3 |
[
"BSD-3-Clause",
"0BSD",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] |
permissive
|
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use ruff_text_size::TextSize;
use crate::edit::Edit;
/// Indicates confidence in the correctness of a suggested fix.
#[derive(Default, Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Applicability {
/// The fix is definitely what the user intended, or maintains the exact meaning of the code.
/// This fix should be automatically applied.
Automatic,
/// The fix may be what the user intended, but it is uncertain.
/// The fix should result in valid code if it is applied.
/// The fix can be applied with user opt-in.
Suggested,
/// The fix has a good chance of being incorrect or the code be incomplete.
/// The fix may result in invalid code if it is applied.
/// The fix should only be manually applied by the user.
Manual,
/// The applicability of the fix is unknown.
#[default]
Unspecified,
}
/// Indicates the level of isolation required to apply a fix.
#[derive(Default, Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum IsolationLevel {
/// The fix should be applied as long as no other fixes in the same group have been applied.
Group(u32),
/// The fix should be applied as long as it does not overlap with any other fixes.
#[default]
NonOverlapping,
}
/// A collection of [`Edit`] elements to be applied to a source file.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Fix {
/// The [`Edit`] elements to be applied, sorted by [`Edit::start`] in ascending order.
edits: Vec<Edit>,
/// The [`Applicability`] of the fix.
applicability: Applicability,
/// The [`IsolationLevel`] of the fix.
isolation_level: IsolationLevel,
}
impl Fix {
/// Create a new [`Fix`] with an unspecified applicability from an [`Edit`] element.
#[deprecated(
note = "Use `Fix::automatic`, `Fix::suggested`, or `Fix::manual` instead to specify an applicability."
)]
pub fn unspecified(edit: Edit) -> Self {
Self {
edits: vec![edit],
applicability: Applicability::Unspecified,
isolation_level: IsolationLevel::default(),
}
}
/// Create a new [`Fix`] with an unspecified applicability from multiple [`Edit`] elements.
#[deprecated(
note = "Use `Fix::automatic_edits`, `Fix::suggested_edits`, or `Fix::manual_edits` instead to specify an applicability."
)]
pub fn unspecified_edits(edit: Edit, rest: impl IntoIterator<Item = Edit>) -> Self {
Self {
edits: std::iter::once(edit).chain(rest).collect(),
applicability: Applicability::Unspecified,
isolation_level: IsolationLevel::default(),
}
}
/// Create a new [`Fix`] with [automatic applicability](Applicability::Automatic) from an [`Edit`] element.
pub fn automatic(edit: Edit) -> Self {
Self {
edits: vec![edit],
applicability: Applicability::Automatic,
isolation_level: IsolationLevel::default(),
}
}
/// Create a new [`Fix`] with [automatic applicability](Applicability::Automatic) from multiple [`Edit`] elements.
pub fn automatic_edits(edit: Edit, rest: impl IntoIterator<Item = Edit>) -> Self {
let mut edits: Vec<Edit> = std::iter::once(edit).chain(rest).collect();
edits.sort_by_key(Edit::start);
Self {
edits,
applicability: Applicability::Automatic,
isolation_level: IsolationLevel::default(),
}
}
/// Create a new [`Fix`] with [suggested applicability](Applicability::Suggested) from an [`Edit`] element.
pub fn suggested(edit: Edit) -> Self {
Self {
edits: vec![edit],
applicability: Applicability::Suggested,
isolation_level: IsolationLevel::default(),
}
}
/// Create a new [`Fix`] with [suggested applicability](Applicability::Suggested) from multiple [`Edit`] elements.
pub fn suggested_edits(edit: Edit, rest: impl IntoIterator<Item = Edit>) -> Self {
let mut edits: Vec<Edit> = std::iter::once(edit).chain(rest).collect();
edits.sort_by_key(Edit::start);
Self {
edits,
applicability: Applicability::Suggested,
isolation_level: IsolationLevel::default(),
}
}
/// Create a new [`Fix`] with [manual applicability](Applicability::Manual) from an [`Edit`] element.
pub fn manual(edit: Edit) -> Self {
Self {
edits: vec![edit],
applicability: Applicability::Manual,
isolation_level: IsolationLevel::default(),
}
}
/// Create a new [`Fix`] with [manual applicability](Applicability::Manual) from multiple [`Edit`] elements.
pub fn manual_edits(edit: Edit, rest: impl IntoIterator<Item = Edit>) -> Self {
let mut edits: Vec<Edit> = std::iter::once(edit).chain(rest).collect();
edits.sort_by_key(Edit::start);
Self {
edits,
applicability: Applicability::Manual,
isolation_level: IsolationLevel::default(),
}
}
/// Return the [`TextSize`] of the first [`Edit`] in the [`Fix`].
pub fn min_start(&self) -> Option<TextSize> {
self.edits.first().map(Edit::start)
}
/// Return a slice of the [`Edit`] elements in the [`Fix`], sorted by [`Edit::start`] in ascending order.
pub fn edits(&self) -> &[Edit] {
&self.edits
}
/// Return the [`Applicability`] of the [`Fix`].
pub fn applicability(&self) -> Applicability {
self.applicability
}
/// Return the [`IsolationLevel`] of the [`Fix`].
pub fn isolation(&self) -> IsolationLevel {
self.isolation_level
}
/// Create a new [`Fix`] with the given [`IsolationLevel`].
#[must_use]
pub fn isolate(mut self, isolation: IsolationLevel) -> Self {
self.isolation_level = isolation;
self
}
}
| true |
a1c5348ad2f062b5ba5bb6eace6e6851eaaa20eb
|
Rust
|
nbigaouette/advent_of_code_2018
|
/day03/src/preparsed_ndarray.rs
|
UTF-8
| 4,454 | 2.9375 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::cmp;
use std::collections::HashSet;
use crate::{parse_input, AoC, Day03SolutionPart1, Day03SolutionPart2, Input};
use ndarray::Array2;
type Grid = Array2<Vec<usize>>;
#[derive(Debug)]
pub struct Day03PreparsedNdarray {
input: Vec<Input>,
grid_size_width: usize,
grid_size_height: usize,
}
fn build_grid(input: &[Input], grid_size_width: usize, grid_size_height: usize) -> Grid {
let mut grid = Array2::<Vec<usize>>::from_elem((grid_size_width, grid_size_height), Vec::new());
for claim in input {
for i in claim.left..(claim.left + claim.wide) {
for j in claim.top..(claim.top + claim.tall) {
grid[[i, j]].push(claim.id);
}
}
}
grid
}
impl<'a> AoC<'a> for Day03PreparsedNdarray {
type SolutionPart1 = Day03SolutionPart1;
type SolutionPart2 = Day03SolutionPart2;
fn description(&self) -> &'static str {
"Pre-parsed string and ndarray"
}
fn new(input: &'a str) -> Day03PreparsedNdarray {
let input: Vec<_> = parse_input(input).collect();
let grid_size_width = input.iter().fold(0, |acc, claim| {
let width = claim.left + claim.wide;
cmp::max(width, acc)
});
let grid_size_height = input.iter().fold(0, |acc, claim| {
let height = claim.top + claim.tall;
cmp::max(height, acc)
});
Day03PreparsedNdarray {
input,
grid_size_width,
grid_size_height,
}
}
fn solution_part1(&self) -> Self::SolutionPart1 {
let grid = build_grid(&self.input, self.grid_size_width, self.grid_size_height);
grid.iter()
.filter_map(|p| if p.len() >= 2 { Some(1) } else { None })
.count()
}
fn solution_part2(&self) -> Self::SolutionPart2 {
let grid = build_grid(&self.input, self.grid_size_width, self.grid_size_height);
let mut claims: HashSet<usize> = self.input.iter().map(|claim| claim.id).collect();
for claim_ids in grid.iter() {
if claim_ids.len() >= 2 {
for claim_id in claim_ids {
claims.remove(claim_id);
}
}
}
assert_eq!(claims.len(), 1);
*claims.iter().next().unwrap()
}
}
#[cfg(test)]
mod tests {
mod part1 {
mod solution {
use super::super::super::Day03PreparsedNdarray;
use crate::{tests::init_logger, AoC, PUZZLE_INPUT};
#[test]
fn solution() {
init_logger();
let expected = 100595;
let to_check = Day03PreparsedNdarray::new(PUZZLE_INPUT).solution_part1();
assert_eq!(expected, to_check);
}
}
mod given {
use super::super::super::Day03PreparsedNdarray;
use crate::{tests::init_logger, AoC};
#[test]
fn ex01() {
init_logger();
let expected = 4;
let input = "#1 @ 1,3: 4x4
#2 @ 3,1: 4x4
#3 @ 5,5: 2x2";
let to_check = Day03PreparsedNdarray::new(input).solution_part1();
assert_eq!(expected, to_check);
}
}
/*
mod extra {
use ::*;
}
*/
}
mod part2 {
mod solution {
use super::super::super::Day03PreparsedNdarray;
use crate::{tests::init_logger, AoC, PUZZLE_INPUT};
#[test]
fn solution() {
init_logger();
let expected = 415;
let to_check = Day03PreparsedNdarray::new(PUZZLE_INPUT).solution_part2();
assert_eq!(expected, to_check);
}
}
mod given {
use super::super::super::Day03PreparsedNdarray;
use crate::{tests::init_logger, AoC};
#[test]
fn ex01() {
init_logger();
let expected = 3;
let input = "#1 @ 1,3: 4x4
#2 @ 3,1: 4x4
#3 @ 5,5: 2x2";
let to_check = Day03PreparsedNdarray::new(input).solution_part2();
assert_eq!(expected, to_check);
}
}
/*
mod extra {
use ::*;
}
*/
}
}
| true |
2c09696fe56066e2f1721746d430a8ba43689692
|
Rust
|
kinseywk/dicey
|
/src/lib.rs
|
UTF-8
| 3,685 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
#![allow(non_snake_case, non_upper_case_globals)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DieRoll {
//Number of dice in the roll
pub quantity: usize,
//Number of die faces (6 = standard cubic die)
pub faces: usize,
//Net bonus and malus applied to the roll (e.g., 1d4+1 adds 1 to each roll)
pub adjustment: isize,
}
pub fn parse(diceRoll: &str) -> Option<Vec<DieRoll>> {
let mut result: Vec<DieRoll> = Vec::new();
//1.) Split input string on each ','
let diceRoll: Vec<&str> = diceRoll.split(',').collect();
for dieRoll in diceRoll {
let mut adjustmentChar: Option<char> = None;
let mut adjustment: isize = 0;
let mut dieString: &str = dieRoll;
//2.) Split-off the '+' or '-' clause, if one exists
//2a.) Test if '+' and '-' are in the string
if let Some(_) = dieRoll.find('+') {
adjustmentChar = Some('+');
} else if let Some(_) = dieRoll.find('-') {
adjustmentChar = Some('-');
}
//2b.) If either exists, break-off the front part and parse the latter part as an integer
if let None = adjustmentChar {
} else {
if let Some((diePart, adjustmentPart)) = dieString.split_once(adjustmentChar.unwrap()) {
dieString = diePart;
if let Ok(adjustmentParsed) = adjustmentPart.parse::<isize>() {
adjustment = adjustmentParsed;
//2c.) Finally, if the prior test matched a '-', make the parsed number negative
if adjustmentChar.unwrap() == '-' {
adjustment = -adjustment;
}
} else {
return None;
}
}
}
//3.) Split each dice string on 'd'
if let Some((quantityPart, facesPart)) = dieString.split_once('d') {
//4.) Parse each of _those_ strings as positive integers and create a DieRoll from each pair
if let (Ok(quantity), Ok(faces)) = (quantityPart.parse::<usize>(), facesPart.parse::<usize>()) {
if quantity == 0 || faces == 0 {
return None;
} else {
result.push(DieRoll{quantity, faces, adjustment});
}
} else {
return None;
}
} else {
return None;
}
}
Some(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_single() {
{
const test: &str = "5d6";
if let Some(result) = parse(test) {
assert_eq!(result[0], DieRoll{quantity: 5, faces: 6, adjustment: 0});
} else {
panic!("Failed to parse string \"{}\"", test);
}
}
{
const test: &str = "3d4+1";
if let Some(result) = parse(test) {
assert_eq!(result[0], DieRoll{quantity: 3, faces: 4, adjustment: 1});
} else {
panic!("Failed to parse string \"{}\"", test);
}
}
{
const test: &str = "1d2-1";
if let Some(result) = parse(test) {
assert_eq!(result[0], DieRoll{quantity: 1, faces: 2, adjustment: -1});
} else {
panic!("Failed to parse string \"{}\"", test);
}
}
}
#[test]
fn parse_list() {
const test: &str = "1d1,100d100,1000000d1000000,1d100+100,100d1-1";
if let Some(result) = parse(test) {
assert_eq!(result.len(), 5, "Failed to parse all list entries");
assert_eq!(result[0], DieRoll{quantity: 1, faces: 1, adjustment: 0});
assert_eq!(result[1], DieRoll{quantity: 100, faces: 100, adjustment: 0});
assert_eq!(result[2], DieRoll{quantity: 1000000, faces: 1000000, adjustment: 0});
assert_eq!(result[3], DieRoll{quantity: 1, faces: 100, adjustment: 100});
assert_eq!(result[4], DieRoll{quantity: 100, faces: 1, adjustment: -1});
} else {
panic!("Failed to parse string \"{}\"", test);
}
}
#[test]
fn parse_fail() {
const tests: &'static [&'static str] = &["r2d2", "-3d3", "3d-3", "3d0", "0d3", "3d", "d3", "3d3,", ",", ""];
for test in tests {
assert_eq!(parse(test), None, "Incorrectly parsed invalid string \"{}\"", test);
}
}
}
| true |
1cb91910631be47d9fbc78821be91beeb4cc5743
|
Rust
|
Concordium/wasm-tools
|
/crates/wasm-encoder/src/code.rs
|
UTF-8
| 26,694 | 3.375 | 3 |
[
"LLVM-exception",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use super::*;
/// An encoder for the code section.
///
/// # Example
///
/// ```
/// use wasm_encoder::{
/// CodeSection, Function, FunctionSection, Instruction, Module,
/// TypeSection, ValType
/// };
///
/// let mut types = TypeSection::new();
/// types.function(vec![], vec![ValType::I32]);
///
/// let mut functions = FunctionSection::new();
/// let type_index = 0;
/// functions.function(type_index);
///
/// let locals = vec![];
/// let mut func = Function::new(locals);
/// func.instruction(Instruction::I32Const(42));
/// let mut code = CodeSection::new();
/// code.function(&func);
///
/// let mut module = Module::new();
/// module
/// .section(&types)
/// .section(&functions)
/// .section(&code);
///
/// let wasm_bytes = module.finish();
/// ```
pub struct CodeSection {
bytes: Vec<u8>,
num_added: u32,
}
impl CodeSection {
/// Create a new code section encoder.
pub fn new() -> CodeSection {
CodeSection {
bytes: vec![],
num_added: 0,
}
}
/// Write a function body into this code section.
pub fn function(&mut self, func: &Function) -> &mut Self {
func.encode(&mut self.bytes);
self.num_added += 1;
self
}
}
impl Section for CodeSection {
fn id(&self) -> u8 {
SectionId::Code.into()
}
fn encode<S>(&self, sink: &mut S)
where
S: Extend<u8>,
{
let num_added = encoders::u32(self.num_added);
let n = num_added.len();
sink.extend(
encoders::u32(u32::try_from(n + self.bytes.len()).unwrap())
.chain(num_added)
.chain(self.bytes.iter().copied()),
);
}
}
/// An encoder for a function body within the code section.
///
/// # Example
///
/// ```
/// use wasm_encoder::{CodeSection, Function, Instruction};
///
/// // Define the function body for:
/// //
/// // (func (param i32 i32) (result i32)
/// // local.get 0
/// // local.get 1
/// // i32.add)
/// let locals = vec![];
/// let mut func = Function::new(locals);
/// func.instruction(Instruction::LocalGet(0));
/// func.instruction(Instruction::LocalGet(1));
/// func.instruction(Instruction::I32Add);
///
/// // Add our function to the code section.
/// let mut code = CodeSection::new();
/// code.function(&func);
/// ```
pub struct Function {
bytes: Vec<u8>,
}
impl Function {
/// Create a new function body with the given locals.
pub fn new<L>(locals: L) -> Self
where
L: IntoIterator<Item = (u32, ValType)>,
L::IntoIter: ExactSizeIterator,
{
let locals = locals.into_iter();
let mut bytes = vec![];
bytes.extend(encoders::u32(u32::try_from(locals.len()).unwrap()));
for (count, ty) in locals {
bytes.extend(encoders::u32(count));
bytes.push(ty.into());
}
Function { bytes }
}
/// Write an instruction into this function body.
pub fn instruction(&mut self, instruction: Instruction) -> &mut Self {
instruction.encode(&mut self.bytes);
self
}
/// Add raw bytes to this function's body.
pub fn raw<B>(&mut self, bytes: B) -> &mut Self
where
B: IntoIterator<Item = u8>,
{
self.bytes.extend(bytes);
self
}
fn encode(&self, bytes: &mut Vec<u8>) {
bytes.extend(
encoders::u32(u32::try_from(self.bytes.len()).unwrap())
.chain(self.bytes.iter().copied()),
);
}
}
/// The immediate for a memory instruction.
#[derive(Clone, Copy, Debug)]
pub struct MemArg {
/// A static offset to add to the instruction's dynamic address operand.
pub offset: u32,
/// The expected alignment of the instruction's dynamic address operand
/// (expressed the exponent of a power of two).
pub align: u32,
/// The index of the memory this instruction is operating upon.
pub memory_index: u32,
}
impl MemArg {
fn encode(&self, bytes: &mut Vec<u8>) {
if self.memory_index == 0 {
bytes.extend(encoders::u32(self.align));
bytes.extend(encoders::u32(self.offset));
} else {
bytes.extend(encoders::u32(self.align | (1 << 6)));
bytes.extend(encoders::u32(self.offset));
bytes.extend(encoders::u32(self.memory_index));
}
}
}
/// The type for a `block`/`if`/`loop`.
#[derive(Clone, Copy, Debug)]
pub enum BlockType {
/// `[] -> []`
Empty,
/// `[] -> [t]`
Result(ValType),
/// The `n`th function type.
FunctionType(u32),
}
impl BlockType {
fn encode(&self, bytes: &mut Vec<u8>) {
match *self {
BlockType::Empty => bytes.push(0x40),
BlockType::Result(ty) => bytes.push(ty.into()),
BlockType::FunctionType(f) => bytes.extend(encoders::s33(f.into())),
}
}
}
/// WebAssembly instructions.
#[derive(Clone, Debug)]
#[non_exhaustive]
#[allow(missing_docs, non_camel_case_types)]
pub enum Instruction<'a> {
// Control instructions.
Unreachable,
Nop,
Block(BlockType),
Loop(BlockType),
If(BlockType),
Else,
End,
Br(u32),
BrIf(u32),
BrTable(&'a [u32], u32),
Return,
Call(u32),
CallIndirect { ty: u32, table: u32 },
// Parametric instructions.
Drop,
Select,
// Variable instructions.
LocalGet(u32),
LocalSet(u32),
LocalTee(u32),
GlobalGet(u32),
GlobalSet(u32),
// Memory instructions.
I32Load(MemArg),
I64Load(MemArg),
F32Load(MemArg),
F64Load(MemArg),
I32Load8_S(MemArg),
I32Load8_U(MemArg),
I32Load16_S(MemArg),
I32Load16_U(MemArg),
I64Load8_S(MemArg),
I64Load8_U(MemArg),
I64Load16_S(MemArg),
I64Load16_U(MemArg),
I64Load32_S(MemArg),
I64Load32_U(MemArg),
I32Store(MemArg),
I64Store(MemArg),
F32Store(MemArg),
F64Store(MemArg),
I32Store8(MemArg),
I32Store16(MemArg),
I64Store8(MemArg),
I64Store16(MemArg),
I64Store32(MemArg),
MemorySize(u32),
MemoryGrow(u32),
MemoryInit { mem: u32, data: u32 },
DataDrop(u32),
MemoryCopy { src: u32, dst: u32 },
MemoryFill(u32),
// Numeric instructions.
I32Const(i32),
I64Const(i64),
F32Const(f32),
F64Const(f64),
I32Eqz,
I32Eq,
I32Neq,
I32LtS,
I32LtU,
I32GtS,
I32GtU,
I32LeS,
I32LeU,
I32GeS,
I32GeU,
I64Eqz,
I64Eq,
I64Neq,
I64LtS,
I64LtU,
I64GtS,
I64GtU,
I64LeS,
I64LeU,
I64GeS,
I64GeU,
F32Eq,
F32Neq,
F32Lt,
F32Gt,
F32Le,
F32Ge,
F64Eq,
F64Neq,
F64Lt,
F64Gt,
F64Le,
F64Ge,
I32Clz,
I32Ctz,
I32Popcnt,
I32Add,
I32Sub,
I32Mul,
I32DivS,
I32DivU,
I32RemS,
I32RemU,
I32And,
I32Or,
I32Xor,
I32Shl,
I32ShrS,
I32ShrU,
I32Rotl,
I32Rotr,
I64Clz,
I64Ctz,
I64Popcnt,
I64Add,
I64Sub,
I64Mul,
I64DivS,
I64DivU,
I64RemS,
I64RemU,
I64And,
I64Or,
I64Xor,
I64Shl,
I64ShrS,
I64ShrU,
I64Rotl,
I64Rotr,
F32Abs,
F32Neg,
F32Ceil,
F32Floor,
F32Trunc,
F32Nearest,
F32Sqrt,
F32Add,
F32Sub,
F32Mul,
F32Div,
F32Min,
F32Max,
F32Copysign,
F64Abs,
F64Neg,
F64Ceil,
F64Floor,
F64Trunc,
F64Nearest,
F64Sqrt,
F64Add,
F64Sub,
F64Mul,
F64Div,
F64Min,
F64Max,
F64Copysign,
I32WrapI64,
I32TruncF32S,
I32TruncF32U,
I32TruncF64S,
I32TruncF64U,
I64ExtendI32S,
I64ExtendI32U,
I64TruncF32S,
I64TruncF32U,
I64TruncF64S,
I64TruncF64U,
F32ConvertI32S,
F32ConvertI32U,
F32ConvertI64S,
F32ConvertI64U,
F32DemoteF64,
F64ConvertI32S,
F64ConvertI32U,
F64ConvertI64S,
F64ConvertI64U,
F64PromoteF32,
I32ReinterpretF32,
I64ReinterpretF64,
F32ReinterpretI32,
F64ReinterpretI64,
I32Extend8S,
I32Extend16S,
I64Extend8S,
I64Extend16S,
I64Extend32S,
I32TruncSatF32S,
I32TruncSatF32U,
I32TruncSatF64S,
I32TruncSatF64U,
I64TruncSatF32S,
I64TruncSatF32U,
I64TruncSatF64S,
I64TruncSatF64U,
// SIMD instructions.
V128Const(i128),
// Reference types instructions.
TypedSelect(ValType),
RefNull(ValType),
RefIsNull,
RefFunc(u32),
// Bulk memory instructions.
TableInit { segment: u32, table: u32 },
ElemDrop { segment: u32 },
TableFill { table: u32 },
TableSet { table: u32 },
TableGet { table: u32 },
TableGrow { table: u32 },
TableSize { table: u32 },
TableCopy { src: u32, dst: u32 },
}
impl Instruction<'_> {
pub(crate) fn encode(&self, bytes: &mut Vec<u8>) {
match *self {
// Control instructions.
Instruction::Unreachable => bytes.push(0x00),
Instruction::Nop => bytes.push(0x01),
Instruction::Block(bt) => {
bytes.push(0x02);
bt.encode(bytes);
}
Instruction::Loop(bt) => {
bytes.push(0x03);
bt.encode(bytes);
}
Instruction::If(bt) => {
bytes.push(0x04);
bt.encode(bytes);
}
Instruction::Else => bytes.push(0x05),
Instruction::End => bytes.push(0x0B),
Instruction::Br(l) => {
bytes.push(0x0C);
bytes.extend(encoders::u32(l));
}
Instruction::BrIf(l) => {
bytes.push(0x0D);
bytes.extend(encoders::u32(l));
}
Instruction::BrTable(ls, l) => {
bytes.push(0x0E);
bytes.extend(encoders::u32(u32::try_from(ls.len()).unwrap()));
for l in ls {
bytes.extend(encoders::u32(*l));
}
bytes.extend(encoders::u32(l));
}
Instruction::Return => bytes.push(0x0F),
Instruction::Call(f) => {
bytes.push(0x10);
bytes.extend(encoders::u32(f));
}
Instruction::CallIndirect { ty, table } => {
bytes.push(0x11);
bytes.extend(encoders::u32(ty));
bytes.extend(encoders::u32(table));
}
// Parametric instructions.
Instruction::Drop => bytes.push(0x1A),
Instruction::Select => bytes.push(0x1B),
Instruction::TypedSelect(ty) => {
bytes.push(0x1c);
bytes.extend(encoders::u32(1));
bytes.push(ty.into());
}
// Variable instructions.
Instruction::LocalGet(l) => {
bytes.push(0x20);
bytes.extend(encoders::u32(l));
}
Instruction::LocalSet(l) => {
bytes.push(0x21);
bytes.extend(encoders::u32(l));
}
Instruction::LocalTee(l) => {
bytes.push(0x22);
bytes.extend(encoders::u32(l));
}
Instruction::GlobalGet(g) => {
bytes.push(0x23);
bytes.extend(encoders::u32(g));
}
Instruction::GlobalSet(g) => {
bytes.push(0x24);
bytes.extend(encoders::u32(g));
}
Instruction::TableGet { table } => {
bytes.push(0x25);
bytes.extend(encoders::u32(table));
}
Instruction::TableSet { table } => {
bytes.push(0x26);
bytes.extend(encoders::u32(table));
}
// Memory instructions.
Instruction::I32Load(m) => {
bytes.push(0x28);
m.encode(bytes);
}
Instruction::I64Load(m) => {
bytes.push(0x29);
m.encode(bytes);
}
Instruction::F32Load(m) => {
bytes.push(0x2A);
m.encode(bytes);
}
Instruction::F64Load(m) => {
bytes.push(0x2B);
m.encode(bytes);
}
Instruction::I32Load8_S(m) => {
bytes.push(0x2C);
m.encode(bytes);
}
Instruction::I32Load8_U(m) => {
bytes.push(0x2D);
m.encode(bytes);
}
Instruction::I32Load16_S(m) => {
bytes.push(0x2E);
m.encode(bytes);
}
Instruction::I32Load16_U(m) => {
bytes.push(0x2F);
m.encode(bytes);
}
Instruction::I64Load8_S(m) => {
bytes.push(0x30);
m.encode(bytes);
}
Instruction::I64Load8_U(m) => {
bytes.push(0x31);
m.encode(bytes);
}
Instruction::I64Load16_S(m) => {
bytes.push(0x32);
m.encode(bytes);
}
Instruction::I64Load16_U(m) => {
bytes.push(0x33);
m.encode(bytes);
}
Instruction::I64Load32_S(m) => {
bytes.push(0x34);
m.encode(bytes);
}
Instruction::I64Load32_U(m) => {
bytes.push(0x35);
m.encode(bytes);
}
Instruction::I32Store(m) => {
bytes.push(0x36);
m.encode(bytes);
}
Instruction::I64Store(m) => {
bytes.push(0x37);
m.encode(bytes);
}
Instruction::F32Store(m) => {
bytes.push(0x38);
m.encode(bytes);
}
Instruction::F64Store(m) => {
bytes.push(0x39);
m.encode(bytes);
}
Instruction::I32Store8(m) => {
bytes.push(0x3A);
m.encode(bytes);
}
Instruction::I32Store16(m) => {
bytes.push(0x3B);
m.encode(bytes);
}
Instruction::I64Store8(m) => {
bytes.push(0x3C);
m.encode(bytes);
}
Instruction::I64Store16(m) => {
bytes.push(0x3D);
m.encode(bytes);
}
Instruction::I64Store32(m) => {
bytes.push(0x3E);
m.encode(bytes);
}
Instruction::MemorySize(i) => {
bytes.push(0x3F);
bytes.extend(encoders::u32(i));
}
Instruction::MemoryGrow(i) => {
bytes.push(0x40);
bytes.extend(encoders::u32(i));
}
Instruction::MemoryInit { mem, data } => {
bytes.push(0xfc);
bytes.extend(encoders::u32(8));
bytes.extend(encoders::u32(data));
bytes.extend(encoders::u32(mem));
}
Instruction::DataDrop(data) => {
bytes.push(0xfc);
bytes.extend(encoders::u32(9));
bytes.extend(encoders::u32(data));
}
Instruction::MemoryCopy { src, dst } => {
bytes.push(0xfc);
bytes.extend(encoders::u32(10));
bytes.extend(encoders::u32(dst));
bytes.extend(encoders::u32(src));
}
Instruction::MemoryFill(mem) => {
bytes.push(0xfc);
bytes.extend(encoders::u32(11));
bytes.extend(encoders::u32(mem));
}
// Numeric instructions.
Instruction::I32Const(x) => {
bytes.push(0x41);
bytes.extend(encoders::s32(x));
}
Instruction::I64Const(x) => {
bytes.push(0x42);
bytes.extend(encoders::s64(x));
}
Instruction::F32Const(x) => {
bytes.push(0x43);
let x = x.to_bits();
bytes.extend(x.to_le_bytes().iter().copied());
}
Instruction::F64Const(x) => {
bytes.push(0x44);
let x = x.to_bits();
bytes.extend(x.to_le_bytes().iter().copied());
}
Instruction::I32Eqz => bytes.push(0x45),
Instruction::I32Eq => bytes.push(0x46),
Instruction::I32Neq => bytes.push(0x47),
Instruction::I32LtS => bytes.push(0x48),
Instruction::I32LtU => bytes.push(0x49),
Instruction::I32GtS => bytes.push(0x4A),
Instruction::I32GtU => bytes.push(0x4B),
Instruction::I32LeS => bytes.push(0x4C),
Instruction::I32LeU => bytes.push(0x4D),
Instruction::I32GeS => bytes.push(0x4E),
Instruction::I32GeU => bytes.push(0x4F),
Instruction::I64Eqz => bytes.push(0x50),
Instruction::I64Eq => bytes.push(0x51),
Instruction::I64Neq => bytes.push(0x52),
Instruction::I64LtS => bytes.push(0x53),
Instruction::I64LtU => bytes.push(0x54),
Instruction::I64GtS => bytes.push(0x55),
Instruction::I64GtU => bytes.push(0x56),
Instruction::I64LeS => bytes.push(0x57),
Instruction::I64LeU => bytes.push(0x58),
Instruction::I64GeS => bytes.push(0x59),
Instruction::I64GeU => bytes.push(0x5A),
Instruction::F32Eq => bytes.push(0x5B),
Instruction::F32Neq => bytes.push(0x5C),
Instruction::F32Lt => bytes.push(0x5D),
Instruction::F32Gt => bytes.push(0x5E),
Instruction::F32Le => bytes.push(0x5F),
Instruction::F32Ge => bytes.push(0x60),
Instruction::F64Eq => bytes.push(0x61),
Instruction::F64Neq => bytes.push(0x62),
Instruction::F64Lt => bytes.push(0x63),
Instruction::F64Gt => bytes.push(0x64),
Instruction::F64Le => bytes.push(0x65),
Instruction::F64Ge => bytes.push(0x66),
Instruction::I32Clz => bytes.push(0x67),
Instruction::I32Ctz => bytes.push(0x68),
Instruction::I32Popcnt => bytes.push(0x69),
Instruction::I32Add => bytes.push(0x6A),
Instruction::I32Sub => bytes.push(0x6B),
Instruction::I32Mul => bytes.push(0x6C),
Instruction::I32DivS => bytes.push(0x6D),
Instruction::I32DivU => bytes.push(0x6E),
Instruction::I32RemS => bytes.push(0x6F),
Instruction::I32RemU => bytes.push(0x70),
Instruction::I32And => bytes.push(0x71),
Instruction::I32Or => bytes.push(0x72),
Instruction::I32Xor => bytes.push(0x73),
Instruction::I32Shl => bytes.push(0x74),
Instruction::I32ShrS => bytes.push(0x75),
Instruction::I32ShrU => bytes.push(0x76),
Instruction::I32Rotl => bytes.push(0x77),
Instruction::I32Rotr => bytes.push(0x78),
Instruction::I64Clz => bytes.push(0x79),
Instruction::I64Ctz => bytes.push(0x7A),
Instruction::I64Popcnt => bytes.push(0x7B),
Instruction::I64Add => bytes.push(0x7C),
Instruction::I64Sub => bytes.push(0x7D),
Instruction::I64Mul => bytes.push(0x7E),
Instruction::I64DivS => bytes.push(0x7F),
Instruction::I64DivU => bytes.push(0x80),
Instruction::I64RemS => bytes.push(0x81),
Instruction::I64RemU => bytes.push(0x82),
Instruction::I64And => bytes.push(0x83),
Instruction::I64Or => bytes.push(0x84),
Instruction::I64Xor => bytes.push(0x85),
Instruction::I64Shl => bytes.push(0x86),
Instruction::I64ShrS => bytes.push(0x87),
Instruction::I64ShrU => bytes.push(0x88),
Instruction::I64Rotl => bytes.push(0x89),
Instruction::I64Rotr => bytes.push(0x8A),
Instruction::F32Abs => bytes.push(0x8B),
Instruction::F32Neg => bytes.push(0x8C),
Instruction::F32Ceil => bytes.push(0x8D),
Instruction::F32Floor => bytes.push(0x8E),
Instruction::F32Trunc => bytes.push(0x8F),
Instruction::F32Nearest => bytes.push(0x90),
Instruction::F32Sqrt => bytes.push(0x91),
Instruction::F32Add => bytes.push(0x92),
Instruction::F32Sub => bytes.push(0x93),
Instruction::F32Mul => bytes.push(0x94),
Instruction::F32Div => bytes.push(0x95),
Instruction::F32Min => bytes.push(0x96),
Instruction::F32Max => bytes.push(0x97),
Instruction::F32Copysign => bytes.push(0x98),
Instruction::F64Abs => bytes.push(0x99),
Instruction::F64Neg => bytes.push(0x9A),
Instruction::F64Ceil => bytes.push(0x9B),
Instruction::F64Floor => bytes.push(0x9C),
Instruction::F64Trunc => bytes.push(0x9D),
Instruction::F64Nearest => bytes.push(0x9E),
Instruction::F64Sqrt => bytes.push(0x9F),
Instruction::F64Add => bytes.push(0xA0),
Instruction::F64Sub => bytes.push(0xA1),
Instruction::F64Mul => bytes.push(0xA2),
Instruction::F64Div => bytes.push(0xA3),
Instruction::F64Min => bytes.push(0xA4),
Instruction::F64Max => bytes.push(0xA5),
Instruction::F64Copysign => bytes.push(0xA6),
Instruction::I32WrapI64 => bytes.push(0xA7),
Instruction::I32TruncF32S => bytes.push(0xA8),
Instruction::I32TruncF32U => bytes.push(0xA9),
Instruction::I32TruncF64S => bytes.push(0xAA),
Instruction::I32TruncF64U => bytes.push(0xAB),
Instruction::I64ExtendI32S => bytes.push(0xAC),
Instruction::I64ExtendI32U => bytes.push(0xAD),
Instruction::I64TruncF32S => bytes.push(0xAE),
Instruction::I64TruncF32U => bytes.push(0xAF),
Instruction::I64TruncF64S => bytes.push(0xB0),
Instruction::I64TruncF64U => bytes.push(0xB1),
Instruction::F32ConvertI32S => bytes.push(0xB2),
Instruction::F32ConvertI32U => bytes.push(0xB3),
Instruction::F32ConvertI64S => bytes.push(0xB4),
Instruction::F32ConvertI64U => bytes.push(0xB5),
Instruction::F32DemoteF64 => bytes.push(0xB6),
Instruction::F64ConvertI32S => bytes.push(0xB7),
Instruction::F64ConvertI32U => bytes.push(0xB8),
Instruction::F64ConvertI64S => bytes.push(0xB9),
Instruction::F64ConvertI64U => bytes.push(0xBA),
Instruction::F64PromoteF32 => bytes.push(0xBB),
Instruction::I32ReinterpretF32 => bytes.push(0xBC),
Instruction::I64ReinterpretF64 => bytes.push(0xBD),
Instruction::F32ReinterpretI32 => bytes.push(0xBE),
Instruction::F64ReinterpretI64 => bytes.push(0xBF),
Instruction::I32Extend8S => bytes.push(0xC0),
Instruction::I32Extend16S => bytes.push(0xC1),
Instruction::I64Extend8S => bytes.push(0xC2),
Instruction::I64Extend16S => bytes.push(0xC3),
Instruction::I64Extend32S => bytes.push(0xC4),
Instruction::I32TruncSatF32S => {
bytes.push(0xFC);
bytes.extend(encoders::u32(0));
}
Instruction::I32TruncSatF32U => {
bytes.push(0xFC);
bytes.extend(encoders::u32(1));
}
Instruction::I32TruncSatF64S => {
bytes.push(0xFC);
bytes.extend(encoders::u32(2));
}
Instruction::I32TruncSatF64U => {
bytes.push(0xFC);
bytes.extend(encoders::u32(3));
}
Instruction::I64TruncSatF32S => {
bytes.push(0xFC);
bytes.extend(encoders::u32(4));
}
Instruction::I64TruncSatF32U => {
bytes.push(0xFC);
bytes.extend(encoders::u32(5));
}
Instruction::I64TruncSatF64S => {
bytes.push(0xFC);
bytes.extend(encoders::u32(6));
}
Instruction::I64TruncSatF64U => {
bytes.push(0xFC);
bytes.extend(encoders::u32(7));
}
// Reference types instructions.
Instruction::RefNull(ty) => {
bytes.push(0xd0);
bytes.push(ty.into());
}
Instruction::RefIsNull => bytes.push(0xd1),
Instruction::RefFunc(f) => {
bytes.push(0xd2);
bytes.extend(encoders::u32(f));
}
// Bulk memory instructions.
Instruction::TableInit { segment, table } => {
bytes.push(0xfc);
bytes.extend(encoders::u32(0x0c));
bytes.extend(encoders::u32(segment));
bytes.extend(encoders::u32(table));
}
Instruction::ElemDrop { segment } => {
bytes.push(0xfc);
bytes.extend(encoders::u32(0x0d));
bytes.extend(encoders::u32(segment));
}
Instruction::TableCopy { src, dst } => {
bytes.push(0xfc);
bytes.extend(encoders::u32(0x0e));
bytes.extend(encoders::u32(dst));
bytes.extend(encoders::u32(src));
}
Instruction::TableGrow { table } => {
bytes.push(0xfc);
bytes.extend(encoders::u32(0x0f));
bytes.extend(encoders::u32(table));
}
Instruction::TableSize { table } => {
bytes.push(0xfc);
bytes.extend(encoders::u32(0x10));
bytes.extend(encoders::u32(table));
}
Instruction::TableFill { table } => {
bytes.push(0xfc);
bytes.extend(encoders::u32(0x11));
bytes.extend(encoders::u32(table));
}
// SIMD instructions.
Instruction::V128Const(x) => {
bytes.push(0xFD);
bytes.extend(encoders::u32(12));
bytes.extend(x.to_le_bytes().iter().copied());
}
}
}
}
| true |
e590f9cc3bc61658b15ea7fcfedc93c7cce091ad
|
Rust
|
StackCrash/kryptos
|
/src/common/mod.rs
|
UTF-8
| 748 | 3.65625 | 4 |
[
"MIT"
] |
permissive
|
pub const ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub fn binary_to_char(bin: &str) -> Result<char, String> {
let binary = bin.as_bytes().iter().map(|b| b - 48).collect::<Vec<u8>>();
for bit in &binary {
if *bit > 1 {
return Err(String::from("Must be a valid binary number"));
}
}
Ok((binary.iter().fold(0, |x, &b| x * 2 + b as u8) + 65) as char)
}
#[cfg(test)]
mod tests {
use super::binary_to_char;
#[test]
fn valid_binary() {
assert!(binary_to_char("010").is_ok());
}
#[test]
fn invalid_binary() {
assert!(binary_to_char("2010").is_err());
}
#[test]
fn number_to_char() {
assert_eq!('C', binary_to_char("010").unwrap());
}
}
| true |
e95dd4fc71955bf79eb1ebf030173d27eb981356
|
Rust
|
yuan-yuan-jia/Algorithms
|
/src/problems/backtracking/nqueens.rs
|
UTF-8
| 4,430 | 3.765625 | 4 |
[
"MIT"
] |
permissive
|
//! The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
//!
//! Given an integer n, return all distinct solutions to the n-queens puzzle.
//!
//! Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
//!
//! # See also
//!
//! - [Leetcode](https://leetcode.com/problems/n-queens/)
use std::collections::HashSet;
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> {
Board::new(n as usize).solve()
}
struct Board {
matrix: Vec<Vec<char>>,
n: usize,
solutions: HashSet<Vec<String>>,
}
impl Board {
pub fn new(n: usize) -> Self {
Self {
matrix: vec![vec!['.'; n]; n],
n,
solutions: HashSet::new(),
}
}
pub fn solve(mut self) -> Vec<Vec<String>> {
self._solve(0, 0);
self.solutions.into_iter().collect()
}
fn _solve(&mut self, i: usize, count: usize) {
if count == self.n {
self.add_solution();
} else if i == self.n {
} else {
for col in 0..self.n {
if self.safe(i, col) {
self.matrix[i][col] = 'Q';
self._solve(i + 1, count + 1);
self.matrix[i][col] = '.';
}
}
}
}
fn add_solution(&mut self) {
self.solutions.insert(
self.matrix
.iter()
.map(|x| x.iter().copied().collect())
.collect(),
);
}
fn safe(&self, i: usize, j: usize) -> bool {
for j_ in 0..self.n {
if self.matrix[i][j_] == 'Q' {
return false;
}
}
for i_ in 0..self.n {
if self.matrix[i_][j] == 'Q' {
return false;
}
}
let (mut i_, mut j_) = (i + 1, j + 1);
while i_ > 0 && j_ > 0 {
i_ -= 1;
j_ -= 1;
if self.matrix[i_][j_] == 'Q' {
return false;
}
}
let (mut i_, mut j_) = (i, j + 1);
while i_ < self.n && j_ > 0 {
j_ -= 1;
if self.matrix[i_][j_] == 'Q' {
return false;
}
i_ += 1;
}
let (mut i_, mut j_) = (i, j);
while i_ < self.n && j_ < self.n {
if self.matrix[i_][j_] == 'Q' {
return false;
}
i_ += 1;
j_ += 1;
}
let (mut i_, mut j_) = (i + 1, j);
while i_ > 0 && j_ < self.n {
i_ -= 1;
if self.matrix[i_][j_] == 'Q' {
return false;
}
j_ += 1;
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_n_queens() {
let n1 = solve_n_queens(1);
assert_eq!(n1, vec![vec!["Q".to_string()]]);
let n2 = solve_n_queens(2);
assert!(n2.is_empty());
let n3 = solve_n_queens(3);
assert!(n3.is_empty());
let mut n4 = solve_n_queens(4);
n4.sort();
assert_eq!(
n4,
make_solution(&[
&["..Q.", "Q...", "...Q", ".Q.."],
&[".Q..", "...Q", "Q...", "..Q."],
])
);
let mut n5 = solve_n_queens(5);
let mut n5_expected = make_solution(&[
&["..Q..", "....Q", ".Q...", "...Q.", "Q...."],
&["...Q.", "Q....", "..Q..", "....Q", ".Q..."],
&["....Q", ".Q...", "...Q.", "Q....", "..Q.."],
&["Q....", "...Q.", ".Q...", "....Q", "..Q.."],
&[".Q...", "....Q", "..Q..", "Q....", "...Q."],
&["....Q", "..Q..", "Q....", "...Q.", ".Q..."],
&[".Q...", "...Q.", "Q....", "..Q..", "....Q"],
&["..Q..", "Q....", "...Q.", ".Q...", "....Q"],
&["...Q.", ".Q...", "....Q", "..Q..", "Q...."],
&["Q....", "..Q..", "....Q", ".Q...", "...Q."],
]);
n5.sort();
n5_expected.sort();
assert_eq!(n5, n5_expected);
let n8 = solve_n_queens(8);
assert_eq!(n8.len(), 92);
}
fn make_solution(sol: &[&[&'static str]]) -> Vec<Vec<String>> {
sol.iter()
.map(|&x| x.iter().map(|&s| s.to_owned()).collect())
.collect()
}
}
| true |
efd3d047c44fa30c6f88b9de8f3cc4410a97acaf
|
Rust
|
arbanhossain/5dchess-tools
|
/lib/parse.rs
|
UTF-8
| 2,769 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
use super::game;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct GameRaw {
timelines: Vec<TimelineRaw>,
width: u8,
height: u8,
active_player: bool,
}
/// Represents an in-game timeline
#[derive(Debug, Deserialize)]
struct TimelineRaw {
index: f32,
states: Vec<Vec<usize>>,
width: u8,
height: u8,
begins_at: isize,
emerges_from: Option<f32>,
}
pub fn parse(raw: &str) -> Option<game::Game> {
let game_raw: GameRaw = serde_json::from_str(raw).ok()?;
let even_initial_timelines = game_raw
.timelines
.iter()
.any(|tl| tl.index == -0.5 || tl.index == 0.5);
let min_timeline = game_raw.timelines
.iter()
.map(|tl| tl.index)
.min_by_key(|x| (*x) as isize)?;
let max_timeline = game_raw.timelines
.iter()
.map(|tl| tl.index)
.max_by_key(|x| (*x) as isize)?;
let timeline_width = ((-min_timeline).min(max_timeline) + 1.0).round();
let active_timelines = game_raw.timelines
.iter()
.filter(|tl| tl.index.abs() <= timeline_width);
let present = active_timelines
.map(|tl| tl.begins_at + (tl.states.len() as isize) - 1)
.min()?;
let mut res = game::Game::new(game_raw.width, game_raw.height);
res.info.present = present;
res.info.min_timeline = de_l(min_timeline, even_initial_timelines);
res.info.max_timeline = de_l(max_timeline, even_initial_timelines);
res.info.active_player = game_raw.active_player;
res.info.even_initial_timelines = even_initial_timelines;
for tl in game_raw.timelines.into_iter() {
res.timelines.insert(
de_l(tl.index, even_initial_timelines),
de_timeline(tl, even_initial_timelines),
);
}
Some(res)
}
fn de_board(raw: Vec<usize>, t: isize, l: i32, width: u8, height: u8) -> game::Board {
let mut res = game::Board::new(t, l, width, height);
res.pieces = raw
.into_iter()
.map(|x| game::Piece::from(x))
.collect();
res
}
fn de_l(raw: f32, even: bool) -> i32 {
if even && raw < 0.0 {
(raw.ceil() - 1.0) as i32
} else {
raw.floor() as i32
}
}
fn de_timeline(raw: TimelineRaw, even: bool) -> game::Timeline {
let mut res = game::Timeline::new(
de_l(raw.index, even),
raw.width,
raw.height,
raw.begins_at,
raw.emerges_from.map(|x| de_l(x, even)),
);
let index = de_l(raw.index, even);
let begins_at = raw.begins_at;
let width = raw.width;
let height = raw.height;
res.states = raw
.states
.into_iter()
.enumerate()
.map(|(i, b)| de_board(b, begins_at + i as isize, index, width, height))
.collect();
res
}
| true |
df05578e32242c25d9e7d2077794fc3a2da03bce
|
Rust
|
0000marcell/LearnRust
|
/RH/aoc1/src/main.rs
|
UTF-8
| 1,188 | 3.90625 | 4 |
[] |
no_license
|
fn main() {
let instruction: Vec<String> = std::env::args().collect();
let instruction: &String = &instruction[1];
println!("{}", santa(instruction));
}
fn santa(instruction: &String) -> i32 {
// if '(' up else if ')' down
let mut floor: i32 = 0;
for paren in instruction.chars() {
println!("{}", paren);
match paren {
'(' => floor += 1,
')' => floor -= 1,
_ => panic!(),
}
}
floor
}
// #[cfg(test)]
mod test {
use super::santa;
#[test]
fn example() {
assert!(santa(&"(())".to_string()) == 0);
assert!(santa(&"()()".to_string()) == 0);
assert!(santa(&"(((".to_string()) == 3);
assert!(santa(&"(()(()(".to_string()) == 3);
assert!(santa(&"))(((((".to_string()) == 3);
assert!(santa(&"())".to_string()) == -1);
assert!(santa(&"))(".to_string()) == -1);
assert!(santa(&")))".to_string()) == -3);
assert!(santa(&")())())".to_string()) == -3);
}
#[test]
fn a() {
assert!(santa(&"".to_string()) == 0);
}
#[test]
#[should_panic]
fn b() {
santa(&"{}".to_string());
}
}
| true |
6a343d704b724f4e3b3d2632e8240d84080c4f8f
|
Rust
|
Godofh3ell/el_monitorro-1
|
/src/db.rs
|
UTF-8
| 2,024 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
use chrono::prelude::*;
use chrono::{DateTime, Utc};
use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use dotenv::dotenv;
use once_cell::sync::OnceCell;
use std::env;
use tokio::sync::Semaphore;
use tokio::sync::SemaphorePermit;
pub mod feed_items;
pub mod feeds;
pub mod telegram;
static POOL: OnceCell<Pool<ConnectionManager<PgConnection>>> = OnceCell::new();
static SEMAPHORE: OnceCell<Semaphore> = OnceCell::new();
static POOL_NUMBER: OnceCell<usize> = OnceCell::new();
pub struct SemaphoredDbConnection<'a> {
_semaphore_permit: SemaphorePermit<'a>,
pub connection: PooledConnection<ConnectionManager<PgConnection>>,
}
pub async fn get_semaphored_connection<'a>() -> SemaphoredDbConnection<'a> {
let _semaphore_permit = semaphore().acquire().await.unwrap();
let connection = establish_connection();
SemaphoredDbConnection {
_semaphore_permit,
connection,
}
}
pub fn current_time() -> DateTime<Utc> {
Utc::now().round_subsecs(0)
}
pub fn establish_connection() -> PooledConnection<ConnectionManager<PgConnection>> {
pool().get().unwrap()
}
pub fn semaphore() -> &'static Semaphore {
SEMAPHORE.get_or_init(|| Semaphore::new(*pool_connection_number()))
}
pub fn pool_connection_number() -> &'static usize {
POOL_NUMBER.get_or_init(|| {
dotenv().ok();
let database_pool_size_str =
env::var("DATABASE_POOL_SIZE").unwrap_or_else(|_| "10".to_string());
let database_pool_size: usize = database_pool_size_str.parse().unwrap();
database_pool_size
})
}
fn pool() -> &'static Pool<ConnectionManager<PgConnection>> {
POOL.get_or_init(|| {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let manager = ConnectionManager::<PgConnection>::new(database_url);
Pool::builder()
.max_size(*pool_connection_number() as u32)
.build(manager)
.unwrap()
})
}
| true |
916510d952a46ad8df39dc2a78aee51d1daedaac
|
Rust
|
potatosalad/leetcode
|
/src/n1122_relative_sort_array.rs
|
UTF-8
| 1,815 | 3.625 | 4 |
[
"Apache-2.0"
] |
permissive
|
/**
* [1122] Relative Sort Array
*
* Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
* Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order.
*
* Example 1:
* Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
* Output: [2,2,2,1,4,3,3,9,6,7,19]
*
* Constraints:
*
* arr1.length, arr2.length <= 1000
* 0 <= arr1[i], arr2[i] <= 1000
* Each arr2[i] is distinct.
* Each arr2[i] is in arr1.
*
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
use std::collections::HashSet;
impl Solution {
pub fn relative_sort_array(arr1: Vec<i32>, arr2: Vec<i32>) -> Vec<i32> {
let set: HashSet<i32> = arr2.iter().copied().collect();
let mut histogram: HashMap<i32, usize> = HashMap::new();
let mut tail: Vec<i32> = Vec::new();
for n in arr1 {
if set.contains(&n) {
*(histogram.entry(n).or_insert(0)) += 1;
} else {
tail.push(n);
}
}
let mut head: Vec<i32> = Vec::new();
for n in arr2 {
let x: usize = histogram.get(&n).copied().unwrap();
head.append(&mut vec![n; x]);
}
tail.sort_unstable();
head.append(&mut tail);
head
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1122() {
assert_eq!(
vec![2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19],
Solution::relative_sort_array(
vec![2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19],
vec![2, 1, 4, 3, 9, 6]
)
);
}
}
| true |
22e8a01c9a2474f92601c744aaa918083d913c1b
|
Rust
|
TerminalStudio/nativeshell
|
/nativeshell/src/shell/platform/win32/window_base.rs
|
UTF-8
| 18,540 | 2.53125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use std::{
cell::RefCell,
rc::{Rc, Weak},
};
use crate::{
shell::{
api_model::{
WindowFrame, WindowGeometry, WindowGeometryFlags, WindowGeometryRequest, WindowStyle,
},
IPoint, IRect, ISize, Point, Rect, Size,
},
util::OkLog,
};
use super::{
all_bindings::*,
display::Displays,
error::PlatformResult,
flutter_sys::{FlutterDesktopGetDpiForHWND, FlutterDesktopGetDpiForMonitor},
util::{clamp, BoolResultExt, HRESULTExt, GET_X_LPARAM, GET_Y_LPARAM},
};
pub struct WindowBaseState {
hwnd: HWND,
min_frame_size: RefCell<Size>,
max_frame_size: RefCell<Size>,
min_content_size: RefCell<Size>,
max_content_size: RefCell<Size>,
delegate: Weak<dyn WindowDelegate>,
style: RefCell<WindowStyle>,
}
const LARGE_SIZE: f64 = 64.0 * 1024.0;
impl WindowBaseState {
pub fn new(hwnd: HWND, delegate: Weak<dyn WindowDelegate>) -> Self {
Self {
hwnd,
delegate,
min_frame_size: RefCell::new(Size::wh(0.0, 0.0)),
max_frame_size: RefCell::new(Size::wh(LARGE_SIZE, LARGE_SIZE)),
min_content_size: RefCell::new(Size::wh(0.0, 0.0)),
max_content_size: RefCell::new(Size::wh(LARGE_SIZE, LARGE_SIZE)),
style: Default::default(),
}
}
pub fn hide(&self) -> PlatformResult<()> {
unsafe { ShowWindow(self.hwnd, SW_HIDE).as_platform_result() }
}
pub fn show<F>(&self, callback: F) -> PlatformResult<()>
where
F: FnOnce() + 'static,
{
unsafe {
ShowWindow(self.hwnd, SW_SHOW); // false is not an error
}
callback();
Ok(())
}
pub fn set_geometry(
&self,
geometry: WindowGeometryRequest,
) -> PlatformResult<WindowGeometryFlags> {
let geometry = geometry.filtered_by_preference();
let mut res = WindowGeometryFlags {
..Default::default()
};
if geometry.content_origin.is_some()
|| geometry.content_size.is_some()
|| geometry.frame_origin.is_some()
|| geometry.frame_size.is_some()
{
self.set_bounds_geometry(&geometry, &mut res)?;
// There's no set_content_rect in winapi, so this is best effort implementation
// that tries to deduce future content rect from current content rect and frame rect
// in case it's wrong (i.e. display with different DPI or frame size change after reposition)
// it will retry once again
if res.content_origin || res.content_size {
let content_rect = self.content_rect_for_frame_rect(&self.get_frame_rect()?)?;
if (res.content_origin
&& content_rect.origin() != *geometry.content_origin.as_ref().unwrap())
|| (res.content_size
&& content_rect.size() != *geometry.content_size.as_ref().unwrap())
{
// retry
self.set_bounds_geometry(&geometry, &mut res)?;
}
}
}
if let Some(size) = geometry.min_frame_size {
self.min_frame_size.replace(size);
res.min_frame_size = true;
}
if let Some(size) = geometry.max_frame_size {
self.max_frame_size.replace(size);
res.max_frame_size = true;
}
if let Some(size) = geometry.min_content_size {
self.min_content_size.replace(size);
res.min_content_size = true;
}
if let Some(size) = geometry.max_content_size {
self.max_content_size.replace(size);
res.max_content_size = true;
}
Ok(res)
}
fn set_bounds_geometry(
&self,
geometry: &WindowGeometry,
flags: &mut WindowGeometryFlags,
) -> PlatformResult<()> {
let current_frame_rect = self.get_frame_rect()?;
let current_content_rect = self.content_rect_for_frame_rect(¤t_frame_rect)?;
let content_offset = current_content_rect.to_local(¤t_frame_rect.origin());
let content_size_delta = current_frame_rect.size() - current_content_rect.size();
let mut origin: Option<Point> = None;
let mut size: Option<Size> = None;
if let Some(frame_origin) = &geometry.frame_origin {
origin.replace(frame_origin.clone());
flags.frame_origin = true;
}
if let Some(frame_size) = &geometry.frame_size {
size.replace(frame_size.clone());
flags.frame_size = true;
}
if let Some(content_origin) = &geometry.content_origin {
origin.replace(content_origin.translated(&content_offset));
flags.content_origin = true;
}
if let Some(content_size) = &geometry.content_size {
size.replace(content_size + &content_size_delta);
flags.content_size = true;
}
let physical = IRect::origin_size(
&self.to_physical(origin.as_ref().unwrap_or(&Point::xy(0.0, 0.0))),
&size
.as_ref()
.unwrap_or(&Size::wh(0.0, 0.0))
.scaled(self.get_scaling_factor())
.into(),
);
let mut flags = SWP_NOZORDER | SWP_NOACTIVATE;
if origin.is_none() {
flags |= SWP_NOMOVE;
}
if size.is_none() {
flags |= SWP_NOSIZE;
}
unsafe {
SetWindowPos(
self.hwnd,
HWND(0),
physical.x,
physical.y,
physical.width,
physical.height,
flags,
)
.as_platform_result()
}
}
pub fn get_geometry(&self) -> PlatformResult<WindowGeometry> {
let frame_rect = self.get_frame_rect()?;
let content_rect = self.content_rect_for_frame_rect(&frame_rect)?;
Ok(WindowGeometry {
frame_origin: Some(frame_rect.origin()),
frame_size: Some(frame_rect.size()),
content_origin: Some(content_rect.origin()),
content_size: Some(content_rect.size()),
min_frame_size: Some(self.min_frame_size.borrow().clone()),
max_frame_size: Some(self.max_frame_size.borrow().clone()),
min_content_size: Some(self.min_content_size.borrow().clone()),
max_content_size: Some(self.max_content_size.borrow().clone()),
})
}
pub fn supported_geometry(&self) -> PlatformResult<WindowGeometryFlags> {
Ok(WindowGeometryFlags {
frame_origin: true,
frame_size: true,
content_origin: true,
content_size: true,
min_frame_size: true,
max_frame_size: true,
min_content_size: true,
max_content_size: true,
})
}
fn get_frame_rect(&self) -> PlatformResult<Rect> {
let mut rect: RECT = Default::default();
unsafe {
GetWindowRect(self.hwnd, &mut rect as *mut _).as_platform_result()?;
}
let size: Size = ISize::wh(rect.right - rect.left, rect.bottom - rect.top).into();
Ok(Rect::origin_size(
&self.to_logical(&IPoint::xy(rect.left, rect.top)),
&size.scaled(1.0 / self.get_scaling_factor()),
))
}
fn content_rect_for_frame_rect(&self, frame_rect: &Rect) -> PlatformResult<Rect> {
let content_rect = IRect::origin_size(
&self.to_physical(&frame_rect.top_left()),
&frame_rect.size().scaled(self.get_scaling_factor()).into(),
);
let rect = RECT {
left: content_rect.x,
top: content_rect.y,
right: content_rect.x2(),
bottom: content_rect.y2(),
};
unsafe {
SendMessageW(
self.hwnd,
WM_NCCALCSIZE as u32,
WPARAM(0),
LPARAM(&rect as *const _ as isize),
);
}
let size: Size = ISize::wh(rect.right - rect.left, rect.bottom - rect.top).into();
Ok(Rect::origin_size(
&self.to_logical(&IPoint::xy(rect.left, rect.top)),
&size.scaled(1.0 / self.get_scaling_factor()),
))
}
fn adjust_window_position(&self, position: &mut WINDOWPOS) -> PlatformResult<()> {
let scale = self.get_scaling_factor();
let frame_rect = self.get_frame_rect()?;
let content_rect = self.content_rect_for_frame_rect(&frame_rect)?;
let size_delta = frame_rect.size() - content_rect.size();
let min_content = &*self.min_content_size.borrow() + &size_delta;
let min_content: ISize = min_content.scaled(scale).into();
let min_frame = self.min_frame_size.borrow();
let min_frame: ISize = min_frame.scaled(scale).into();
let min_size = ISize::wh(
std::cmp::max(min_content.width, min_frame.width),
std::cmp::max(min_content.height, min_frame.height),
);
let max_content = &*self.max_content_size.borrow() + &size_delta;
let max_content: ISize = max_content.scaled(scale).into();
let max_frame = self.max_frame_size.borrow();
let max_frame: ISize = max_frame.scaled(scale).into();
let max_size = ISize::wh(
std::cmp::min(max_content.width, max_frame.width),
std::cmp::min(max_content.height, max_frame.height),
);
position.cx = clamp(position.cx, min_size.width, max_size.width);
position.cy = clamp(position.cy, min_size.height, max_size.height);
Ok(())
}
pub fn close(&self) -> PlatformResult<()> {
unsafe { DestroyWindow(self.hwnd).as_platform_result() }
}
pub fn local_to_global(&self, offset: &Point) -> IPoint {
let scaled: IPoint = offset.scaled(self.get_scaling_factor()).into();
self.local_to_global_physical(&scaled)
}
pub fn local_to_global_physical(&self, offset: &IPoint) -> IPoint {
let mut point = POINT {
x: offset.x,
y: offset.y,
};
unsafe {
ClientToScreen(self.hwnd, &mut point as *mut _);
}
IPoint::xy(point.x, point.y)
}
pub fn global_to_local(&self, offset: &IPoint) -> Point {
let local: Point = self.global_to_local_physical(&offset).into();
local.scaled(1.0 / self.get_scaling_factor())
}
pub fn global_to_local_physical(&self, offset: &IPoint) -> IPoint {
let mut point = POINT {
x: offset.x,
y: offset.y,
};
unsafe {
ScreenToClient(self.hwnd, &mut point as *mut _);
}
IPoint::xy(point.x, point.y)
}
fn to_physical(&self, offset: &Point) -> IPoint {
Displays::get_displays()
.convert_logical_to_physical(offset)
.unwrap_or_else(|| offset.clone().into())
}
fn to_logical(&self, offset: &IPoint) -> Point {
Displays::get_displays()
.convert_physical_to_logical(offset)
.unwrap_or_else(|| offset.clone().into())
}
pub fn is_rtl(&self) -> bool {
let style = WINDOW_EX_STYLE(unsafe { GetWindowLongW(self.hwnd, GWL_EXSTYLE) } as u32);
style & WS_EX_LAYOUTRTL == WS_EX_LAYOUTRTL
}
pub fn get_scaling_factor(&self) -> f64 {
unsafe { FlutterDesktopGetDpiForHWND(self.hwnd) as f64 / 96.0 }
}
#[allow(unused)]
fn get_scaling_factor_for_monitor(&self, monitor: isize) -> f64 {
unsafe { FlutterDesktopGetDpiForMonitor(monitor) as f64 / 96.0 }
}
fn delegate(&self) -> Rc<dyn WindowDelegate> {
// delegate owns us so unwrap is safe here
self.delegate.upgrade().unwrap()
}
unsafe fn set_close_enabled(&self, enabled: bool) {
let menu = GetSystemMenu(self.hwnd, false);
if enabled {
EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);
} else {
EnableMenuItem(
menu,
SC_CLOSE as u32,
MF_BYCOMMAND | MF_DISABLED | MF_GRAYED,
);
}
}
pub fn update_dwm_frame(&self) -> PlatformResult<()> {
let margin = match self.style.borrow().frame {
WindowFrame::Regular => 0, // already has shadow
WindowFrame::NoTitle => 1, // neede for window shadow
WindowFrame::NoFrame => 0, // neede for transparency
};
let margins = MARGINS {
cxLeftWidth: 0,
cxRightWidth: 0,
cyTopHeight: margin,
cyBottomHeight: 0,
};
unsafe {
DwmExtendFrameIntoClientArea(self.hwnd, &margins as *const _).as_platform_result()
}
}
pub fn set_title(&self, title: String) -> PlatformResult<()> {
unsafe {
SetWindowTextW(self.hwnd, title);
}
Ok(())
}
pub fn set_style(&self, style: WindowStyle) -> PlatformResult<()> {
*self.style.borrow_mut() = style.clone();
unsafe {
let mut s = WINDOW_STYLE(GetWindowLongW(self.hwnd, GWL_STYLE) as u32);
s &= WINDOW_STYLE(!(WS_OVERLAPPEDWINDOW | WS_DLGFRAME).0);
if style.frame == WindowFrame::Regular {
s |= WS_CAPTION;
if style.can_resize {
s |= WS_THICKFRAME;
}
}
if style.frame == WindowFrame::NoTitle {
s |= WS_CAPTION;
if style.can_resize {
s |= WS_THICKFRAME;
} else {
s |= WS_BORDER;
}
}
if style.frame == WindowFrame::NoFrame {
s |= WS_POPUP
}
s |= WS_SYSMENU;
self.set_close_enabled(style.can_close);
if style.can_maximize && style.can_resize {
s |= WS_MAXIMIZEBOX;
}
if style.can_minimize {
s |= WS_MINIMIZEBOX;
}
SetWindowLongW(self.hwnd, GWL_STYLE, s.0 as i32);
SetWindowPos(
self.hwnd,
HWND(0),
0,
0,
0,
0,
SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER,
)
.as_platform_result()?;
self.update_dwm_frame()?;
}
Ok(())
}
pub fn perform_window_drag(&self) -> PlatformResult<()> {
unsafe {
println!("Perform window drag!");
ReleaseCapture();
SendMessageW(
self.hwnd,
WM_NCLBUTTONDOWN as u32,
WPARAM(HTCAPTION as usize),
LPARAM(0),
);
}
Ok(())
}
pub fn has_redirection_surface(&self) -> bool {
let style = WINDOW_EX_STYLE(unsafe { GetWindowLongW(self.hwnd, GWL_EXSTYLE) } as u32);
(style & WS_EX_NOREDIRECTIONBITMAP).0 == 0
}
pub fn remove_border(&self) -> bool {
self.style.borrow().frame == WindowFrame::NoTitle
}
fn do_hit_test(&self, x: i32, y: i32) -> u32 {
let mut win_rect = RECT::default();
unsafe {
GetWindowRect(self.hwnd, &mut win_rect as *mut _);
}
let border_width = (7.0 * self.get_scaling_factor()) as i32;
if x < win_rect.left + border_width && y < win_rect.top + border_width {
HTTOPLEFT
} else if x > win_rect.right - border_width && y < win_rect.top + border_width {
HTTOPRIGHT
} else if y < win_rect.top + border_width {
HTTOP
} else if x < win_rect.left + border_width && y > win_rect.bottom - border_width {
HTBOTTOMLEFT
} else if x > win_rect.right - border_width && y > win_rect.bottom - border_width {
HTBOTTOMRIGHT
} else if y > win_rect.bottom - border_width {
HTBOTTOM
} else if x < win_rect.left + border_width {
HTLEFT
} else if x > win_rect.right - border_width {
HTRIGHT
} else {
HTCLIENT
}
}
pub fn handle_message(
&self,
_h_wnd: HWND,
msg: u32,
_w_param: WPARAM,
l_param: LPARAM,
) -> Option<LRESULT> {
match msg {
WM_CLOSE => {
self.delegate().should_close();
Some(LRESULT(0))
}
WM_DESTROY => {
self.delegate().will_close();
None
}
WM_DISPLAYCHANGE => {
Displays::displays_changed();
self.delegate().displays_changed();
None
}
WM_WINDOWPOSCHANGING => {
let position = unsafe { &mut *(l_param.0 as *mut WINDOWPOS) };
self.adjust_window_position(position).ok_log();
None
}
WM_DWMCOMPOSITIONCHANGED => {
self.update_dwm_frame().ok_log();
None
}
WM_NCCALCSIZE => {
if self.remove_border() {
Some(LRESULT(1))
} else {
None
}
}
WM_NCHITTEST => {
if self.remove_border() {
let res = self.do_hit_test(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param));
Some(LRESULT(res as i32))
} else {
None
}
}
_ => None,
}
}
pub fn handle_child_message(
&self,
_h_wnd: HWND,
msg: u32,
_w_param: WPARAM,
l_param: LPARAM,
) -> Option<LRESULT> {
match msg {
WM_NCHITTEST => {
if self.remove_border() {
let res = self.do_hit_test(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param));
if res != HTCLIENT {
Some(LRESULT(HTTRANSPARENT))
} else {
Some(LRESULT(res as i32))
}
} else {
None
}
}
_ => None,
}
}
}
pub trait WindowDelegate {
fn should_close(&self);
fn will_close(&self);
fn displays_changed(&self);
}
| true |
8e91db882281095b6715f97f1a64202981b013ce
|
Rust
|
DrewKestell/ForayRust
|
/src/game_timer.rs
|
UTF-8
| 3,022 | 2.625 | 3 |
[] |
no_license
|
use winapi::um::profileapi::QueryPerformanceCounter;
use winapi::shared::ntdef::LARGE_INTEGER;
use std::mem::zeroed;
pub struct GameTimer {
seconds_per_count: f64,
delta_time: f64,
base_time: i64,
paused_time: i64,
stop_time: i64,
previous_time: i64,
current_time: i64,
stopped: bool
}
impl GameTimer {
pub fn new() -> GameTimer {
unsafe {
let mut counts_per_second: LARGE_INTEGER = zeroed();
QueryPerformanceCounter(&mut counts_per_second);
let seconds_per_count = 1.0 / *counts_per_second.QuadPart() as f64;
GameTimer {
seconds_per_count: seconds_per_count,
delta_time: -1.0,
base_time: 0,
paused_time: 0,
stop_time: 0,
previous_time: 0,
current_time: 0,
stopped: false
}
}
}
pub fn tick(&mut self) {
if self.stopped {
self.delta_time = 0.0;
return;
}
unsafe {
let mut current_time: LARGE_INTEGER = zeroed();
QueryPerformanceCounter(&mut current_time);
self.current_time = *current_time.QuadPart();
}
self.delta_time = (self.current_time - self.previous_time) as f64 * self.seconds_per_count;
self.previous_time = self.current_time;
if self.delta_time < 0.0 {
self.delta_time = 0.0;
}
}
pub fn reset(&mut self) {
unsafe {
let mut current_time: LARGE_INTEGER = zeroed();
QueryPerformanceCounter(&mut current_time);
self.base_time = *current_time.QuadPart();
self.previous_time = *current_time.QuadPart();
self.stop_time = *current_time.QuadPart();
self.stopped = false;
}
}
pub fn stop(&mut self) {
if !self.stopped {
unsafe {
let mut current_time: LARGE_INTEGER = zeroed();
QueryPerformanceCounter(&mut current_time);
self.stop_time = *current_time.QuadPart();
self.stopped = true;
}
}
}
pub fn start(&mut self) {
if self.stopped {
unsafe {
let mut start_time: LARGE_INTEGER = zeroed();
QueryPerformanceCounter(&mut start_time);
self.paused_time += *start_time.QuadPart() - self.stop_time;
self.previous_time = *start_time.QuadPart();
self.stop_time = 0;
self.stopped = false;
}
}
}
pub fn total_time(&self) -> f64 {
if self.stopped {
((self.stop_time - self.paused_time) - self.base_time) as f64 * self.seconds_per_count
}
else {
((self.current_time - self.paused_time) - self.base_time) as f64 * self.seconds_per_count
}
}
pub fn delta_time(&self) -> f64 {
self.delta_time
}
}
| true |
c3337f1f1473accd16e0a194ec276ef69b78cc85
|
Rust
|
gloriousfutureio/hermitdb
|
/src/memory_log.rs
|
UTF-8
| 2,578 | 2.796875 | 3 |
[] |
no_license
|
use std::collections::BTreeMap;
use std::fmt::Debug;
use crdts::{CmRDT, Actor};
use log::{TaggedOp, LogReplicable};
use error::Result;
#[derive(Debug, Clone)]
pub struct Log<A: Actor, C: Debug + CmRDT> {
actor: A,
logs: BTreeMap<A, (u64, Vec<C::Op>)>
}
#[derive(Debug, Clone)]
pub struct Op<A: Actor, C: Debug + CmRDT> {
actor: A,
index: u64,
op: C::Op
}
impl<A: Actor, C: Debug + CmRDT> TaggedOp<C> for Op<A, C> {
type ID = (A, u64);
fn id(&self) -> Self::ID {
(self.actor.clone(), self.index)
}
fn op(&self) -> &C::Op {
&self.op
}
}
impl<A: Actor, C: Debug + CmRDT> LogReplicable<A, C> for Log<A, C> {
type Op = Op<A, C>;
fn next(&self) -> Result<Option<Self::Op>> {
let largest_lag = self.logs.iter()
.max_by_key(|(_, (index, log))| (log.len() as u64) - *index);
if let Some((actor, (index, log))) = largest_lag {
if *index >= log.len() as u64 {
Ok(None)
} else {
Ok(Some(Op {
actor: actor.clone(),
index: *index,
op: log[*index as usize].clone()
}))
}
} else {
Ok(None)
}
}
fn ack(&mut self, op: &Self::Op) -> Result<()> {
// We can ack ops that are not present in the log
let (actor, index) = op.id();
let log = self.logs.entry(actor)
.or_insert_with(|| (0, Vec::new()));
log.0 = index + 1;
Ok(())
}
fn commit(&mut self, op: C::Op) -> Result<Self::Op> {
let log = self.logs.entry(self.actor.clone())
.or_insert_with(|| (0, Vec::new()));
log.1.push(op.clone());
Ok(Op {
actor: self.actor.clone(),
index: log.0,
op: op
})
}
fn pull(&mut self, other: &Self) -> Result<()> {
for (actor, (_, log)) in other.logs.iter() {
let entry = self.logs.entry(actor.clone())
.or_insert_with(|| (0, vec![]));
if log.len() > entry.1.len() {
for i in (entry.1.len())..log.len() {
entry.1.push(log[i as usize].clone());
}
}
}
Ok(())
}
fn push(&self, other: &mut Self) -> Result<()> {
other.pull(self)
}
}
impl<A: Actor, C: Debug + CmRDT> Log<A, C> {
pub fn new(actor: A) -> Self {
Log {
actor: actor,
logs: BTreeMap::new()
}
}
}
| true |
3b6a8bd239de8e214574da7f3d0eb3faedfd1d68
|
Rust
|
AlberErre/rust-experiments
|
/fizz-buzz/src/main.rs
|
UTF-8
| 573 | 4.15625 | 4 |
[] |
no_license
|
fn main() {
println!("Hello, Fizz Buzz!");
const NUMBER: i32 = 35;
let fizz_buzz_result = fizz_buzz(NUMBER);
println!("Fizz Buzz for number {} is: {:?}", NUMBER, fizz_buzz_result);
}
fn fizz_buzz(number: i32) -> Vec<String> {
//NOTE: we start at 1 to avoid handling another case with 0
let numbers = 1..=number;
numbers
.map(|n| match n {
n if (n % 3 == 0 && n % 5 == 0) => String::from("FizzBuzz"),
n if n % 3 == 0 => String::from("Fizz"),
n if n % 5 == 0 => String::from("Buzz"),
_ => n.to_string(),
})
.collect()
}
| true |
00813770f2c8333ff4b3a5282971ad36f1644f50
|
Rust
|
Dongitestil/PL_2_Rust
|
/server/src/main.rs
|
UTF-8
| 1,569 | 2.8125 | 3 |
[] |
no_license
|
use std::thread;
use std::net::{TcpListener, TcpStream, Shutdown};
use std::io::{Read, Write};
use std::str::from_utf8;
mod protector;
use protector::*;
fn handle_client(mut stream: TcpStream) {
let mut hash = [0 as u8; 5];
let mut key = [0 as u8; 10];
let mut mes = [0 as u8;50];
while match stream.read(&mut hash) {
Ok(_) => {
stream.read(&mut key);
stream.read(&mut mes);
let text1 = from_utf8(&hash).unwrap();
let text2 = from_utf8(&key).unwrap();
let new_key = next_session_key(&text1,&text2);
let result = new_key.clone().into_bytes();
//отправка данных
stream.write(&result).unwrap();
stream.write(&mes).unwrap();
true
},
Err(_) => {
println!("Ошибка при подключении к {}", stream.peer_addr().unwrap());
stream.shutdown(Shutdown::Both).unwrap();
false
}
} {}
}
fn main() {
let listener = TcpListener::bind("0.0.0.0:3333").unwrap();
println!("Сервер запустился...");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
println!("Новое подключение: {}", stream.peer_addr().unwrap());
thread::spawn(move|| {
handle_client(stream)
});
}
Err(e) => {
println!("Ошибка: {}", e);
}
}
}
drop(listener);
}
| true |
ce1070567ee74acc90f0f31ff337228e172fe016
|
Rust
|
evelynmitchell/stateright.github.io
|
/rs-src/getting-started/src/main.rs
|
UTF-8
| 3,202 | 2.53125 | 3 |
[] |
no_license
|
/* ANCHOR: all */
use stateright::actor::{*, register::*};
use std::borrow::Cow; // COW == clone-on-write
use std::net::{SocketAddrV4, Ipv4Addr};
// ANCHOR: actor
type RequestId = u64;
#[derive(Clone)]
struct ServerActor;
impl Actor for ServerActor {
type Msg = RegisterMsg<RequestId, char, ()>;
type State = char;
fn on_start(&self, _id: Id, _o: &mut Out<Self>) -> Self::State {
'?' // default value for the register
}
fn on_msg(&self, _id: Id, state: &mut Cow<Self::State>,
src: Id, msg: Self::Msg, o: &mut Out<Self>) {
match msg {
RegisterMsg::Put(req_id, value) => {
*state.to_mut() = value;
o.send(src, RegisterMsg::PutOk(req_id));
}
RegisterMsg::Get(req_id) => {
o.send(src, RegisterMsg::GetOk(req_id, **state));
}
_ => {}
}
}
}
// ANCHOR_END: actor
#[cfg(test)]
mod test {
use super::*;
use stateright::{*, semantics::*, semantics::register::*};
use ActorModelAction::Deliver;
use RegisterMsg::{Get, GetOk, Put, PutOk};
// ANCHOR: test
#[test]
fn is_unfortunately_not_linearizable() {
let checker = ActorModel::new(
(),
LinearizabilityTester::new(Register('?'))
)
.actor(RegisterActor::Server(ServerActor))
.actor(RegisterActor::Client { put_count: 2, server_count: 1 })
.property(Expectation::Always, "linearizable", |_, state| {
state.history.serialized_history().is_some()
})
.property(Expectation::Sometimes, "get succeeds", |_, state| {
state.network.iter().any(|e| matches!(e.msg, RegisterMsg::GetOk(_, _)))
})
.property(Expectation::Sometimes, "put succeeds", |_, state| {
state.network.iter().any(|e| matches!(e.msg, RegisterMsg::PutOk(_)))
})
.record_msg_in(RegisterMsg::record_returns)
.record_msg_out(RegisterMsg::record_invocations)
.checker().spawn_dfs().join();
//checker.assert_properties(); // TRY IT: Uncomment this line, and the test will fail.
checker.assert_discovery("linearizable", vec![
Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(1, 'A') },
Deliver { src: Id::from(0), dst: Id::from(1), msg: PutOk(1) },
Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(2, 'Z') },
Deliver { src: Id::from(0), dst: Id::from(1), msg: PutOk(2) },
Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(1, 'A') },
Deliver { src: Id::from(1), dst: Id::from(0), msg: Get(3) },
Deliver { src: Id::from(0), dst: Id::from(1), msg: GetOk(3, 'A') },
]);
}
// ANCHOR_END: test
}
// ANCHOR: main
fn main() {
env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));
spawn(
serde_json::to_vec,
|bytes| serde_json::from_slice(bytes),
vec![
(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 3000), ServerActor)
]).unwrap();
}
// ANCHOR_END: main
/* ANCHOR_END: all */
| true |
539a574f3851eefc209d9506b0cbe9999a5ed8f8
|
Rust
|
unpluggedcoder/memory-profiler
|
/integration-tests/test-programs/return-opt-u128.rs
|
UTF-8
| 401 | 2.640625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
const CONSTANT: u128 = 0xaaaaaaaaaaaaaaaa5555555555555555;
extern {
fn malloc( size: usize ) -> *const u8;
fn abort() -> !;
}
#[inline(never)]
#[no_mangle]
fn func_1() -> Option< u128 > {
unsafe { malloc( 123456 ); }
Some( CONSTANT )
}
#[inline(never)]
#[no_mangle]
fn func_2() {
if func_1() != Some( CONSTANT ) {
unsafe { abort(); }
}
}
fn main() {
func_2();
}
| true |
d24d4db001063f5d1473e134935fe0021b6b5b70
|
Rust
|
kavirajk/pgroup
|
/src/lib.rs
|
UTF-8
| 2,373 | 2.734375 | 3 |
[] |
no_license
|
use bincode;
use crossbeam_channel::Receiver;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
#[derive(Debug)]
struct Group {
me: Node,
peers: HashMap<String, Node>,
// ack for specific ping's seq_no.
ack_handlers: HashMap<u32, Receiver<Packet>>,
}
impl Group {
fn members(&self) -> Vec<Node> {
unimplemented!()
}
fn new(me: Node, seed_peers: &[Node]) -> Self {
unimplemented!()
}
fn probe_peers(&self) {
unimplemented!()
}
fn probe(&self, node: &Node) {
unimplemented!()
}
fn packet_listener(&self) -> Result<(), String> {
let mut buf: Vec<u8> = vec![0; 1024];
self.me.sock.recv(&mut buf).unwrap();
let pkt = decode_packet(&buf).unwrap();
match pkt {
Packet::Ping { from, seq_no } => if self.ack_handlers.contains_key(&seq_no) {},
Packet::Ack { from, seq_no } => {}
Packet::PingReq => {}
Packet::IndirectAck => {}
_ => {}
}
Ok(())
}
fn send<T: ToSocketAddrs>(sock: &UdpSocket, msg: Vec<u8>, to: T) -> std::io::Result<usize> {
sock.send_to(&msg, to)
}
fn encode_and_send() {}
}
#[derive(Debug)]
struct Node {
name: String,
seq_no: u64,
incar_no: u64,
addr: SocketAddr,
sock: UdpSocket,
state: NodeState,
}
impl Node {
fn next_seq_no(&self) {
unimplemented!()
}
fn next_incar_no(&self) {
unimplemented!()
}
}
#[derive(Debug)]
enum NodeState {
Alive,
Dead,
Suspect,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
enum Packet {
Ping { from: String, seq_no: u32 },
Ack { from: String, seq_no: u32 },
PingReq,
IndirectAck,
Alive,
Joined,
Left,
Failed,
}
fn encode_packet(pkt: &Packet) -> Result<Vec<u8>, String> {
let buf = bincode::serialize(pkt).unwrap();
Ok(buf)
}
fn decode_packet(buf: &[u8]) -> Result<Packet, String> {
let pkt: Packet = bincode::deserialize(buf).unwrap();
Ok(pkt)
}
#[test]
fn test_encode_decode() {
let before = Packet::Ping {
from: "me".to_owned(),
seq_no: 1234,
};
let buf = encode_packet(&before).unwrap();
let after = decode_packet(&buf).unwrap();
assert_eq!(before, after);
}
| true |
f9a2594077419e7a188555f362be2af0e36c6b1a
|
Rust
|
quinnnned/rust-mancala
|
/src/main.rs
|
UTF-8
| 9,671 | 3.09375 | 3 |
[] |
no_license
|
use std::fmt;
#[derive(Copy, Clone, PartialEq, Debug)]
struct Player {
pits: [i8; 6],
score: i8,
}
impl Player {
fn get_moves(&self) -> Vec<usize> {
(0..6)
.into_iter()
.filter(|&i| self.pits[i] != 0)
.collect::<Vec<_>>()
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
enum GameMode {
WhiteTurn,
BlackTurn,
GameOver,
}
#[derive(Copy, Clone, PartialEq, Debug)]
struct GameState {
mode: GameMode,
white: Player,
black: Player,
}
struct GameSkeuomorph {
b: [i8; 8],
w: [i8; 8],
}
impl fmt::Display for GameState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
" |{: >2}|{: >2}|{: >2}|{: >2}|{: >2}|{: >2}|
{: >2} |--{}--| {}
|{: >2}|{: >2}|{: >2}|{: >2}|{: >2}|{: >2}|
",
// Top Row: Black Pits (reverse order)
self.black.pits[5],
self.black.pits[4],
self.black.pits[3],
self.black.pits[2],
self.black.pits[1],
self.black.pits[0],
// Middle Row: Score and Status
self.black.score,
match self.mode {
GameMode::WhiteTurn => "WHITE TO MOVE",
GameMode::BlackTurn => "BLACK TO MOVE",
GameMode::GameOver => "--GAME OVER--",
},
self.white.score,
// Bottom Row: White Pits
self.white.pits[0],
self.white.pits[1],
self.white.pits[2],
self.white.pits[3],
self.white.pits[4],
self.white.pits[5],
)
}
}
impl GameState {
fn get_valid_moves(&self) -> Vec<usize> {
match self.mode {
GameMode::WhiteTurn => self.white.get_moves(),
GameMode::BlackTurn => self.black.get_moves(),
GameMode::GameOver => vec![],
}
}
fn from(s: GameSkeuomorph) -> GameState {
GameState {
mode: if s.b[7] == 0 {
if s.w[0] == 0 {
GameMode::GameOver
} else {
GameMode::WhiteTurn
}
} else {
GameMode::BlackTurn
},
white: Player {
pits: [s.w[1], s.w[2], s.w[3], s.w[4], s.w[5], s.w[6]],
score: s.w[7],
},
black: Player {
pits: [s.b[6], s.b[5], s.b[4], s.b[3], s.b[2], s.b[1]],
score: s.b[0],
},
}
}
fn new() -> GameState {
GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 4, 4, 4, 0],
w: [1, 4, 4, 4, 4, 4, 4, 0],
})
}
fn get_next_state(&self, pit_index: usize) -> GameState {
// Ignore moves after Game Over
if self.mode == GameMode::GameOver {
return GameState { ..*self };
}
// Set up active/inactive semantics
let (mut active_player, mut inactive_player) = match self.mode {
GameMode::WhiteTurn => (self.white, self.black),
_ => (self.black, self.white),
};
let mut last_stone_was_score = false;
let mut stones_to_move = active_player.pits[pit_index];
let mut pit_pointer = pit_index;
const MAX_PIT_INDEX: usize = 5;
active_player.pits[pit_pointer] = 0;
pit_pointer += 1;
while stones_to_move > 0 {
// Active Pits
while stones_to_move > 0 && pit_pointer <= MAX_PIT_INDEX {
stones_to_move -= 1;
// Detect Steal
let is_last_stone = stones_to_move == 0;
let last_pit_is_empty = active_player.pits[pit_pointer] == 0;
if is_last_stone && last_pit_is_empty {
let opposite_pit = 5 - pit_pointer;
let stolen_stones = inactive_player.pits[opposite_pit];
inactive_player.pits[opposite_pit] = 0;
active_player.score += stolen_stones + 1;
} else {
active_player.pits[pit_pointer] += 1;
pit_pointer += 1;
}
}
// Active Scoring Pit
if stones_to_move > 0 {
stones_to_move -= 1;
let is_last_stone = stones_to_move == 0;
if is_last_stone {
last_stone_was_score = true;
}
active_player.score += 1;
pit_pointer = 0;
}
// Inactive Pits
while stones_to_move > 0 && pit_pointer <= MAX_PIT_INDEX {
stones_to_move -= 1;
inactive_player.pits[pit_pointer] += 1;
pit_pointer += 1;
}
pit_pointer = 0;
}
// Undo active/inactive semantics
let (white, black) = match self.mode {
GameMode::WhiteTurn => (active_player, inactive_player),
_ => (inactive_player, active_player),
};
let is_game_over = true
&& active_player.pits[0] == 0
&& active_player.pits[1] == 0
&& active_player.pits[2] == 0
&& active_player.pits[3] == 0
&& active_player.pits[4] == 0
&& active_player.pits[5] == 0;
let mode = if is_game_over {
GameMode::GameOver
} else {
if last_stone_was_score {
self.mode
} else {
if self.mode == GameMode::WhiteTurn {
GameMode::BlackTurn
} else {
GameMode::WhiteTurn
}
}
};
return GameState { mode, white, black };
}
}
#[test]
fn game_over_is_permanent() {
let game_over = GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 4, 4, 4, 0],
w: [0, 4, 4, 4, 4, 4, 4, 0],
});
assert_eq!(game_over.get_next_state(0), game_over);
}
#[test]
fn white_basic_move() {
assert_eq!(
GameState::new().get_next_state(0),
GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 4, 4, 4, 1],
w: [0, 0, 5, 5, 5, 5, 4, 0],
})
);
}
#[test]
fn black_basic_move() {
assert_eq!(
GameState::new().get_next_state(0).get_next_state(0),
GameState::from(GameSkeuomorph {
b: [0, 4, 5, 5, 5, 5, 0, 0],
w: [1, 0, 5, 5, 5, 5, 4, 0],
})
);
}
#[test]
fn white_overflow_move() {
assert_eq!(
GameState::new().get_next_state(5),
GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 5, 5, 5, 1],
w: [0, 4, 4, 4, 4, 4, 0, 1],
})
);
}
#[test]
fn black_overflow_move() {
assert_eq!(
GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 5, 5, 5, 1],
w: [0, 4, 4, 4, 4, 4, 0, 1],
}).get_next_state(5),
GameState::from(GameSkeuomorph {
b: [1, 0, 4, 4, 5, 5, 5, 0],
w: [1, 5, 5, 5, 4, 4, 0, 1],
})
);
}
#[test]
fn white_free_turn() {
assert_eq!(
GameState::new().get_next_state(2),
GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 4, 4, 4, 0],
w: [1, 4, 4, 0, 5, 5, 5, 1],
})
);
}
#[test]
fn black_free_turn() {
assert_eq!(
GameState::new().get_next_state(0).get_next_state(2),
GameState::from(GameSkeuomorph {
b: [1, 5, 5, 5, 0, 4, 4, 1],
w: [0, 0, 5, 5, 5, 5, 4, 0],
})
);
}
#[test]
fn white_long_wrap() {
assert_eq!(
GameState::from(GameSkeuomorph {
b: [0, 0, 0, 0, 0, 0, 0, 0],
w: [1, 0, 0, 0, 0, 0, 48, 0],
}).get_next_state(5),
GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 4, 4, 4, 1],
w: [0, 4, 4, 3, 3, 3, 3, 4],
})
);
}
#[test]
fn black_long_wrap() {
assert_eq!(
GameState::from(GameSkeuomorph {
b: [0, 48, 0, 0, 0, 0, 0, 1],
w: [0, 0, 0, 0, 0, 0, 0, 0],
}).get_next_state(5),
GameState::from(GameSkeuomorph {
b: [4, 3, 3, 3, 3, 4, 4, 0],
w: [1, 4, 4, 4, 4, 4, 4, 0],
})
);
}
#[test]
fn white_steal() {
assert_eq!(
GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 4, 4, 4, 0],
w: [1, 8, 4, 4, 4, 4, 0, 0],
}).get_next_state(1),
GameState::from(GameSkeuomorph {
b: [0, 4, 4, 4, 4, 4, 0, 1],
w: [0, 8, 0, 5, 5, 5, 0, 5],
})
);
}
#[test]
fn black_steal() {
assert_eq!(
GameState::from(GameSkeuomorph {
b: [0, 0, 4, 4, 4, 4, 8, 1],
w: [0, 4, 4, 4, 4, 4, 4, 0],
}).get_next_state(1),
GameState::from(GameSkeuomorph {
b: [5, 0, 5, 5, 5, 0, 8, 0],
w: [1, 0, 4, 4, 4, 4, 4, 0],
})
);
}
#[test]
fn game_over_if_white_empty() {
assert_eq!(
GameState::from(GameSkeuomorph {
b: [0, 8, 8, 8, 8, 8, 6, 0],
w: [1, 0, 0, 0, 0, 0, 2, 0],
}).get_next_state(5),
GameState::from(GameSkeuomorph {
b: [0, 8, 8, 8, 8, 8, 7, 0],
w: [0, 0, 0, 0, 0, 0, 0, 1],
})
);
}
#[test]
fn game_over_if_black_empty() {
assert_eq!(
GameState::from(GameSkeuomorph {
b: [0, 2, 0, 0, 0, 0, 0, 1],
w: [0, 6, 8, 8, 8, 8, 8, 0],
}).get_next_state(5),
GameState::from(GameSkeuomorph {
b: [1, 0, 0, 0, 0, 0, 0, 0],
w: [0, 7, 8, 8, 8, 8, 8, 0],
})
);
}
fn main() {}
| true |
ca8df953a610e9ef5696a063e7b52596cd83288f
|
Rust
|
blackjack/algorithms_pt1
|
/rust/week01_quickmerge/src/percolation.rs
|
UTF-8
| 3,263 | 3.3125 | 3 |
[] |
no_license
|
use std::fmt::{Display, Formatter, Error};
use quickmerge::QuickMerge;
#[allow(dead_code)]
pub struct Percolation {
x: usize,
y: usize,
pub last: usize,
data: QuickMerge,
}
impl Percolation {
pub fn new(x: usize, y: usize) -> Percolation {
let mut p = Percolation {
x: x,
y: y,
last: x * y + 1,
data: QuickMerge::new(x * y + 2),
};
for i in p.data.id.iter_mut() {
*i = x * y + 2;
}
p.data.id[0] = 0;
p.data.id[p.last] = p.last;
p
}
pub fn index(&self, row: usize, column: usize) -> usize {
if row == 0 {
return 0;
}
if row > self.y {
return self.last;
}
self.y * (row - 1) + column
}
pub fn open(&mut self, row: usize, column: usize) {
let index = self.index(row, column);
if !self.is_open(row, column) {
self.data.id[index] = index;
}
let neighbors =
[(row + 1, column), (row - 1, column), (row, column + 1), (row, column - 1)];
let x = self.x;
for &(nrow, ncol) in neighbors.iter()
.filter(|c| c.1 > 0 && c.1 <= x) {
if self.is_open(nrow, ncol) {
let neighbor = self.index(nrow, ncol);
self.data.union(index, neighbor);
}
}
}
pub fn is_open(&self, row: usize, column: usize) -> bool {
let index = self.index(row, column);
self.data.id[index] <= self.last
}
pub fn is_full(&mut self, row: usize, column: usize) -> bool {
let index = self.index(row, column);
self.data.connected(index, 0)
}
pub fn number_of_open_sites(&self) -> usize {
let max = self.last;
let id = &self.data.id[1..max];
id.iter().filter(|&&i| i < max).count()
}
pub fn percolates(&mut self) -> bool {
let row = self.y + 1;
self.is_full(row, 1)
}
}
impl Display for Percolation {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{}\n", self.data.id[0])?;
let print = |row, column| {
if self.is_open(row, column) {
let index = self.index(row, column);
self.data.id[index].to_string()
} else {
"X".to_string()
}
};
for row in 1..self.x + 1 {
for column in 1..self.y + 1 {
write!(f, "{}", print(row, column))?;
}
write!(f, "\n")?;
}
write!(f, "{}\n", print(self.y + 1, self.x))
}
}
#[test]
fn test_open() {
let mut p = Percolation::new(3, 3);
p.open(1, 3);
p.open(2, 2);
p.open(2, 3);
p.open(3, 3);
assert!(p.is_open(4, 3));
assert!(p.is_open(4, 1));
}
#[test]
fn test_count() {
let mut p = Percolation::new(3, 3);
p.open(1, 3);
p.open(2, 2);
p.open(2, 3);
p.open(3, 3);
assert_eq!(4, p.number_of_open_sites());
}
#[test]
fn test_percolates() {
let mut p = Percolation::new(3, 3);
p.open(1, 1);
p.open(2, 1);
p.open(2, 2);
p.open(2, 3);
assert!(!p.percolates());
p.open(3, 3);
assert!(p.percolates());
}
| true |
fe45abe02d8c82057cab67c3d57a52c0db4ac9a4
|
Rust
|
KaiseiYokoyama/iiif_awesome_sample_viewer
|
/src/iif_manifest.rs
|
UTF-8
| 1,711 | 2.75 | 3 |
[] |
no_license
|
#[derive(Deserialize, Debug, Serialize)]
pub struct Manifest {
#[serde(rename = "@context")]
context: String,
#[serde(rename = "@id")]
id: String,
#[serde(rename = "@type")]
type_: String,
license: String,
attribution: String,
description: String,
label: String,
sequences: Vec<Sequence>,
}
impl Manifest {
pub fn get_images(&self) -> Vec<String> {
let mut images = Vec::new();
for sequence in &self.sequences {
for canvas in &sequence.canvases {
for image in &canvas.images {
images.push(image.resource.id.clone());
}
}
}
return images;
}
}
#[derive(Deserialize, Debug, Serialize)]
struct Sequence {
#[serde(rename = "@id")]
id: String,
#[serde(rename = "@type")]
type_: String,
canvases: Vec<Canvas>,
}
#[derive(Deserialize, Debug, Serialize)]
struct Canvas {
#[serde(rename = "@id")]
id: String,
#[serde(rename = "@type")]
type_: String,
width: u32,
height: u32,
label: String,
images: Vec<Image>,
}
#[derive(Deserialize, Debug, Serialize)]
struct Image {
#[serde(rename = "@id")]
id: String,
#[serde(rename = "@type")]
type_: String,
resource: Resource,
}
#[derive(Deserialize, Debug, Serialize)]
struct Resource {
#[serde(rename = "@id")]
id: String,
#[serde(rename = "@type")]
type_: String,
format: String,
width: u32,
height: u32,
service: Service,
}
#[derive(Deserialize, Debug, Serialize)]
struct Service {
#[serde(rename = "@context")]
context: String,
#[serde(rename = "@id")]
id: String,
profile: String,
}
| true |
157578cc19a1950de93f8033afdf0c4e222d9af6
|
Rust
|
KallDrexx/r8
|
/r8-core/src/execution.rs
|
UTF-8
| 51,703 | 2.90625 | 3 |
[] |
no_license
|
use custom_error::custom_error;
use crate::{Hardware, Instruction, Register};
use crate::hardware::{STACK_SIZE, MEMORY_SIZE, FRAMEBUFFER_HEIGHT, FRAMEBUFFER_WIDTH};
custom_error!{pub ExecutionError
InvalidRegisterForInstruction {instruction:Instruction} = "Invalid register was used for instruction: {instruction}",
UnhandleableInstruction {instruction:Instruction} = "The instruction '{instruction}' is not known",
StackOverflow = "Call exceeded maximum stack size",
InvalidCallOrJumpAddress {address:u16} = "Call performed to invalid address {address}",
EmptyStack = "Return was called with an empty stack",
InvalidFontDigit {digit: u8} = "Font digit of {digit} is invalid, only 0-f is allowed",
}
pub fn execute_instruction(instruction: Instruction, hardware: &mut Hardware) -> Result<(), ExecutionError> {
match instruction {
Instruction::AddFromRegister {register1: Register::General(reg1_num), register2: Register::General(reg2_num)} => {
let reg1_value = hardware.gen_registers[reg1_num as usize];
let reg2_value = hardware.gen_registers[reg2_num as usize];
let will_wrap = reg1_value > 0 && std::u8::MAX - reg1_value < reg2_value;;
hardware.gen_registers[reg1_num as usize] = reg1_value.wrapping_add(reg2_value);
hardware.gen_registers[0xf] = if will_wrap { 1 } else { 0};
hardware.program_counter += 2;
}
Instruction::AddFromRegister {register1: Register::I, register2: Register::General(reg2_num)} => {
hardware.i_register = hardware.i_register.wrapping_add(hardware.gen_registers[reg2_num as usize] as u16);
hardware.program_counter += 2;
}
Instruction::AddFromValue {register: Register::General(reg_num), value} => {
hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize].wrapping_add(value);
hardware.program_counter += 2;
}
Instruction::And {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {
hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] & hardware.gen_registers[reg_num2 as usize];
hardware.program_counter += 2;
}
Instruction::Call {address} => {
if hardware.stack_pointer >= STACK_SIZE {
return Err(ExecutionError::StackOverflow);
}
hardware.stack[hardware.stack_pointer] = hardware.program_counter;
hardware.stack_pointer = hardware.stack_pointer + 1;
hardware.program_counter = address;
}
Instruction::ClearDisplay => {
for x in 0..hardware.framebuffer.len() {
for y in 0..hardware.framebuffer[x].len() {
hardware.framebuffer[x][y] = 0;
}
}
hardware.program_counter += 2;
}
Instruction::DrawSprite {x_register: Register::General(x_reg_num), y_register: Register::General(y_reg_num), height} => {
let first_row = hardware.gen_registers[y_reg_num as usize] as usize;
let first_pixel = hardware.gen_registers[x_reg_num as usize] as usize;
let shift_amount = first_pixel % 8;
let left_column_set = first_pixel / 8;
// According to the Cowgod spec, if the right column set would be out of bounds it
// wraps to the other side on the same row
let right_column_set = (left_column_set + 1) % (FRAMEBUFFER_WIDTH / 8);
let mut collisions_found = false;
for x in 0..height as usize {
let sprite_byte = hardware.memory[hardware.i_register as usize + x];
let left_byte = sprite_byte >> shift_amount;
// According to Cowgod spec, if we've gone past the screen in height then wrap to the top
let row = (first_row + x) % FRAMEBUFFER_HEIGHT;
// Detect if the xor will reset any already on pixels
if hardware.framebuffer[row][left_column_set] & left_byte > 0 {
collisions_found = true;
}
// Update framebuffer
hardware.framebuffer[row][left_column_set] ^= left_byte;
// If we are affecting pixels across column set boundaries, repeat for the next byte
if shift_amount > 0 {
let right_byte = sprite_byte << 8 - shift_amount;
if hardware.framebuffer[row][right_column_set] & right_byte > 0 {
collisions_found = true;
}
hardware.framebuffer[row][right_column_set] ^= right_byte;
}
}
hardware.program_counter += 2;
hardware.gen_registers[0xf] = if collisions_found { 1 } else { 0 };
}
Instruction::JumpToAddress {address, add_register_0} => {
let final_address = match add_register_0 {
true => address + hardware.gen_registers[0] as u16,
false => address
};
if final_address < 512 || final_address > MEMORY_SIZE as u16 {
return Err(ExecutionError::InvalidCallOrJumpAddress {address: final_address});
}
hardware.program_counter = final_address;
}
Instruction::LoadAddressIntoIRegister {address} => {
hardware.i_register = address;
hardware.program_counter += 2;
}
Instruction::LoadBcdValue {source: Register::General(reg_num)} => {
let start_address = hardware.i_register as usize;
let source_value = hardware.gen_registers[reg_num as usize];
hardware.memory[start_address] = (source_value / 100) % 10;
hardware.memory[start_address + 1] = (source_value / 10) % 10;
hardware.memory[start_address + 2] = source_value % 10;
hardware.program_counter += 2;
}
Instruction::LoadFromKeyPress {destination: Register::General(reg_num)} => {
// According to specs I have found this instruction does not recognize a key if it's
// currently down. So it will wait (stay on the same program counter for our purposes)
// until the user releases the key, at which point for one execution
// `hardware.key_released_since_last_instruction` should have the key that was just released.
if let Some(key_num) = hardware.key_released_since_last_instruction {
hardware.gen_registers[reg_num as usize] = key_num;
hardware.program_counter += 2;
}
}
Instruction::LoadFromMemory {last_register: Register::General(reg_num)} => {
for index in 0..=reg_num {
hardware.gen_registers[index as usize] = hardware.memory[hardware.i_register as usize + index as usize];
}
hardware.i_register = hardware.i_register + reg_num as u16 + 1;
hardware.program_counter += 2;
}
Instruction::LoadFromRegister {destination, source} => {
let source_value = match source {
Register::General(num) => hardware.gen_registers[num as usize],
Register::SoundTimer => hardware.sound_timer,
Register::DelayTimer => hardware.delay_timer,
_ => return Err(ExecutionError::InvalidRegisterForInstruction {instruction: Instruction::LoadFromRegister {destination, source}}),
};
match destination {
Register::General(num) => hardware.gen_registers[num as usize] = source_value,
Register::SoundTimer => hardware.sound_timer = source_value,
Register::DelayTimer => hardware.delay_timer = source_value,
_ => return Err(ExecutionError::InvalidRegisterForInstruction {instruction: Instruction::LoadFromRegister {destination, source}}),
}
hardware.program_counter += 2;
}
Instruction::LoadFromValue {destination: Register::General(reg_num), value} => {
hardware.gen_registers[reg_num as usize] = value;
hardware.program_counter += 2;
}
Instruction::LoadIntoMemory {last_register: Register::General(reg_num)} => {
for index in 0..=reg_num {
hardware.memory[hardware.i_register as usize + index as usize] = hardware.gen_registers[index as usize];
}
hardware.i_register = hardware.i_register + reg_num as u16 + 1;
hardware.program_counter += 2;
}
Instruction::LoadSpriteLocation {sprite_digit: Register::General(reg_num)} => {
let digit = hardware.gen_registers[reg_num as usize];
if digit > 0xf {
return Err(ExecutionError::InvalidFontDigit {digit});
}
hardware.i_register = hardware.font_addresses[&digit];
hardware.program_counter += 2;
}
Instruction::Or {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {
hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] | hardware.gen_registers[reg_num2 as usize];
hardware.program_counter += 2;
}
Instruction::Return => {
if hardware.stack_pointer == 0 {
return Err(ExecutionError::EmptyStack);
}
hardware.program_counter = hardware.stack[hardware.stack_pointer - 1] + 2;
hardware.stack_pointer = hardware.stack_pointer - 1;
}
Instruction::SetRandom {register: Register::General(reg_num), and_value} => {
hardware.gen_registers[reg_num as usize] = rand::random::<u8>() & and_value;
hardware.program_counter += 2;
}
Instruction::ShiftLeft {register: Register::General(reg_num)} => {
hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize] << 1;
hardware.program_counter += 2;
}
Instruction::ShiftRight {register: Register::General(reg_num)} => {
hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize] >> 1;
hardware.program_counter += 2;
}
Instruction::SkipIfEqual {register: Register::General(reg_num), value} => {
let increment = match hardware.gen_registers[reg_num as usize] == value {
true => 4,
false => 2,
};
hardware.program_counter += increment;
}
Instruction::SkipIfKeyPressed {register: Register::General(reg_num)} => {
let increment = match hardware.current_key_down {
Some(x) if x == hardware.gen_registers[reg_num as usize] => 4,
_ => 2,
};
hardware.program_counter += increment;
}
Instruction::SkipIfKeyNotPressed {register: Register::General(reg_num)} => {
let increment = match hardware.current_key_down {
Some(x) if x == hardware.gen_registers[reg_num as usize] => 2,
_ => 4,
};
hardware.program_counter += increment;
}
Instruction::SkipIfNotEqual {register: Register::General(reg_num), value} => {
let increment = match hardware.gen_registers[reg_num as usize] == value {
true => 2,
false => 4,
};
hardware.program_counter += increment;
}
Instruction::SkipIfRegistersEqual {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {
let increment = match hardware.gen_registers[reg_num1 as usize] == hardware.gen_registers[reg_num2 as usize] {
true => 4,
false => 2,
};
hardware.program_counter += increment;
}
Instruction::SkipIfRegistersNotEqual {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {
let increment = match hardware.gen_registers[reg_num1 as usize] == hardware.gen_registers[reg_num2 as usize] {
true => 2,
false => 4,
};
hardware.program_counter += increment;
}
Instruction::Subtract {minuend: Register::General(minuend_reg), subtrahend: Register::General(subtrahend_reg), stored_in: Register::General(stored_in_reg)} => {
let will_underflow = hardware.gen_registers[minuend_reg as usize] < hardware.gen_registers[subtrahend_reg as usize];
let difference = hardware.gen_registers[minuend_reg as usize].wrapping_sub(hardware.gen_registers[subtrahend_reg as usize]);
hardware.gen_registers[stored_in_reg as usize] = difference;
hardware.gen_registers[0xf] = if will_underflow { 0 } else { 1 };
hardware.program_counter += 2;
}
Instruction::Xor {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {
hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] ^ hardware.gen_registers[reg_num2 as usize];
hardware.program_counter += 2;
}
_ => return Err(ExecutionError::UnhandleableInstruction{instruction})
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use ::{Hardware, Register};
#[test]
fn can_add_value_to_general_register() {
const REGISTER_NUMBER: u8 = 3;
let mut hardware = Hardware::new();
hardware.gen_registers[REGISTER_NUMBER as usize] = 100;
hardware.program_counter = 1000;
let instruction = Instruction::AddFromValue {
register: Register::General(REGISTER_NUMBER),
value: 12,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.gen_registers[REGISTER_NUMBER as usize], 112, "Invalid register value");
assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter");
}
#[test]
fn can_add_value_to_general_register_that_overflows() {
const REGISTER_NUMBER: u8 = 3;
let mut hardware = Hardware::new();
hardware.gen_registers[REGISTER_NUMBER as usize] = 100;
hardware.program_counter = 1000;
let instruction = Instruction::AddFromValue {
register: Register::General(REGISTER_NUMBER),
value: 165,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.gen_registers[REGISTER_NUMBER as usize], 9, "Invalid register value");
assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter");
assert_eq!(hardware.gen_registers[0xf], 0, "Add by value should not have caused carry mark");
}
#[test]
fn can_add_value_from_general_register_without_carry() {
const REGISTER1_NUMBER: u8 = 4;
const REGISTER2_NUMBER: u8 = 6;
let mut hardware = Hardware::new();
hardware.gen_registers[REGISTER1_NUMBER as usize] = 100;
hardware.gen_registers[REGISTER2_NUMBER as usize] = 55;
hardware.program_counter = 1000;
let instruction = Instruction::AddFromRegister {
register1: Register::General(REGISTER1_NUMBER),
register2: Register::General(REGISTER2_NUMBER),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.gen_registers[REGISTER1_NUMBER as usize], 155, "Invalid register value");
assert_eq!(hardware.gen_registers[0xf], 0, "Invalid VF register value");
assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter");
}
#[test]
fn can_add_value_from_general_register_with_carry() {
const REGISTER1_NUMBER: u8 = 4;
const REGISTER2_NUMBER: u8 = 6;
let mut hardware = Hardware::new();
hardware.gen_registers[REGISTER1_NUMBER as usize] = 200;
hardware.gen_registers[REGISTER2_NUMBER as usize] = 65;
hardware.program_counter = 1000;
let instruction = Instruction::AddFromRegister {
register1: Register::General(REGISTER1_NUMBER),
register2: Register::General(REGISTER2_NUMBER),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.gen_registers[REGISTER1_NUMBER as usize], 9, "Invalid register value");
assert_eq!(hardware.gen_registers[0xf], 1, "Invalid VF register value");
assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter");
}
#[test]
fn can_add_value_from_general_register_to_i_register() {
let mut hardware = Hardware::new();
hardware.i_register = 100;
hardware.gen_registers[3] = 12;
hardware.program_counter = 1000;
let instruction = Instruction::AddFromRegister {
register1: Register::I,
register2: Register::General(3),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.i_register, 112, "Invalid register value");
assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter");
}
#[test]
fn can_execute_call_instruction() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.stack[0] = 567;
hardware.stack[1] = 599;
hardware.stack_pointer = 2;
let instruction = Instruction::Call {address: 1654};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.stack_pointer, 3, "Incorrect stack pointer");
assert_eq!(hardware.stack[0], 567, "Incorrect address at stack 0");
assert_eq!(hardware.stack[1], 599, "Incorrect address at stack 1");
assert_eq!(hardware.stack[2], 1000, "Incorrect address at stack 2");
assert_eq!(hardware.program_counter, 1654, "Incorrect program counter value");
}
#[test]
fn stack_overflow_error_when_call_performed_at_max_stack() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.stack_pointer = 16;
let instruction = Instruction::Call {address: 1654};
match execute_instruction(instruction, &mut hardware).unwrap_err() {
ExecutionError::StackOverflow => (),
x => panic!("Expected StackOverflow, instead got {:?}", x),
}
}
#[test]
fn can_call_jump_to_address_without_add() {
let mut hardware = Hardware::new();
hardware.program_counter = 1002;
hardware.gen_registers[0] = 10;
hardware.stack_pointer = 1;
hardware.stack[0] = 533;
let instruction = Instruction::JumpToAddress {address: 2330, add_register_0: false};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 2330, "Incorrect program counter value");
assert_eq!(hardware.stack_pointer, 1, "Incorrect stack pointer value"); // Make sure stack wasn't messed with
assert_eq!(hardware.stack[0], 533, "Incorrect stack[0] value");
}
#[test]
fn can_call_jump_address_with_add() {
let mut hardware = Hardware::new();
hardware.program_counter = 1002;
hardware.gen_registers[0] = 10;
hardware.stack_pointer = 1;
hardware.stack[0] = 533;
let instruction = Instruction::JumpToAddress {address: 2330, add_register_0: true};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 2340, "Incorrect program counter value");
assert_eq!(hardware.stack_pointer, 1, "Incorrect stack pointer value"); // Make sure stack wasn't messed with
assert_eq!(hardware.stack[0], 533, "Incorrect stack[0] value");
}
#[test]
fn cannot_jump_to_address_below_512() {
let mut hardware = Hardware::new();
hardware.program_counter = 1002;
hardware.gen_registers[0] = 10;
hardware.stack_pointer = 1;
hardware.stack[0] = 533;
let instruction = Instruction::JumpToAddress {address: 511, add_register_0: false};
match execute_instruction(instruction, &mut hardware).unwrap_err() {
ExecutionError::InvalidCallOrJumpAddress {address: 511} => (),
x => panic!("Expected InvalidCallOrJumpAddress {{address: 2331}}, instead got {:?}", x),
}
}
#[test]
fn cannot_jump_to_address_above_memory_size() {
let mut hardware = Hardware::new();
hardware.program_counter = 1002;
hardware.gen_registers[0] = 10;
hardware.stack_pointer = 1;
hardware.stack[0] = 533;
let address = MEMORY_SIZE as u16 + 1;
let instruction = Instruction::JumpToAddress {address, add_register_0: false};
match execute_instruction(instruction, &mut hardware).unwrap_err() {
ExecutionError::InvalidCallOrJumpAddress {address: _} => (),
x => panic!("Expected InvalidCallOrJumpAddress {{address: {}}}, instead got {:?}", address, x),
}
}
#[test]
fn jump_to_machine_code_is_unhandled() {
// According to specs, SYS instructions are ignored by modern interpreters.
let mut hardware = Hardware::new();
let instruction = Instruction::JumpToMachineCode {address: 123};
match execute_instruction(instruction, &mut hardware).unwrap_err() {
ExecutionError::UnhandleableInstruction {instruction: _} => (),
x => panic!("Expected UnhandleableInstruction, instead got {:?}", x),
}
}
#[test]
fn can_load_from_value_into_general_register() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 10;
let instruction = Instruction::LoadFromValue {
destination: Register::General(4),
value: 123,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.gen_registers[4], 123, "Incorrect value in register");
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
}
#[test]
fn can_load_from_register_into_general_register() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 10;
hardware.gen_registers[5] = 122;
let instruction = Instruction::LoadFromRegister {
destination: Register::General(4),
source: Register::General(5),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.gen_registers[4], 122, "Incorrect value in register");
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
}
#[test]
fn load_from_key_press_does_not_progress_if_no_key_released() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 10;
hardware.current_key_down = Some(0x4);
hardware.key_released_since_last_instruction = None;
let instruction = Instruction::LoadFromKeyPress {destination: Register::General(4)};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1000, "Incorrect program counter");
assert_eq!(hardware.gen_registers[4], 10, "Register 4 value should not have changed");
}
#[test]
fn load_from_key_press_proceeds_if_key_was_released() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 10;
hardware.current_key_down = None;
hardware.key_released_since_last_instruction = Some(0x5);
let instruction = Instruction::LoadFromKeyPress {destination: Register::General(4)};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[4], 5, "Incorrect value in register");
}
#[test]
fn can_load_bcd_value_into_memory() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 235;
hardware.i_register = 1500;
let instruction = Instruction::LoadBcdValue {source: Register::General(5)};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.memory[1500], 2, "Incorrect bcd value #1");
assert_eq!(hardware.memory[1501], 3, "Incorrect bcd value #2");
assert_eq!(hardware.memory[1502], 5, "Incorrect bcd value #3");
}
#[test]
fn can_load_register_values_into_memory() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[0] = 100;
hardware.gen_registers[1] = 101;
hardware.gen_registers[2] = 102;
hardware.gen_registers[3] = 103;
hardware.gen_registers[4] = 104;
hardware.gen_registers[5] = 105;
hardware.i_register = 933;
let instruction = Instruction::LoadIntoMemory {last_register: Register::General(4)};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.memory[933], 100, "Incorrect value in memory location 0");
assert_eq!(hardware.memory[934], 101, "Incorrect value in memory location 1");
assert_eq!(hardware.memory[935], 102, "Incorrect value in memory location 2");
assert_eq!(hardware.memory[936], 103, "Incorrect value in memory location 3");
assert_eq!(hardware.memory[937], 104, "Incorrect value in memory location 4");
assert_eq!(hardware.memory[938], 0, "Incorrect value in memory location 5");
assert_eq!(hardware.i_register, 938, "Incorrect resulting I register");
}
#[test]
fn can_load_memory_into_multiple_register_values() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.i_register = 933;
hardware.memory[933] = 100;
hardware.memory[934] = 101;
hardware.memory[935] = 102;
hardware.memory[936] = 103;
hardware.memory[937] = 104;
hardware.memory[938] = 105;
let instruction = Instruction::LoadFromMemory {last_register: Register::General(4)};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[0], 100, "Incorrect value in register V0");
assert_eq!(hardware.gen_registers[1], 101, "Incorrect value in register V1");
assert_eq!(hardware.gen_registers[2], 102, "Incorrect value in register V2");
assert_eq!(hardware.gen_registers[3], 103, "Incorrect value in register V3");
assert_eq!(hardware.gen_registers[4], 104, "Incorrect value in register V4");
assert_eq!(hardware.gen_registers[5], 0, "Incorrect value in register V5");
assert_eq!(hardware.i_register, 938, "Incorrect resulting I register");
}
#[test]
fn can_execute_return_instruction() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.stack_pointer = 2;
hardware.stack[0] = 1500;
hardware.stack[1] = 938;
hardware.stack[2] = 1700; // residual from previous call
let instruction = Instruction::Return;
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 938 + 2, "Incorrect program pointer");
assert_eq!(hardware.stack_pointer, 1, "Incorrect stack pointer");
}
#[test]
fn cannot_execute_return_with_empty_stack() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.stack_pointer = 0;
hardware.stack[0] = 1500;
hardware.stack[1] = 938;
let instruction = Instruction::Return;
match execute_instruction(instruction, &mut hardware).unwrap_err() {
ExecutionError::EmptyStack => (),
x => panic!("Expected EmptyStack instead got {:?}", x),
}
}
#[test]
fn skip_occurs_when_skip_if_equal_passes() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 23;
let instruction = Instruction::SkipIfEqual {
register: Register::General(5),
value: 23,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1004, "Incorrect program counter");
}
#[test]
fn does_not_skip_when_skip_if_equal_fails() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 23;
let instruction = Instruction::SkipIfEqual {
register: Register::General(5),
value: 24,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
}
#[test]
fn skip_occurs_when_skip_if_not_equal_passes() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 23;
let instruction = Instruction::SkipIfNotEqual {
register: Register::General(5),
value: 25,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1004, "Incorrect program counter");
}
#[test]
fn does_not_skip_occurs_when_skip_if_not_equal_fails() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 23;
let instruction = Instruction::SkipIfNotEqual {
register: Register::General(5),
value: 23,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
}
#[test]
fn skip_occurs_when_skip_if_register_equals_passes() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 23;
hardware.gen_registers[5] = 23;
let instruction = Instruction::SkipIfRegistersEqual {
register1: Register::General(5),
register2: Register::General(4),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1004, "Incorrect program counter");
}
#[test]
fn does_not_skip_occurs_when_skip_if_register_equals_fails() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 25;
hardware.gen_registers[5] = 23;
let instruction = Instruction::SkipIfRegistersEqual {
register1: Register::General(5),
register2: Register::General(4),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
}
#[test]
fn skip_occurs_when_skip_if_register_not_equals_passes() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 25;
hardware.gen_registers[5] = 23;
let instruction = Instruction::SkipIfRegistersNotEqual {
register1: Register::General(5),
register2: Register::General(4),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1004, "Incorrect program counter");
}
#[test]
fn does_not_skip_occurs_when_skip_if_register_not_equals_fails() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 23;
hardware.gen_registers[5] = 23;
let instruction = Instruction::SkipIfRegistersNotEqual {
register1: Register::General(5),
register2: Register::General(4),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
}
#[test]
fn skip_occurs_when_skip_if_key_pressed_passes() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 10;
hardware.current_key_down = Some(10);
let instruction = Instruction::SkipIfKeyPressed {
register: Register::General(5),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1004, "Incorrect program counter");
}
#[test]
fn does_not_skip_occurs_when_skip_if_key_pressed_fails() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 10;
hardware.current_key_down = Some(11);
let instruction = Instruction::SkipIfKeyPressed {
register: Register::General(5),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
}
#[test]
fn skip_occurs_when_skip_if_key_not_pressed_passes() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 10;
hardware.current_key_down = Some(11);
let instruction = Instruction::SkipIfKeyNotPressed {
register: Register::General(5),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1004, "Incorrect program counter");
}
#[test]
fn does_not_skip_occurs_when_skip_if_key_not_pressed_fails() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[5] = 10;
hardware.current_key_down = Some(10);
let instruction = Instruction::SkipIfKeyNotPressed {
register: Register::General(5),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
}
#[test]
fn can_or_register_values_together() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[2] = 123;
hardware.gen_registers[3] = 203;
let instruction = Instruction::Or {
register1: Register::General(3),
register2: Register::General(2),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[2], 123, "Incorrect V2 value");
assert_eq!(hardware.gen_registers[3], 203 | 123, "Incorrect v3 value");
}
#[test]
fn can_and_register_values_together() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[2] = 123;
hardware.gen_registers[3] = 203;
let instruction = Instruction::And {
register1: Register::General(3),
register2: Register::General(2),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[2], 123, "Incorrect V2 value");
assert_eq!(hardware.gen_registers[3], 203 & 123, "Incorrect v3 value");
}
#[test]
fn can_xor_register_values_together() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[2] = 123;
hardware.gen_registers[3] = 203;
let instruction = Instruction::Xor {
register1: Register::General(3),
register2: Register::General(2),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[2], 123, "Incorrect V2 value");
assert_eq!(hardware.gen_registers[3], 203 ^ 123, "Incorrect v3 value");
}
#[test]
fn can_shift_register_value_right() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[3] = 203;
let instruction = Instruction::ShiftRight {
register: Register::General(3),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[3], 203 >> 1, "Incorrect v3 value");
}
#[test]
fn can_shift_register_value_left() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[3] = 203;
let instruction = Instruction::ShiftLeft {
register: Register::General(3),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[3], 203 << 1, "Incorrect v3 value");
}
#[test]
fn can_get_random_number() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[3] = 100;
let instruction = Instruction::SetRandom {
register: Register::General(3),
and_value: 23,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
let value1 = hardware.gen_registers[3];
let instruction = Instruction::SetRandom {
register: Register::General(3),
and_value: 23,
};
execute_instruction(instruction, &mut hardware).unwrap();
let value2 = hardware.gen_registers[3];
assert_ne!(value1, value2, "Values 1 and 2 were the same (possibly not random??)");
}
#[test]
fn can_subtract_register_without_underflow() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 100;
hardware.gen_registers[5] = 25;
let instruction = Instruction::Subtract {
minuend: Register::General(4),
subtrahend: Register::General(5),
stored_in: Register::General(4),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[4], 75, "Incorrect V4 register");
assert_eq!(hardware.gen_registers[5], 25, "Incorrect V5 register");
assert_eq!(hardware.gen_registers[0xf], 1, "Incorrect VF register");
}
#[test]
fn can_subtract_register_with_underflow() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 100;
hardware.gen_registers[5] = 25;
let instruction = Instruction::Subtract {
minuend: Register::General(5),
subtrahend: Register::General(4),
stored_in: Register::General(5),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[4], 100, "Incorrect V4 register");
assert_eq!(hardware.gen_registers[5], 181, "Incorrect V5 register");
assert_eq!(hardware.gen_registers[0xf], 0, "Incorrect VF register");
}
#[test]
fn can_clear_display() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
for x in 0..hardware.framebuffer.len() {
for y in 0..hardware.framebuffer[x].len() {
hardware.framebuffer[x][y] = 0xFF;
}
}
let instruction = Instruction::ClearDisplay;
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
for x in 0..hardware.framebuffer.len() {
for y in 0..hardware.framebuffer[x].len() {
if hardware.framebuffer[x][y] != 0 {
panic!("Expected frame buffer by {}x{} to be 0", x, y);
}
}
}
}
#[test]
fn can_load_digit_sprite_location() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[4] = 0xa;
let instruction = Instruction::LoadSpriteLocation {sprite_digit: Register::General(4)};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.i_register, hardware.font_addresses[&0xa], "Incorrect sprite address");
}
#[test]
fn can_load_address_into_i_register() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
let instruction = Instruction::LoadAddressIntoIRegister {address: 0x123};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.i_register, 0x123, "Incorrect I register value");
}
#[test]
fn visible_8_x_3_sprite_to_screen_on_x_multiple_of_8_can_be_drawn() {
const SPRITE_START_ADDRESS: usize = 1046;
const X_POS: u8 = 16;
const Y_POS: u8 = 2;
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.i_register = SPRITE_START_ADDRESS as u16;
hardware.gen_registers[4] = X_POS;
hardware.gen_registers[3] = Y_POS;
hardware.memory[SPRITE_START_ADDRESS] = 0b10101010;
hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101;
hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101;
hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111;
let instruction = Instruction::DrawSprite {
x_register: Register::General(4),
y_register: Register::General(3),
height: 3,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[0xf], 0, "Incorrect VF value");
assert_eq!(hardware.framebuffer[2][2], 0b10101010, "Incorrect framebuffer value at row 2 column byte 2");
assert_eq!(hardware.framebuffer[3][2], 0b01010101, "Incorrect framebuffer value at row 3 column byte 2");
assert_eq!(hardware.framebuffer[4][2], 0b11001101, "Incorrect framebuffer value at row 4 column byte 2");
assert_eq!(hardware.framebuffer[5][2], 0, "Incorrect framebuffer value at row 5 column byte 2");
}
#[test]
fn visible_8_x_3_sprite_to_screen_on_x_non_multiple_of_8_can_be_drawn() {
const SPRITE_START_ADDRESS: usize = 1046;
const X_POS: u8 = 18;
const Y_POS: u8 = 2;
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.i_register = SPRITE_START_ADDRESS as u16;
hardware.gen_registers[4] = X_POS;
hardware.gen_registers[3] = Y_POS;
hardware.memory[SPRITE_START_ADDRESS] = 0b10101010;
hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101;
hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101;
hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111;
let instruction = Instruction::DrawSprite {
x_register: Register::General(4),
y_register: Register::General(3),
height: 3,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[0xf], 0, "Incorrect VF value");
assert_eq!(hardware.framebuffer[2][2], 0b00101010, "Incorrect framebuffer value at row 2 column byte 2");
assert_eq!(hardware.framebuffer[2][3], 0b10000000, "Incorrect framebuffer value at row 2 column byte 3");
assert_eq!(hardware.framebuffer[3][2], 0b00010101, "Incorrect framebuffer value at row 3 column byte 2");
assert_eq!(hardware.framebuffer[3][3], 0b01000000, "Incorrect framebuffer value at row 3 column byte 3");
assert_eq!(hardware.framebuffer[4][2], 0b00110011, "Incorrect framebuffer value at row 4 column byte 2");
assert_eq!(hardware.framebuffer[4][3], 0b01000000, "Incorrect framebuffer value at row 4 column byte 3");
assert_eq!(hardware.framebuffer[5][2], 0, "Incorrect framebuffer value at row 5 column byte 2");
assert_eq!(hardware.framebuffer[5][3], 0, "Incorrect framebuffer value at row 5 column byte 3");
}
#[test]
fn sprites_xor_existing_framebuffer_values() {
const SPRITE_START_ADDRESS: usize = 1046;
const X_POS: u8 = 18;
const Y_POS: u8 = 2;
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.i_register = SPRITE_START_ADDRESS as u16;
hardware.gen_registers[4] = X_POS;
hardware.gen_registers[3] = Y_POS;
hardware.memory[SPRITE_START_ADDRESS] = 0b10101010;
hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101;
hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101;
hardware.framebuffer[2][2] = 0xFF;
hardware.framebuffer[2][3] = 0xFF;
let instruction = Instruction::DrawSprite {
x_register: Register::General(4),
y_register: Register::General(3),
height: 3,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[0xf], 1, "Incorrect VF value");
assert_eq!(hardware.framebuffer[2][2], 0b00101010 ^ 0xFF, "Incorrect framebuffer value at row 2 column byte 2");
assert_eq!(hardware.framebuffer[2][3], 0b10000000 ^ 0xFF, "Incorrect framebuffer value at row 2 column byte 3");
assert_eq!(hardware.framebuffer[3][2], 0b00010101, "Incorrect framebuffer value at row 3 column byte 2");
assert_eq!(hardware.framebuffer[3][3], 0b01000000, "Incorrect framebuffer value at row 3 column byte 3");
assert_eq!(hardware.framebuffer[4][2], 0b00110011, "Incorrect framebuffer value at row 4 column byte 2");
assert_eq!(hardware.framebuffer[4][3], 0b01000000, "Incorrect framebuffer value at row 4 column byte 3");
assert_eq!(hardware.framebuffer[5][2], 0, "Incorrect framebuffer value at row 5 column byte 2");
assert_eq!(hardware.framebuffer[5][3], 0, "Incorrect framebuffer value at row 5 column byte 3");
}
#[test]
fn partially_visible_sprite_wraps_across_both_axis() {
const SPRITE_START_ADDRESS: usize = 1046;
const X_POS: u8 = 58;
const Y_POS: u8 = 30;
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.i_register = SPRITE_START_ADDRESS as u16;
hardware.gen_registers[4] = X_POS;
hardware.gen_registers[3] = Y_POS;
hardware.memory[SPRITE_START_ADDRESS] = 0b10101010;
hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101;
hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101;
hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111;
let instruction = Instruction::DrawSprite {
x_register: Register::General(4),
y_register: Register::General(3),
height: 3,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[0xf], 0, "Incorrect VF value");
assert_eq!(hardware.framebuffer[30][7], 0b00101010, "Incorrect framebuffer value at row 30 column byte 7");
assert_eq!(hardware.framebuffer[30][0], 0b10000000, "Incorrect framebuffer value at row 30 column byte 0");
assert_eq!(hardware.framebuffer[31][7], 0b00010101, "Incorrect framebuffer value at row 31 column byte 7");
assert_eq!(hardware.framebuffer[31][0], 0b01000000, "Incorrect framebuffer value at row 31 column byte 0");
assert_eq!(hardware.framebuffer[0][7], 0b00110011, "Incorrect framebuffer value at row 0 column byte 7");
assert_eq!(hardware.framebuffer[0][0], 0b01000000, "Incorrect framebuffer value at row 0 column byte 0");
assert_eq!(hardware.framebuffer[1][7], 0, "Incorrect framebuffer value at row 1 column byte 7");
assert_eq!(hardware.framebuffer[1][0], 0, "Incorrect framebuffer value at row 1 column byte 0");
}
#[test]
fn can_set_gen_register_to_delay_timer_value() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[3] = 25;
hardware.delay_timer = 50;
let instruction = Instruction::LoadFromRegister {
source: Register::DelayTimer,
destination: Register::General(3),
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[3], 50, "Incorrect VX value");
assert_eq!(hardware.delay_timer, 50, "Incorrect delay timer value");
}
#[test]
fn can_set_delay_timer_to_value_in_general_register() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[3] = 25;
hardware.delay_timer = 50;
let instruction = Instruction::LoadFromRegister {
source: Register::General(3),
destination: Register::DelayTimer,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[3], 25, "Incorrect VX value");
assert_eq!(hardware.delay_timer, 25, "Incorrect delay timer value");
}
#[test]
fn can_set_sound_timer_to_value_in_general_register() {
let mut hardware = Hardware::new();
hardware.program_counter = 1000;
hardware.gen_registers[3] = 25;
hardware.sound_timer = 50;
let instruction = Instruction::LoadFromRegister {
source: Register::General(3),
destination: Register::SoundTimer,
};
execute_instruction(instruction, &mut hardware).unwrap();
assert_eq!(hardware.program_counter, 1002, "Incorrect program counter");
assert_eq!(hardware.gen_registers[3], 25, "Incorrect VX value");
assert_eq!(hardware.sound_timer, 25, "Incorrect delay timer value");
}
}
| true |
b02f18df40f0853593c61d4e526fd341a4b168d3
|
Rust
|
kalaninja/data-structures
|
/week2_priority_queues_and_disjoint_sets/2_job_queue/rust/src/main.rs
|
UTF-8
| 3,274 | 3.5 | 4 |
[] |
no_license
|
use std::io::stdin;
use std::fmt::{self, Display, Formatter};
type ThreadId = u32;
type ThreadTime = u64;
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
struct Thread {
time_idle: ThreadTime,
thread_id: ThreadId,
}
impl Thread {
fn new(thread_id: ThreadId, time_idle: ThreadTime) -> Self {
Thread { thread_id, time_idle }
}
}
impl Display for Thread {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.thread_id, self.time_idle)
}
}
#[derive(Debug)]
struct ThreadQueue {
data: Vec<Thread>
}
impl ThreadQueue {
fn new(n: usize) -> Self {
ThreadQueue {
data: (0..n as ThreadId)
.fold(Vec::with_capacity(n),
|mut acc, i| {
acc.push(Thread::new(i, 0));
acc
})
}
}
fn peak(&self) -> &Thread {
&self.data[0]
}
fn exec_task(&mut self, time: u32) {
self.data[0].time_idle += time as u64;
self.sift_down(0);
}
fn sift_down(&mut self, i: usize) {
let mut cur_i = i;
loop {
let left = 2 * cur_i + 1;
if left >= self.data.len() { break; }
let right = 2 * cur_i + 2;
let min = if right < self.data.len() && self.data[right] < self.data[left] {
right
} else {
left
};
if self.data[min] < self.data[cur_i] {
self.data.swap(cur_i, min);
cur_i = min;
} else {
break;
}
}
}
}
fn main() {
let n = read_line()
.split_whitespace()
.nth(0).unwrap()
.parse().unwrap();
let t = read_line().trim()
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
solve(n, t).iter().for_each(|x| println!("{}", x));
}
fn solve(n: usize, tasks: Vec<u32>) -> Vec<Thread> {
let mut threads = ThreadQueue::new(n);
let mut result = Vec::with_capacity(tasks.len());
for time in tasks {
result.push(*threads.peak());
threads.exec_task(time);
}
result
}
#[test]
fn test_case_1() {
let e = vec![
Thread::new(0, 0),
Thread::new(1, 0),
Thread::new(0, 1),
Thread::new(1, 2),
Thread::new(0, 4),
];
assert_eq!(solve(2, vec![1, 2, 3, 4, 5]), e);
}
#[test]
fn test_case_2() {
let e = vec![
Thread::new(0, 0),
Thread::new(1, 0),
Thread::new(2, 0),
Thread::new(3, 0),
Thread::new(0, 1),
Thread::new(1, 1),
Thread::new(2, 1),
Thread::new(3, 1),
Thread::new(0, 2),
Thread::new(1, 2),
Thread::new(2, 2),
Thread::new(3, 2),
Thread::new(0, 3),
Thread::new(1, 3),
Thread::new(2, 3),
Thread::new(3, 3),
Thread::new(0, 4),
Thread::new(1, 4),
Thread::new(2, 4),
Thread::new(3, 4),
];
assert_eq!(solve(4, vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), e);
}
fn read_line() -> String {
let mut input = String::new();
stdin().read_line(&mut input).unwrap();
input
}
| true |
ef1331be181b9020769930de3c4dcfc1ff3f1abd
|
Rust
|
MwlLj/rust-p2p
|
/exchange_service/src/enums/nat.rs
|
UTF-8
| 555 | 3.46875 | 3 |
[] |
no_license
|
use std::cmp::PartialEq;
#[derive(PartialEq, Debug, Clone)]
pub enum Nat {
Nat1 = 1,
Nat2 = 2,
Nat3 = 3,
Nat4 = 4,
NotNat4 = 5
}
impl std::convert::From<u8> for Nat {
fn from(item: u8) -> Self {
match item {
1 => Nat::Nat1,
2 => Nat::Nat2,
3 => Nat::Nat3,
4 => Nat::Nat4,
5 => Nat::NotNat4,
_ => Nat::Nat1
}
}
}
// impl PartialEq for Nat {
// fn eq(&self, other: &Nat) -> bool {
// *self as u8 == *other as u8
// }
// }
| true |
c18e0eec7aa060fe97fdb6dc292259a5da9e8088
|
Rust
|
leon2k2k2k/xi_pl
|
/xi-backends/py_backend/py_prim.rs
|
UTF-8
| 4,355 | 2.515625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
use std::collections::BTreeMap;
use xi_core::judgment::{Judgment, Primitive};
use xi_uuid::VarUuid;
use crate::py_backend::py_output::{
make_var_name, promise_resolve, to_py_ident, to_py_num, to_py_str, Expr,
};
use super::py_output::{to_py_app, to_py_ident1};
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum PyPrim {
StringType,
NumberType,
StringElem(String),
NumberElem(String),
Ffi(String, String),
Remote(String, String),
Var(VarUuid),
}
impl Primitive for PyPrim {
fn maybe_prim_type(&self) -> Option<Judgment<Self>> {
use PyPrim::*;
match self {
StringType => Some(Judgment::u(None)),
NumberType => Some(Judgment::u(None)),
StringElem(_) => Some(Judgment::prim_wo_prim_type(StringType, None)),
NumberElem(_) => Some(Judgment::prim_wo_prim_type(NumberType, None)),
Ffi(_, _) => None,
Var(_) => None,
Remote(_, _) => None,
}
}
}
impl PyPrim {
pub fn to_py_prim(
&self,
ffi: &mut BTreeMap<(String, String), VarUuid>,
remote: &mut BTreeMap<(String, String), VarUuid>,
) -> Expr {
match self {
PyPrim::StringType => {
promise_resolve(to_py_app(to_py_ident("prim"), vec![to_py_str("Str")]))
}
PyPrim::NumberType => {
promise_resolve(to_py_app(to_py_ident("prim"), vec![to_py_str("Int")]))
}
PyPrim::StringElem(str) => promise_resolve(to_py_str(str.clone())),
PyPrim::NumberElem(num) => promise_resolve(to_py_num(num.clone())),
PyPrim::Ffi(filename, ffi_name) => {
let var = match ffi.get(&(filename.clone(), ffi_name.clone())) {
Some(var) => *var,
None => {
let var = VarUuid::new();
ffi.insert((filename.clone(), ffi_name.clone()), var);
var
}
};
to_py_ident(format!("ffi{}", var.index()))
}
PyPrim::Remote(remote_address, remote_name) => {
let var = match remote.get(&(remote_address.clone(), remote_name.clone())) {
Some(var) => *var,
None => {
let var = VarUuid::new();
remote.insert((remote_address.clone(), remote_address.clone()), var);
var
}
};
to_py_ident(format!("remote{}", var.index()))
}
PyPrim::Var(index) => to_py_ident1(make_var_name(index)),
}
}
}
#[derive(Clone, Debug)]
pub struct PyModule {
pub str_to_index: BTreeMap<String, VarUuid>,
pub module_items: BTreeMap<VarUuid, PyModuleItem>,
}
#[derive(Clone, Debug)]
pub struct PyModuleAndImports {
pub module: PyModule,
pub imports: BTreeMap<VarUuid, PyModuleAndImports>,
}
#[derive(Clone, Debug)]
pub enum PyModuleItem {
Define(PyDefineItem),
// Import(JsImportItem),
}
impl PyModuleItem {
pub fn type_(&self) -> Judgment<PyPrim> {
match self {
PyModuleItem::Define(define_item) => define_item.type_.clone(),
// JsModuleItem::Import(import_item) => import_item.type_.clone(),
}
}
pub fn transport_info(&self) -> TransportInfo {
match self {
PyModuleItem::Define(define_item) => define_item.transport_info.clone(),
}
}
}
#[derive(Clone, Debug)]
pub struct PyDefineItem {
pub name: String,
pub transport_info: TransportInfo,
pub type_: Judgment<PyPrim>,
pub impl_: Judgment<PyPrim>,
}
#[derive(Clone, Debug)]
pub struct TransportInfo {
pub origin: Option<String>,
pub transport: Option<String>,
}
impl TransportInfo {
pub fn none() -> TransportInfo {
TransportInfo {
origin: None,
transport: None,
}
}
pub fn only_origin(origin: String) -> TransportInfo {
TransportInfo {
origin: Some(origin),
transport: None,
}
}
pub fn origin_and_transport(origin: String, tranport: String) -> TransportInfo {
TransportInfo {
origin: Some(origin),
transport: Some(tranport),
}
}
}
| true |
8be91f8a6314d1ee36682bf93fca8b5573a1dafd
|
Rust
|
SuperiorJT/mr-cd-projekt-red
|
/src/audio/receiver.rs
|
UTF-8
| 3,352 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
use std::{
collections::HashMap,
sync::Arc,
sync::RwLock,
time::{Instant, SystemTime, UNIX_EPOCH},
};
use config::{Config, File};
use serde::Deserialize;
use serenity::model::id::UserId;
use serenity::voice::AudioReceiver;
use super::buffer::DiscordAudioBuffer;
use super::DiscordAudioPacket;
#[derive(Deserialize)]
struct UserMixConfig {
volume: f32,
mute: bool,
}
impl Default for UserMixConfig {
fn default() -> Self {
Self {
volume: 1.0,
mute: false,
}
}
}
pub struct Receiver {
buffer: Arc<RwLock<DiscordAudioBuffer>>,
mix_config: HashMap<u64, UserMixConfig>,
instant: Instant,
}
impl Receiver {
pub fn new(buffer: Arc<RwLock<DiscordAudioBuffer>>) -> Self {
let mut config = Config::new();
if let Err(err) = config.merge(File::with_name("config/mixer.json")) {
error!("{} - Using empty config", err);
}
let mix_config = match config.try_into::<HashMap<u64, UserMixConfig>>() {
Ok(c) => c,
Err(_) => HashMap::new(),
};
Self {
buffer,
mix_config,
instant: Instant::now(),
}
}
}
impl AudioReceiver for Receiver {
fn speaking_update(&mut self, ssrc: u32, user_id: u64, speaking: bool) {
let mut buffer = match self.buffer.write() {
Ok(buffer) => buffer,
Err(why) => {
error!("Could not get audio buffer lock: {:?}", why);
return;
}
};
let volume = self.mix_config.entry(user_id).or_default().volume;
buffer.update_track_mix(ssrc, (volume * f32::from(u8::max_value())) as u8);
info!("Speaking Update: {}, {}, {}", user_id, ssrc, speaking);
}
fn voice_packet(
&mut self,
ssrc: u32,
sequence: u16,
_timestamp: u32,
stereo: bool,
data: &[i16],
_compressed_size: usize,
) {
// info!(
// "Audio packet sequence {:05} has {:04} bytes, SSRC {}, is_stereo: {}",
// sequence,
// data.len() * 2,
// ssrc,
// stereo
// );
// let since_the_epoch = SystemTime::now()
// .duration_since(UNIX_EPOCH)
// .expect("Time went backwards");
// let since_start = self.instant.elapsed().as_secs()
// * u64::from(1000 + self.instant.elapsed().subsec_millis());
// let timestamp = since_the_epoch.as_secs() * 1000 + since_the_epoch.subsec_millis() as u64;
// info!(
// "Time: {}, Sequence: {}, ssrc: {}",
// since_start, sequence, ssrc
// );
// let mut buffer = match self.buffer.write() {
// Ok(buffer) => buffer,
// Err(why) => {
// error!("Could not get audio buffer lock: {:?}", why);
// return;
// }
// };
// buffer.insert_item(DiscordAudioPacket::new(
// ssrc,
// sequence,
// timestamp,
// stereo,
// data.to_owned(),
// ));
// info!(
// "Data Size: {}, Buffer Length: {}, Buffer Cap: {}",
// data.len(),
// buffer.size(),
// buffer.capacity()
// );
}
}
| true |
e1257f2999b0a1a7a626edd92e68b001cded0b65
|
Rust
|
tonmanna/RustLearningFollowBookBeginer
|
/chapter2/src/tuples_sample3.rs
|
UTF-8
| 159 | 2.796875 | 3 |
[] |
no_license
|
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);
pub fn tuples_sample_struct() {
let matrix = Matrix(1.1,1.2,2.1,2.2);
println!("{:?}", matrix);
}
| true |
515021a225e189e61d7eab324be1137cab06e59b
|
Rust
|
shunty-gh/AdventOfCode2017
|
/day12/aoc2017-day12.rs
|
UTF-8
| 2,689 | 3.203125 | 3 |
[] |
no_license
|
use std::io::prelude::*;
use std::fmt;
use std::io::BufReader;
use std::fs::File;
use std::path::Path;
use std::env;
/// Advent of Code 2017
/// Day 12
// compile with, for example:
// $> rustc -g --out-dir ./bin aoc2017-day12.rs
// or (providing the 'path' is set correctly in Cargo.toml):
// $> cargo build
fn main() {
let args: Vec<String> = env::args().collect();
let inputname: &str;
if args.len() > 1 {
inputname = &args[1];
} else {
inputname = "./aoc2017-day12.txt";
}
let input = lines_from_file(inputname);
let programs: Vec<Program> = input.iter()
.map(|line| {
let splits: Vec<&str> = line.split(" <-> ").collect();
Program {
id: splits[0].to_string().parse::<usize>().unwrap(),
connections: splits[1].to_string()
.split(", ")
.map(|s| s.parse::<usize>().unwrap())
.collect(),
}
})
.collect();
//println!("Programs: {:?}", programs);
let mut visited: Vec<usize> = vec![];
let mut group_count = 0;
let mut group_zero_count = 0;
for program in &programs {
let key = &program.id;
if visited.contains(key) {
continue;
}
group_count += 1;
let mut to_visit: Vec<usize> = vec![*key];
while to_visit.len() > 0 {
let current = to_visit.pop().unwrap();
if !visited.contains(¤t) {
visited.push(current);
for conn in &programs[current].connections {
if !visited.contains(conn) {
to_visit.push(*conn);
}
}
}
}
if *key == 0 {
group_zero_count = visited.len();
}
}
assert!(programs.len() == visited.len(), "Number visited should equal total number of programs");
println!("Using {} as input", &inputname);
println!("Num programs: {}", programs.len());
println!("Programs connected to P0 (part 1): {}", group_zero_count);
println!("Number of groups (part 2): {}", group_count);
}
fn lines_from_file<P>(filename: P) -> Vec<String>
where
P: AsRef<Path>,
{
let file = File::open(filename).expect("no such file");
let buf = BufReader::new(file);
buf.lines()
.map(|l| l.expect("Could not parse line"))
.collect()
}
struct Program {
id: usize,
connections: Vec<usize>,
}
impl fmt::Debug for Program {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Prog id: {}; Connections: {:?}", self.id, self.connections)
}
}
| true |
f5dff23875161835aebdb3f0e6a7dc725d3facee
|
Rust
|
KwinnerChen/rust_repo
|
/workspace_learning/complex/src/lib.rs
|
UTF-8
| 1,850 | 3.921875 | 4 |
[] |
no_license
|
#![allow(dead_code)]
use std::{fmt::{Display, Formatter, Result}, ops::Add, write};
/// 表示复数结构
#[derive(Debug, Default, PartialEq, Clone, Copy)]
struct Complex<T> {
re: T,
im: T,
}
impl<T: Add<Output=T>> Complex<T> {
/// 创建一个复数结构
/// # Example
/// ```
/// use complex::Complex;
/// let com = Complex::new(0, 0);
/// assert_eq!(Complex{re:0, im:0}, com);
///```
/// # Panic!
/// 只能由实现了Add trait的类型创建
fn new(re: T, im: T) -> Self {
Self {
re,
im,
}
}
}
impl<T: Add<Output=T>> Add for Complex<T> {
type Output = Self;
fn add(self, other:Self) -> Self::Output {
Self {
re: self.re + other.re,
im: self.im + other.im,
}
}
}
impl<T: Display> Display for Complex<T> {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}+{}i", self.re, self.im)
}
}
fn show_me(item: impl Display) {
println!("{}", item);
}
#[cfg(test)]
mod tests {
#[derive(Debug, Clone)]
struct Foo;
use super::*;
#[test]
fn it_works() {
let complex1 = Complex::new(3, 5);
let complex2 = Complex::<i32>::default();
assert_eq!(complex1, complex1 + complex2);
assert_eq!(complex1, Complex {re:3, im:5});
println!("{}", complex1);
}
#[test]
fn do_work() {
show_me("hello rust!");
}
#[test]
fn do_work_2() {
let mut s1 = String::from("hello");
let s2 = &mut s1;
s2.push_str("rust");
println!("{:?}", s2);
}
#[test]
fn test_work_3() {
let mut s = String::from("Hello Rust");
let a_mut_ref = &mut s;
let a_mut_ref_2 = a_mut_ref;
a_mut_ref_2.push_str("!");
println!("{}", &s);
}
}
| true |
c2115a876151368aae7cb2232eb1b815a0990de5
|
Rust
|
peterhj/libcpu_topo
|
/src/lib.rs
|
UTF-8
| 2,874 | 2.921875 | 3 |
[] |
no_license
|
extern crate libc;
use libc::*;
//use std::collections::{HashSet};
use std::fs::{File};
use std::io::{BufRead, BufReader};
use std::mem::{size_of_val, uninitialized};
use std::path::{PathBuf};
//use std::process::{Command};
/*pub enum CpuLevel {
Processor,
Core,
Thread,
}*/
#[cfg(target_os = "linux")]
pub fn set_affinity(thr_idxs: &[usize]) -> Result<(), ()> {
unsafe {
let mut cpuset = uninitialized();
CPU_ZERO(&mut cpuset);
for &thr_idx in thr_idxs {
CPU_SET(thr_idx, &mut cpuset);
}
let thread = pthread_self();
match pthread_setaffinity_np(thread, size_of_val(&cpuset), &cpuset as *const _) {
0 => Ok(()),
_ => Err(()),
}
}
}
pub enum CpuTopologySource {
Auto,
LinuxProcCpuinfo,
}
#[derive(Debug)]
pub struct CpuThreadInfo {
pub thr_idx: usize,
pub core_idx: usize,
pub proc_idx: usize,
}
#[derive(Debug)]
pub struct CpuTopology {
pub threads: Vec<CpuThreadInfo>,
}
impl CpuTopology {
pub fn query(source: CpuTopologySource) -> CpuTopology {
match source {
CpuTopologySource::Auto => {
unimplemented!();
}
CpuTopologySource::LinuxProcCpuinfo => {
Self::query_proc_cpuinfo()
}
}
}
fn query_proc_cpuinfo() -> CpuTopology {
let file = File::open(&PathBuf::from("/proc/cpuinfo"))
.unwrap();
let reader = BufReader::new(file);
//let mut thread_set = HashSet::new();
let mut threads = vec![];
let mut curr_thread = None;
for line in reader.lines() {
let line = line.unwrap();
if line.len() >= 9 && &line[ .. 9] == "processor" {
let toks: Vec<_> = line.splitn(2, ":").collect();
// Not assuming processor numbers are consecutive.
let thread_idx: usize = toks[1].trim().parse().unwrap();
//thread_set.insert(thread_idx);
if let Some(info) = curr_thread {
threads.push(info);
}
curr_thread = Some(CpuThreadInfo{
thr_idx: thread_idx,
core_idx: 0,
proc_idx: 0,
});
} else if line.len() >= 7 && &line[ .. 7] == "core id" {
let toks: Vec<_> = line.splitn(2, ":").collect();
let core_idx: usize = toks[1].trim().parse().unwrap();
if let Some(ref mut info) = curr_thread {
info.core_idx = core_idx;
}
} else if line.len() >= 11 && &line[ .. 11] == "physical id" {
let toks: Vec<_> = line.splitn(2, ":").collect();
let proc_idx: usize = toks[1].trim().parse().unwrap();
if let Some(ref mut info) = curr_thread {
info.proc_idx = proc_idx;
}
}
}
if let Some(info) = curr_thread {
threads.push(info);
}
//let num_threads = processor_set.len();
CpuTopology{
threads: threads,
}
}
pub fn num_threads(&self) -> usize {
self.threads.len()
}
}
| true |
fb51b6683054c4122e05bd60fe5ede509a3d103b
|
Rust
|
sbeckeriv/dex
|
/src/app/mod.rs
|
UTF-8
| 3,149 | 3.3125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
mod error;
mod pokemon;
mod style;
use error::Error;
use iced::{
button, Alignment, Application, Button, Column, Command, Container, Element, Length, Text,
};
use pokemon::Pokemon;
#[derive(Debug)]
pub enum Pokedex {
Loading,
Loaded {
pokemon: Pokemon,
search: button::State,
},
Errored {
error: Error,
try_again: button::State,
},
}
#[derive(Debug, Clone)]
pub enum Message {
PokémonFound(Result<Pokemon, Error>),
Search,
}
impl Application for Pokedex {
type Executor = iced::executor::Default;
type Message = Message;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(
Self::Loading,
Command::perform(Pokemon::search(), Message::PokémonFound),
)
}
fn title(&self) -> String {
let subtitle = match self {
Self::Loading => "Loading",
Self::Loaded { pokemon, .. } => &pokemon.name,
Self::Errored { .. } => "Whoops!",
};
format!("Pok\u{e9}dex - {}", subtitle)
}
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::PokémonFound(Ok(pokemon)) => {
*self = Self::Loaded {
pokemon,
search: button::State::new(),
};
Command::none()
}
Message::PokémonFound(Err(error)) => {
*self = Self::Errored {
error,
try_again: button::State::new(),
};
Command::none()
}
Message::Search => {
if let Self::Loading = self {
Command::none()
} else {
*self = Self::Loading;
Command::perform(Pokemon::search(), Message::PokémonFound)
}
}
}
}
fn view(&mut self) -> Element<Message> {
let content = match self {
Self::Loading => Column::new()
.width(Length::Shrink)
.push(Text::new("Searching for Pok\u{e9}mon...").size(40)),
Self::Loaded { pokemon, search } => Column::new()
.max_width(500)
.spacing(20)
.align_items(Alignment::End)
.push(pokemon.view())
.push(button(search, "Keep searching!").on_press(Message::Search)),
Self::Errored { try_again, .. } => Column::new()
.spacing(20)
.align_items(Alignment::End)
.push(Text::new("Whoops! Something went wrong...").size(40))
.push(button(try_again, "Try again").on_press(Message::Search)),
};
Container::new(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
}
}
fn button<'a>(state: &'a mut button::State, text: &str) -> Button<'a, Message> {
Button::new(state, Text::new(text))
.padding(10)
.style(style::Button::Primary)
}
| true |
4f2ae26f3aacf1d4e12313867cd19177ef29110b
|
Rust
|
pitcer/brucket
|
/c-generator/src/syntax/c_struct.rs
|
UTF-8
| 3,141 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
use crate::generator::{GeneratorError, GeneratorResult, GeneratorState, IndentedGenerator};
use crate::syntax::instruction::VariableDeclaration;
use derive_more::Constructor;
#[derive(Debug, PartialEq, Constructor)]
pub struct CStruct {
name: String,
fields: Fields,
}
impl IndentedGenerator for CStruct {
#[inline]
fn generate_indented(self, state: &GeneratorState) -> GeneratorResult {
let indentation = &state.indentation;
let incremented_indentation = state.indentation.to_incremented();
let state = GeneratorState::new(incremented_indentation);
Ok(format!(
"{}struct {} {{\n{}\n{}}};",
indentation,
self.name,
self.fields.generate_indented(&state)?,
indentation
))
}
}
pub type Fields = Vec<VariableDeclaration>;
impl IndentedGenerator for Fields {
#[inline]
fn generate_indented(self, state: &GeneratorState) -> GeneratorResult {
Ok(self
.into_iter()
.map(|field| field.generate_indented(state))
.collect::<Result<Vec<String>, GeneratorError>>()?
.join("\n"))
}
}
#[cfg(test)]
mod test {
use crate::syntax::c_type::{CPrimitiveType, CType};
use crate::syntax::modifiers::Modifier;
use crate::syntax::TestResult;
use super::*;
#[test]
fn test_generate_fields() -> TestResult {
assert_eq!(
"const int a;\nint b;\nint c;",
vec![
VariableDeclaration::new(
vec![Modifier::Const],
CType::Primitive(CPrimitiveType::Int),
"a".to_owned()
),
VariableDeclaration::new(
vec![],
CType::Primitive(CPrimitiveType::Int),
"b".to_owned()
),
VariableDeclaration::new(
vec![],
CType::Primitive(CPrimitiveType::Int),
"c".to_owned()
)
]
.generate_indented(&GeneratorState::default())?
);
Ok(())
}
#[test]
fn test_generate_struct() -> TestResult {
assert_eq!(
"struct foobar {\n const int a;\n int b;\n int c;\n};",
CStruct::new(
"foobar".to_owned(),
vec![
VariableDeclaration::new(
vec![Modifier::Const],
CType::Primitive(CPrimitiveType::Int),
"a".to_owned()
),
VariableDeclaration::new(
vec![],
CType::Primitive(CPrimitiveType::Int),
"b".to_owned()
),
VariableDeclaration::new(
vec![],
CType::Primitive(CPrimitiveType::Int),
"c".to_owned()
)
]
)
.generate_indented(&GeneratorState::default())?
);
Ok(())
}
}
| true |
3ccef59cbe0cd896e9356a4fcf1d782c11ab34c2
|
Rust
|
naamancurtis/rust_data_structures_and_algorithms
|
/sorting/src/insertion_sort.rs
|
UTF-8
| 2,439 | 4.28125 | 4 |
[
"MIT"
] |
permissive
|
//! # Insertion Sort
//!
//! Is a simple sorting algorithm that builds the sorted array one element at a time by maintaining a sorted
//! sub-array into which elements are inserted.
//!
//! - Time Complexity: **O**(n<sup>2</sup>)
//! - Space Complexity: **O**( _log_(n) )
use std::cmp::Ordering;
/// Shorthand helper function which carries out sorting of a slice of `T` _where_ `T: Ord`
///
/// # Examples
/// ```rust
/// use sorting::insertion_sort::insertion_sort;
///
/// let mut arr = vec![37, 45, 29, 8];
/// insertion_sort(&mut arr);
/// assert_eq!(arr, [8, 29, 37, 45]);
/// ```
pub fn insertion_sort<T>(arr: &mut [T])
where
T: Ord,
{
insertion_sort_by(arr, &|x, y| x.cmp(y))
}
/// Carries out sorting of a slice of `T` using the provided comparator function `F`
///
/// # Examples
/// ```rust
/// use sorting::insertion_sort::insertion_sort_by;
///
/// let mut arr = vec![37, 45, 29, 8 ,10];
/// insertion_sort_by(&mut arr, &|x, y| x.cmp(y));
/// assert_eq!(arr, [8, 10, 29, 37, 45]);
/// ```
pub fn insertion_sort_by<T, F>(arr: &mut [T], cmp: &F)
where
F: Fn(&T, &T) -> Ordering,
{
if arr.is_empty() {
return;
}
for i in 1..arr.len() {
for j in (1..=i).rev() {
if cmp(&arr[j], &arr[j - 1]) == Ordering::Less {
arr.swap(j, j - 1);
} else {
break;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_semi_sorted() {
let mut arr = vec![1, 23, 2, 32, 29, 33];
insertion_sort(&mut arr);
assert_eq!(arr, [1, 2, 23, 29, 32, 33]);
}
#[test]
fn test_backwards() {
let mut arr = vec![50, 25, 10, 5, 1];
insertion_sort(&mut arr);
assert_eq!(arr, [1, 5, 10, 25, 50]);
}
#[test]
fn test_sorted() {
let mut arr = vec![1, 5, 10, 25, 50];
insertion_sort(&mut arr);
assert_eq!(arr, [1, 5, 10, 25, 50]);
}
#[test]
fn test_empty() {
let mut arr: Vec<u32> = vec![];
insertion_sort(&mut arr);
assert_eq!(arr, []);
}
#[test]
fn test_len_two() {
let mut arr = vec![5, 1];
insertion_sort(&mut arr);
assert_eq!(arr, [1, 5]);
}
#[test]
fn test_partially_sorted() {
let mut arr = vec![50, 75, 1, 1, 3, 4, 5, 6, 50];
insertion_sort(&mut arr);
assert_eq!(arr, [1, 1, 3, 4, 5, 6, 50, 50, 75]);
}
}
| true |
75e6ec41d57b2b916e9b24178f790cd732015af3
|
Rust
|
Iwancof/SECR
|
/riscv-rust/src/terminal.rs
|
UTF-8
| 747 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
/// Emulates terminal. It holds input/output data in buffer
/// transferred to/from `Emulator`.
pub trait Terminal {
/// Puts an output ascii byte data to output buffer.
/// The data is expected to be read by user program via `get_output()`
/// and be displayed to user.
fn put_byte(&mut self, value: u8);
/// Gets an output ascii byte data from output buffer.
/// This method returns zero if the buffer is empty.
fn get_output(&mut self) -> u8;
/// Puts an input ascii byte data to input buffer.
/// The data is expected to be read by `Emulator` via `get_input()`
/// and be handled.
fn put_input(&mut self, data: u8);
/// Gets an input ascii byte data from input buffer.
/// Used by `Emulator`.
fn get_input(&mut self) -> u8;
}
| true |
722a7a33904b12f0f16d1119e7b861b533edc412
|
Rust
|
sirkibsirkib/middleman
|
/src/structs.rs
|
UTF-8
| 17,075 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
use super::*;
use mio::{
*,
event::Evented,
};
use ::std::{
io,
io::{
Read,
Write,
ErrorKind,
},
time,
};
#[derive(Debug)]
pub struct Middleman {
stream: mio::net::TcpStream,
buf: Vec<u8>,
buf_occupancy: usize,
payload_bytes: Option<u32>,
}
impl Middleman { fn check_payload(&mut self) {
if self.payload_bytes.is_none() && self.buf_occupancy >= 4 {
self.payload_bytes = Some(
bincode::deserialize(&self.buf[..4])
.unwrap()
)
}
}
/// Create a new Middleman structure to wrap the given Mio TcpStream.
/// The Middleman implements `mio::Evented`, but delegates its functions to this given stream
/// As such, registering the Middleman and registering the TcpStream are anaologous.
pub fn new(stream: mio::net::TcpStream) -> Middleman {
Self {
stream: stream,
buf: Vec::with_capacity(128),
buf_occupancy: 0,
payload_bytes: None,
}
}
fn read_in(&mut self) -> Result<usize, io::Error> {
let mut total = 0;
loop {
let limit = (self.buf_occupancy + 64) + (self.buf_occupancy);
if self.buf.len() < limit {
self.buf.resize(limit, 0u8);
}
match self.stream.read(&mut self.buf[self.buf_occupancy..]) {
Ok(0) => return Ok(total),
Ok(bytes) => {
self.buf_occupancy += bytes;
total += bytes;
},
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
return Ok(total);
},
Err(e) => return Err(e),
};
}
}
/// Write the given message directly into the TcpStream. Returns `Err` variant if there
/// is a problem serializing or writing the message. The call returns Ok(()) once the bytes
/// are entirely written to the stream.
pub fn send<M: Message>(&mut self, m: &M) -> Result<(), SendError> {
self.send_packed(
& PackedMessage::new(m)?
)?;
Ok(())
}
/// See `send`. This variant can be useful to
/// avoid the overhead of repeatedly packing a message for whatever reason, eg: sending
/// the same message using multiple Middleman structs.
///
/// Note that this function does NOT check for internal consistency of the packed message.
/// So, if this message was constructed by a means other than `Packed::new`, then the
/// results may be unpredictable.
pub fn send_packed(&mut self, msg: & PackedMessage) -> Result<(), io::Error> {
self.stream.write_all(&msg.0)
}
/// Conume an iterator over some Message structs, sending them all in the order traversed (see `send`).
/// Returns (a,b) where a gives the total number of messages sent successfully and where b is Ok if
/// nothing goes wrong and an error otherwise. In the event of the first error, no more messages will be sent.
pub fn send_all<'m, I, M>(&'m mut self, msg_iter: I) -> (usize, Result<(), SendError>)
where
M: Message + 'm,
I: Iterator<Item = &'m M>,
{
let mut total = 0;
for msg in msg_iter {
match self.send(msg) {
Ok(_) => total += 1,
Err(e) => return (total, Err(e)),
}
}
(total, Ok(()))
}
/// See `send_all` and `send_packed`. This uses the message iterator from the former and
/// the packed messages from the latter.
pub fn send_all_packed<'m, I>(&'m mut self, packed_msg_iter: I) -> (usize, Result<(), io::Error>)
where
I: Iterator<Item = &'m PackedMessage>,
{
let mut total = 0;
for msg in packed_msg_iter {
match self.send_packed(msg) {
Ok(_) => total += 1,
Err(e) => return (total, Err(e)),
}
}
(total, Ok(()))
}
/// Attempt to dedserialize some data in the receiving buffer into a single
/// complete structure with the given type M. If there is insufficient data
/// at the moment, Ok(None) is returned.
///
/// As the type is provided by the reader, it is possible for the sent
/// message to be misinterpreted as a different type. At best, this is detected
/// by a failure in deserialization. If an error occurs, the data is not consumed
/// from the Middleman. Subsequent reads will operate on the same data.
///
/// NOTE: The correctness of this call depends on the sender sending an _internally consistent_
/// `PackedMessage`. If you (or the sender) are manually manipulating the internal state of
/// sent messages this may cause errors for the receiver. If you are sticking to the Middleman API
/// and treating each `PackedMessage` as a black box, everything should be fine.
pub fn recv<M: Message>(&mut self) -> Result<Option<M>, RecvError> {
self.read_in()?;
self.check_payload();
if let Some(pb) = self.payload_bytes {
let buf_end = pb as usize + 4;
if self.buf_occupancy >= buf_end {
let decoded: M = bincode::deserialize(
&self.buf[4..buf_end]
)?;
self.payload_bytes = None;
self.buf.drain(0..buf_end);
self.buf_occupancy -= buf_end;
return Ok(Some(decoded))
}
}
Ok(None)
}
/// See `recv`. Will repeatedly call recv() until the next message is not yet ready.
/// Recevied messages are placed into the buffer `dest_vector`. The return result is (a,b)
/// where a is the total number of message successfully received and where b is OK(()) if all goes well
/// and some Err otherwise. In the event of the first error, the call will return and not receive any further.
pub fn recv_all_into<M: Message>(&mut self, dest_vector: &mut Vec<M>) -> (usize, Result<(), RecvError>) {
let mut total = 0;
loop {
match self.recv::<M>() {
Ok(None) => return (total, Ok(())),
Ok(Some(msg)) => { dest_vector.push(msg); total += 1; },
Err(e) => return (total, Err(e)),
};
}
}
/// Hijack the mio event loop, reading and writing to the socket as polling allows.
/// Events not related to the recv() of this middleman (determined from the provided mio::Token)
/// are pushed into the provided extra_events vector. Returns Ok(Some(_)) if a
/// message was successfully received. May return Ok(None) if the user provides as timeout some
// non-none Duration. Returns Err(_) if something goes wrong with reading from the socket or
/// deserializing the message. See try_recv for more information.
/// WARNING: The user should take care to iterate over these events also, as without them all the
/// Evented objects registered with the provided poll object might experience lost wakeups.
/// It is suggested that in the event of any recv_blocking calls in your loop, you extend the event
/// loop with a drain() on the same vector passed here as extra_events (using the iterator chain function, for example.)
pub fn recv_blocking<M: Message>(&mut self,
poll: &Poll,
events: &mut Events,
my_tok: Token,
extra_events: &mut Vec<Event>,
mut timeout: Option<time::Duration>) -> Result<Option<M>, RecvError> {
if let Some(msg) = self.recv::<M>()? {
// trivial case.
// message was already sitting in the buffer.
return Ok(Some(msg));
}
let started_at = time::Instant::now();
let mut res = None;
loop {
for event in events.iter() {
let tok = event.token();
if res.is_none() && tok == my_tok {
if ! event.readiness().is_readable() {
continue;
}
// event is relevant!
self.read_in()?;
match self.recv::<M>() {
Ok(Some(msg)) => {
// got a message!
res = Some(msg);
},
Ok(None) => (),
Err(e) => return Err(e),
}
} else {
extra_events.push(event);
}
}
if let Some(msg) = res {
// message ready to go. Exiting loop
return Ok(Some(msg));
} else {
poll.poll(events, timeout).expect("poll() failed inside `recv_blocking()`");
if let Some(t) = timeout {
// update remaining timeout
let since = started_at.elapsed();
if since >= t {
// ran out of time
return Ok(None);
}
timeout = Some(t-since);
}
}
}
}
/// See `recv_blocking`. This function is intended as an alternative for use
/// for cases where it is _certain_ that this Middleman is the only registered `mio::Evented`
/// for the provided `Poll` and `Events` objects. Thus, the call _WILL NOT CHECK_ the token at all,
/// presuming that all events are associated with this middleman.
pub fn recv_blocking_solo<M: Message>(&mut self,
poll: &Poll,
events: &mut Events,
mut timeout: Option<time::Duration>) -> Result<Option<M>, RecvError> {
if let Some(msg) = self.recv::<M>()? {
// trivial case.
// message was already sitting in the buffer.
return Ok(Some(msg));
}
let started_at = time::Instant::now();
loop {
for event in events.iter() {
if event.readiness().is_readable(){
// event is relevant!
self.read_in()?;
match self.recv::<M>() {
Ok(Some(msg)) => return Ok(Some(msg)),
Ok(None) => (),
Err(e) => return Err(e),
}
}
}
poll.poll(events, timeout).expect("poll() failed inside `recv_blocking_solo()`");
if let Some(t) = timeout {
// update remaining timeout
let since = started_at.elapsed();
if since >= t {
// ran out of time
return Ok(None);
}
timeout = Some(t-since);
}
}
}
/// Similar to `recv_all_into`, but rather than storing each received message 'm',
/// the provided function is called with arguments (self, m) where self is `&mut self`.
/// This allows for ergonomic utility of the received messages using a closure.
pub fn recv_all_map<F,M>(&mut self, mut func: F) -> (usize, Result<(), RecvError>)
where M: Message, F: FnMut(&mut Self, M) + Sized {
let mut total = 0;
loop {
match self.recv::<M>() {
Ok(None) => return (total, Ok(())),
Ok(Some(msg)) => { total += 1; func(self, msg) },
Err(e) => return (total, Err(e)),
};
}
}
/// Combination of `recv_all_map` and `recv_packed`.
pub fn recv_all_packed_map<F>(&mut self, mut func: F) -> (usize, Result<(), RecvError>)
where F: FnMut(&mut Self, PackedMessage) + Sized {
let mut total = 0;
loop {
match self.recv_packed() {
Ok(None) => return (total, Ok(())),
Ok(Some(packed)) => { total += 1; func(self, packed) },
Err(e) => return (total, Err(e)),
};
}
}
/// Similar to `recv`, except builds (instead of some M: Message), a `PackedMessage` object.
/// These packed messages can be deserialized later, sent on the line without knowledge of the
/// message type etc.
pub fn recv_packed(&mut self) -> Result<Option<PackedMessage>, RecvError> {
self.read_in()?;
self.check_payload();
if let Some(pb) = self.payload_bytes {
let buf_end = pb as usize + 4;
if self.buf_occupancy >= buf_end {
let mut vec = self.buf.drain(0..buf_end)
.collect::<Vec<_>>();
self.payload_bytes = None;
self.buf_occupancy -= buf_end;
return Ok(Some(PackedMessage(vec)))
}
}
Ok(None)
}
/// Similar to `recv_packed`, but the potentially-read bytes are not actually removed
/// from the stream. The message will _still be there_.
pub fn peek_packed(&mut self) -> Result<Option<PackedMessage>, RecvError> {
if let Some(pb) = self.payload_bytes {
let buf_end = pb as usize + 4;
if self.buf_occupancy >= buf_end {
return Ok(
Some(
PackedMessage::from_raw(
self.buf[4..buf_end].to_vec()
)
)
)
}
}
Ok(None)
}
}
/// This structure represents the serialized form of some `Message`-implementing structure.
/// Dealing with a PackedMessage may be suitable when:
/// (1) You need to send/store/receive a message but don't need to actually _use_ it yourself.
/// (2) You want to serialize a message once, and send it multiple times.
/// (3) You want to read and discard a message whose type is unknown.
///
/// NOTE: The packed message maps 1:1 with the bytes that travel over the TcpStream. As such,
/// packed messages also contain the 4-byte length preable. The user is discocuraged from
/// manipulating the contents of a packed message. The `recv` statement relies on consistency
/// of packed messages
pub struct PackedMessage(Vec<u8>);
impl PackedMessage {
/// Create a new PakcedMessage from the given `Message`-implementing struct
pub fn new<M: Message>(m: &M) -> Result<Self, PackingError> {
let m_len: usize = bincode::serialized_size(&m)? as usize;
if m_len > ::std::u32::MAX as usize {
return Err(PackingError::TooBigToRepresent);
}
let tot_len = m_len+4;
let mut vec = Vec::with_capacity(tot_len);
vec.resize(tot_len, 0u8);
bincode::serialize_into(&mut vec[0..4], &(m_len as u32))?;
bincode::serialize_into(&mut vec[4..tot_len], m)?;
Ok(PackedMessage(vec))
}
/// Attempt to unpack this Packedmessage given a type hint. This may fail if the
/// PackedMessage isn't internally consistent or the type doesn't match that
/// of the type used for serialization.
pub fn unpack<M: Message>(&self) -> Result<M, Box<bincode::ErrorKind>> {
bincode::deserialize(&self.0[4..])
}
/// Unwrap the byte buffer comprising this PackedMessage
#[inline] pub fn into_raw(self) -> Vec<u8> { self.0 }
/// Accept the given byte buffer as the basis for a PackedMessage
///
/// WARNING: Use this at your own risk! The `recv` functions and their variants rely on
/// the correct contents of messages to work correcty.
///
/// NOTE: The first 4 bytes of a the buffer are used to store the length of the payload.
#[inline] pub fn from_raw(v: Vec<u8>) -> Self { PackedMessage(v) }
/// Return the number of bytes this packed message contains. Maps 1:1 with
/// the bit complexity of the message sent over the network.
#[inline] pub fn byte_len(&self) -> usize { self.0.len() }
/// Acquire an immutable reference to the internal buffer of the packed message.
#[inline] pub fn get_raw(&self) -> &Vec<u8> { &self.0 }
/// Acquire a mutable reference to the internal buffer of the packed message.
///
/// WARNING: Contents of a PackedMessage represent a delicata internal state. Sending an
/// internally inconsistent PackedMessage will compromise the connection. Use at your own risk!
#[inline] pub fn get_mut_raw(&mut self) -> &mut Vec<u8> { &mut self.0 }
}
impl Evented for Middleman {
fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt)
-> io::Result<()> {
self.stream.register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt)
-> io::Result<()> {
self.stream.reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
self.stream.deregister(poll)
}
}
| true |
534738c930cb9798e38a845fb74c54ebbf1b5704
|
Rust
|
gengteng/impl-leetcode-for-rust
|
/src/three_sum.rs
|
UTF-8
| 1,618 | 3.859375 | 4 |
[
"MIT"
] |
permissive
|
/// # 15. 3Sum
///
/// Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
///
/// # Note:
///
/// The solution set must not contain duplicate triplets.
///
/// # Example:
///
/// Given array nums = [-1, 0, 1, 2, -1, -4],
///
/// A solution set is:
/// [
/// [-1, 0, 1],
/// [-1, -1, 2]
/// ]
///
use std::collections::HashSet;
pub trait ThreeSum {
fn three_sum(nums: &[i32]) -> HashSet<[i32;3]>;
}
pub struct Solution1;
impl ThreeSum for Solution1 {
fn three_sum(nums: &[i32]) -> HashSet<[i32;3]> {
let mut result = HashSet::new();
for (i, a) in nums.iter().enumerate() {
for (j, b) in nums.iter().skip(i + 1).enumerate() {
for c in nums.iter().skip(i + j + 2) {
if a + b + c == 0 {
let mut v = [*a, *b, *c];
v.sort();
result.insert(v);
}
}
}
}
result
}
}
#[cfg(test)]
mod test {
use super::ThreeSum;
use test::Bencher;
use super::Solution1;
#[test]
fn test_solution1() {
use std::collections::HashSet;
assert_eq!(Solution1::three_sum(&[-1, 0, 1, 2, -1, -4]), {
let mut result = HashSet::new();
result.insert([-1, 0, 1]);
result.insert([-1, -1, 2]);
result
});
}
#[bench]
fn bench_solution1(b: &mut Bencher) {
b.iter(|| Solution1::three_sum(&[-1, 0, 1, 2, -1, -4]));
}
}
| true |
025a08ef28a850e3a7ede38d3f00a1b48980fc47
|
Rust
|
rusty-ecma/resast
|
/src/pat.rs
|
UTF-8
| 2,954 | 3.265625 | 3 |
[] |
no_license
|
use crate::expr::{Expr, Prop};
use crate::{Ident, IntoAllocated};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// All of the different ways you can declare an identifier
/// and/or value
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum Pat<T> {
Ident(Ident<T>),
Obj(ObjPat<T>),
Array(Vec<Option<ArrayPatPart<T>>>),
RestElement(Box<Pat<T>>),
Assign(AssignPat<T>),
}
impl<T> IntoAllocated for Pat<T>
where
T: ToString,
{
type Allocated = Pat<String>;
fn into_allocated(self) -> Self::Allocated {
match self {
Pat::Ident(inner) => Pat::Ident(inner.into_allocated()),
Pat::Obj(inner) => Pat::Obj(inner.into_iter().map(|a| a.into_allocated()).collect()),
Pat::Array(inner) => Pat::Array(
inner
.into_iter()
.map(|o| o.map(|a| a.into_allocated()))
.collect(),
),
Pat::RestElement(inner) => Pat::RestElement(inner.into_allocated()),
Pat::Assign(inner) => Pat::Assign(inner.into_allocated()),
}
}
}
impl<T> Pat<T> {
pub fn ident_from(inner: T) -> Self {
Self::Ident(Ident { name: inner })
}
}
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum ArrayPatPart<T> {
Pat(Pat<T>),
Expr(Expr<T>),
}
impl<T> IntoAllocated for ArrayPatPart<T>
where
T: ToString,
{
type Allocated = ArrayPatPart<String>;
fn into_allocated(self) -> Self::Allocated {
match self {
ArrayPatPart::Pat(inner) => ArrayPatPart::Pat(inner.into_allocated()),
ArrayPatPart::Expr(inner) => ArrayPatPart::Expr(inner.into_allocated()),
}
}
}
/// similar to an `ObjectExpr`
pub type ObjPat<T> = Vec<ObjPatPart<T>>;
/// A single part of an ObjectPat
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum ObjPatPart<T> {
Assign(Prop<T>),
Rest(Box<Pat<T>>),
}
impl<T> IntoAllocated for ObjPatPart<T>
where
T: ToString,
{
type Allocated = ObjPatPart<String>;
fn into_allocated(self) -> Self::Allocated {
match self {
ObjPatPart::Assign(inner) => ObjPatPart::Assign(inner.into_allocated()),
ObjPatPart::Rest(inner) => ObjPatPart::Rest(inner.into_allocated()),
}
}
}
/// An assignment as a pattern
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct AssignPat<T> {
pub left: Box<Pat<T>>,
pub right: Box<Expr<T>>,
}
impl<T> IntoAllocated for AssignPat<T>
where
T: ToString,
{
type Allocated = AssignPat<String>;
fn into_allocated(self) -> Self::Allocated {
AssignPat {
left: self.left.into_allocated(),
right: self.right.into_allocated(),
}
}
}
| true |
2eb8609523eddcfcf9aaec109460477cbf7759ea
|
Rust
|
dan-sf/advent_of_code
|
/2018/day2/solution2.rs
|
UTF-8
| 1,131 | 3.21875 | 3 |
[] |
no_license
|
use std::fs;
use std::io;
use std::io::BufRead;
fn get_common_chars(box_one: &String, box_two: &String) -> String {
box_one.chars()
.zip(box_two.chars())
.filter(|ch| ch.0 == ch.1)
.map(|ch| ch.0)
.collect()
}
fn find_common_id() -> Option<String> {
let input = fs::File::open("input.txt")
.expect("Something went wrong reading the file");
let reader = io::BufReader::new(input);
let mut box_ids: Vec<String> = reader.lines().map(|l| l.unwrap()).collect();
box_ids.sort();
for i in 0..box_ids.len() {
let mut diff = 0;
if i != box_ids.len() - 1 {
for (a, b) in box_ids[i].chars().zip(box_ids[i+1].chars()) {
if a != b {
diff += 1;
}
}
if diff == 1 {
return Some(get_common_chars(&box_ids[i], &box_ids[i+1]));
}
}
}
None
}
fn main() {
println!("Common letters in the box ids: {}",
match find_common_id() {
Some(s) => s,
None => "NA".to_string()
});
}
| true |
e13c33e5a575f4ab435f01914a81c74b1033ae9a
|
Rust
|
xiaolang315/json-schema-to-c
|
/src/main.rs
|
UTF-8
| 1,037 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
// use std::process::Command;
use std::fs::read_to_string;
use std::fs::write;
use serde_json::from_str;
use serde_json::{Value};
fn make_str(body:String)->String {
let head = String::from(r#"
#ifdef __cplusplus
extern "C" {
#endif "#);
let tail = String::from(r#"
#ifdef __cplusplus
}
#endif
"#);
return head + &body + &tail;
}
fn main() {
// let mut echo_hello = Command::new("sh");
// let ret = echo_hello.arg("-c").arg("ls").output();
// println!("结果:{:?}",ret);
// let file = File::open( "./src/schema.json").unwrap();
// println!("文件打开成功:{:?}",file);
let contents:String = read_to_string("./src/schema.json").unwrap();
let v: Value = from_str(&contents).unwrap();
println!("Please call {} at the number {}", v["type"], v["id"]);
let body = String::from(r#"
typedef struct All{
char name[100];
int value;
}All ;
All parser_print(const char* str);
"#);
write("./src/demo.h", make_str(body))
.unwrap();
}
#[test]
fn test(){
}
| true |
27c9d7ded1cb3ebf884c97949751989c6f27c507
|
Rust
|
rudib/axess
|
/axess_gui/src/windows/keyboard.rs
|
UTF-8
| 6,231 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
use std::{borrow::Cow, fmt::Display};
use axess_core::payload::{DeviceState, UiPayload};
use packed_struct::PrimitiveEnum;
use crate::config::AxessConfiguration;
#[derive(Debug, Copy, Clone)]
pub enum UiEvent {
KeyDown(usize, u32),
KeyUp(usize, u32)
}
#[derive(Default, Debug)]
pub struct KeyboardState {
ctrl: bool
}
#[derive(Debug, Copy, Clone)]
pub enum KeyboardCombination {
Key(usize),
CtrlKey(usize)
}
impl KeyboardState {
pub fn handle_event(&mut self, ev: &UiEvent) -> Option<KeyboardCombination> {
const CTRL: usize = 0x11;
//const ALT: usize = 0x12;
match *ev {
UiEvent::KeyDown(CTRL, _) => {
self.ctrl = true;
}
UiEvent::KeyUp(CTRL, _) => {
self.ctrl = false;
}
UiEvent::KeyDown(k, _) => {
// todo: ignore repeats?
if self.ctrl {
return Some(KeyboardCombination::CtrlKey(k));
} else {
return Some(KeyboardCombination::Key(k));
}
},
UiEvent::KeyUp(_, _) => {}
}
None
}
}
#[derive(Debug, Copy, Clone, PartialEq, PrimitiveEnum)]
pub enum Keys {
Enter = 13,
PageUp = 33,
PageDown = 34,
Space = 32,
Tab = 9,
Number0 = 48,
Number1 = 49,
Number2 = 50,
Number3 = 51,
Number4 = 52,
Number5 = 53,
Number6 = 54,
Number7 = 55,
Number8 = 56,
Number9 = 57,
Fn1 = 0x70,
Fn2 = 0x71,
Fn3 = 0x72,
Fn4 = 0x73,
Fn5 = 0x74,
Fn6 = 0x75,
Fn7 = 0x76,
Fn8 = 0x77,
Fn9 = 0x78,
Fn10 = 0x79,
Fn11 = 0x7A,
Fn12 = 0x7B,
Fn13 = 0x7C,
Fn14 = 0x7D,
Fn15 = 0x7E,
Fn16 = 0x7F
}
impl Display for Keys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let str = match self {
Keys::Number0 => "0",
Keys::Number1 => "1",
Keys::Number2 => "2",
Keys::Number3 => "3",
Keys::Number4 => "4",
Keys::Number5 => "5",
Keys::Number6 => "6",
Keys::Number7 => "7",
Keys::Number8 => "8",
Keys::Number9 => "9",
Keys::PageUp => "Page Up",
Keys::PageDown => "Page Down",
Keys::Fn1 => "F1",
Keys::Fn2 => "F2",
Keys::Fn3 => "F3",
Keys::Fn4 => "F4",
Keys::Fn5 => "F5",
Keys::Fn6 => "F6",
Keys::Fn7 => "F7",
Keys::Fn8 => "F8",
Keys::Fn9 => "F9",
Keys::Fn10 => "F10",
Keys::Fn11 => "F11",
Keys::Fn12 => "F12",
Keys::Fn13 => "F13",
Keys::Fn14 => "F14",
Keys::Fn15 => "F15",
Keys::Fn16 => "F16",
_ => { return f.write_fmt(format_args!("{:?}", self)); }
};
f.write_str(str)
}
}
#[derive(Debug, Clone)]
pub struct KeyboardShortcut {
pub key: KeyboardShortcutKey,
pub command_description: Cow<'static, str>,
pub command: ShortcutCommand
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum KeyboardShortcutKey {
Key(Keys),
CtrlKey(Keys)
}
impl Display for KeyboardShortcutKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KeyboardShortcutKey::Key(k) => {
k.fmt(f)
}
KeyboardShortcutKey::CtrlKey(k) => {
f.write_str("Ctrl + ")?;
k.fmt(f)
}
}
}
}
#[derive(Debug, Clone)]
pub enum ShortcutCommand {
UiPayload(UiPayload),
SelectPresetOrScene
}
pub fn get_main_keyboard_shortcuts(config: &AxessConfiguration) -> Vec<KeyboardShortcut> {
let mut s = vec![
KeyboardShortcut {
key: KeyboardShortcutKey::Key(Keys::Enter),
command_description: "Select the preset or scene".into(),
command: ShortcutCommand::SelectPresetOrScene
}
];
if config.keyboard_shortcuts_axe_edit {
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::CtrlKey(Keys::PageUp),
command_description: "Preset Up".into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: 1 }))
});
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::CtrlKey(Keys::PageDown),
command_description: "Preset Down".into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: -1 }))
});
for i in 0..8 {
let key = Keys::from_primitive(Keys::Number1.to_primitive() + i);
if let Some(key) = key {
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::CtrlKey(key),
command_description: format!("Select Scene {}", i + 1).into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::SetScene { scene: i }))
});
}
}
}
if config.keyboard_shortcuts_presets_and_scenes_function_keys {
for i in 0..8 {
let key = Keys::from_primitive(Keys::Fn1.to_primitive() + i);
if let Some(key) = key {
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::Key(key),
command_description: format!("Select Scene {}", i + 1).into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::SetScene { scene: i }))
});
}
}
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::Key(Keys::Fn11),
command_description: "Preset Down".into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: -1 }))
});
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::Key(Keys::Fn12),
command_description: "Preset Up".into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: 1 }))
});
}
s
}
| true |
d8f7063a021efc499a4e1676623450e539b4a860
|
Rust
|
simon-whitehead/tetrs
|
/src/game/scoring/score.rs
|
UTF-8
| 1,983 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
use piston_window::{Graphics, Transformed};
use piston_window::character::CharacterCache;
use game::config::Config;
use game::render_options::RenderOptions;
pub struct Score {
score: u32,
location: (f64, f64),
color: [f32; 4],
font_size: u32,
}
impl Score {
pub fn new(config: &Config) -> Score {
Score {
score: 0,
location: (320.0, 29.0),
color: config.ui_color,
font_size: 16,
}
}
pub fn add(&mut self, value: u32) {
self.score += value;
}
pub fn render<'a, C, G>(&self, options: &mut RenderOptions<'a, G, C>)
where C: CharacterCache,
G: Graphics<Texture = <C as CharacterCache>::Texture>
{
let score_label_transform = options.context
.transform
.trans(self.location.0 as f64, self.location.1 as f64);
let score_number_transform = options.context
.transform
.trans(self.location.0 as f64,
self.location.1 + (self.font_size + (self.font_size / 3)) as f64);
let score = format!("{}", self.score);
::piston_window::Text::new_color(self.color, self.font_size - (self.font_size / 3))
.draw("Score",
options.character_cache,
&options.context.draw_state,
score_label_transform,
options.graphics);
::piston_window::Text::new_color(self.color, self.font_size).draw(&score[..],
options.character_cache,
&options.context
.draw_state,
score_number_transform,
options.graphics);
}
}
| true |
fe91a6ee5a258a2447a117eae677decb355d72c6
|
Rust
|
enso-org/enso
|
/lib/rust/ensogl/component/text/src/buffer/rope/formatted.rs
|
UTF-8
| 2,010 | 3.375 | 3 |
[
"AGPL-3.0-only",
"Apache-2.0",
"AGPL-3.0-or-later"
] |
permissive
|
//! A rope (efficient text representation) with formatting information.
use crate::prelude::*;
use crate::buffer::formatting::Formatting;
use crate::buffer::formatting::FormattingCell;
use enso_text::Rope;
use enso_text::RopeCell;
// =====================
// === FormattedRope ===
// =====================
/// A rope (efficient text representation) with formatting information.
#[derive(Clone, CloneRef, Debug, Default, Deref)]
pub struct FormattedRope {
data: Rc<FormattedRopeData>,
}
impl FormattedRope {
/// Constructor.
pub fn new() -> Self {
default()
}
/// Replace the content of the buffer with the provided text.
pub fn replace(&self, range: impl enso_text::RangeBounds, text: impl Into<Rope>) {
let text = text.into();
let range = self.crop_byte_range(range);
let size = text.last_byte_index();
self.text.replace(range, text);
self.formatting.set_resize_with_default(range, size);
}
}
// =========================
// === FormattedRopeData ===
// =========================
/// Internal data of `FormattedRope`.
#[derive(Debug, Default, Deref)]
pub struct FormattedRopeData {
#[deref]
pub(crate) text: RopeCell,
pub(crate) formatting: FormattingCell,
}
impl FormattedRopeData {
/// Constructor.
pub fn new() -> Self {
default()
}
/// Rope getter.
pub fn text(&self) -> Rope {
self.text.get()
}
/// Rope setter.
pub fn set_text(&self, text: impl Into<Rope>) {
self.text.set(text);
}
/// Formatting getter.
pub fn style(&self) -> Formatting {
self.formatting.get()
}
/// Formatting setter.
pub fn set_style(&self, style: Formatting) {
self.formatting.set(style)
}
/// Query style information for the provided range.
pub fn sub_style(&self, range: impl enso_text::RangeBounds) -> Formatting {
let range = self.crop_byte_range(range);
self.formatting.sub(range)
}
}
| true |
3df1d52edb3fc2c5ab768b76f40b288745bc7613
|
Rust
|
rust-cc/rcmath
|
/src/utils.rs
|
UTF-8
| 576 | 3.265625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
#[derive(Debug)]
pub struct BitIterator<E> {
t: E,
n: usize,
}
impl<E: AsRef<[u64]>> BitIterator<E> {
pub fn new(t: E) -> Self {
let n = t.as_ref().len() * 64;
BitIterator { t, n }
}
}
impl<E: AsRef<[u64]>> Iterator for BitIterator<E> {
type Item = bool;
fn next(&mut self) -> Option<bool> {
if self.n == 0 {
None
} else {
self.n -= 1;
let part = self.n / 64;
let bit = self.n - (64 * part);
Some(self.t.as_ref()[part] & (1 << bit) > 0)
}
}
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.