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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3ef29f72441d020c35099a7f798aabe3d00095f7
|
Rust
|
Hirevo/alexandrie
|
/crates/alexandrie-rendering/src/config.rs
|
UTF-8
| 3,160
| 3.015625
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use syntect::dumps;
use syntect::highlighting::ThemeSet;
use syntect::parsing::SyntaxSet;
/// The syntax-highlighting themes configuration struct.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum SyntectThemesConfig {
/// Variant for loading themes from a binary dump.
Dump {
/// The path to the binary dump to load themes from.
path: PathBuf,
/// The name of the theme to use.
theme_name: String,
},
/// Variant for recursively loading themes from a directory.
Directory {
/// The path to the directory to load themes from.
path: PathBuf,
/// The name of the theme to use.
theme_name: String,
},
}
/// The syntax-highlighting syntaxes configuration struct.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum SyntectSyntaxesConfig {
/// Variant for loading syntaxes from a binary dump.
Dump {
/// The path to the binary dump to load syntaxes from.
path: PathBuf,
},
/// Variant for recursively loading syntaxes from a directory.
Directory {
/// The path to the directory to load syntaxes from.
path: PathBuf,
},
}
/// The complete syntax-highlighting configuration struct.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyntectConfig {
/// The highlighting themes configuration.
pub themes: SyntectThemesConfig,
/// The highlighting syntaxes configuration.
pub syntaxes: SyntectSyntaxesConfig,
}
/// The syntax-highlighting state struct, created from [SyntectConfig].
pub struct SyntectState {
/// The loaded syntax set.
pub syntaxes: SyntaxSet,
/// The loaded theme set.
pub themes: ThemeSet,
/// The chosen theme's name.
pub theme_name: String,
}
impl From<SyntectConfig> for SyntectState {
fn from(config: SyntectConfig) -> SyntectState {
let syntaxes = match config.syntaxes {
SyntectSyntaxesConfig::Dump { path } => {
dumps::from_dump_file(&path).expect("couldn't load syntaxes' dump file")
}
SyntectSyntaxesConfig::Directory { path } => {
SyntaxSet::load_from_folder(&path).expect("couldn't load syntaxes from directory")
}
};
let (themes, theme_name) = match config.themes {
SyntectThemesConfig::Dump { path, theme_name } => (
dumps::from_dump_file(&path).expect("couldn't load themes' dump"),
theme_name,
),
SyntectThemesConfig::Directory { path, theme_name } => (
ThemeSet::load_from_folder(&path).expect("couldn't load themes from directory"),
theme_name,
),
};
if !themes.themes.contains_key(theme_name.as_str()) {
panic!("no theme named '{0}' has been found", theme_name);
}
SyntectState {
syntaxes,
themes,
theme_name,
}
}
}
| true
|
c3b2fb5f5fbf88430379b504a15e2c10922a18a1
|
Rust
|
HerringtonDarkholme/leetcode
|
/src/count_binary_substrings.rs
|
UTF-8
| 564
| 2.796875
| 3
|
[] |
no_license
|
pub struct Solution;
impl Solution {
pub fn count_binary_substrings(s: String) -> i32 {
let s = s.as_bytes();
let mut ret = 0;
let mut preced = 0;
let mut after = 1;
let mut last_c = s[0];
for &c in s[1..].iter() {
if c == last_c {
after += 1;
continue;
}
ret += std::cmp::min(preced, after);
preced = after;
last_c = c;
after = 1;
}
ret += std::cmp::min(preced, after);
ret
}
}
| true
|
0c708eea75557fafe3f3515cce1f66e835b57c30
|
Rust
|
sile/bytecodec
|
/src/padding.rs
|
UTF-8
| 3,879
| 3.703125
| 4
|
[
"MIT"
] |
permissive
|
//! Encoder and decoder for padding bytes.
use crate::{ByteCount, Decode, Encode, Eos, ErrorKind, Result};
/// Decoder for reading padding bytes from input streams.
///
/// `PaddingDecoder` discards any bytes in a stream until it reaches EOS.
#[derive(Debug, Default)]
pub struct PaddingDecoder {
expected_byte: Option<u8>,
eos: bool,
}
impl PaddingDecoder {
/// Makes a new `PaddingDecoder` instance.
pub fn new(expected_byte: Option<u8>) -> Self {
PaddingDecoder {
expected_byte,
eos: false,
}
}
/// Returns the expected byte used for padding.
///
/// `None` means that this decoder accepts any bytes.
pub fn expected_byte(&self) -> Option<u8> {
self.expected_byte
}
/// Sets the expected byte used for padding.
pub fn set_expected_byte(&mut self, b: Option<u8>) {
self.expected_byte = b;
}
}
impl Decode for PaddingDecoder {
type Item = ();
fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> {
if self.eos {
Ok(0)
} else if let Some(expected) = self.expected_byte {
for &padding_byte in buf {
track_assert_eq!(padding_byte, expected, ErrorKind::InvalidInput);
}
self.eos = eos.is_reached();
Ok(buf.len())
} else {
self.eos = eos.is_reached();
Ok(buf.len())
}
}
fn finish_decoding(&mut self) -> Result<Self::Item> {
track_assert!(self.eos, ErrorKind::IncompleteDecoding);
self.eos = false;
Ok(())
}
fn is_idle(&self) -> bool {
self.eos
}
fn requiring_bytes(&self) -> ByteCount {
if self.eos {
ByteCount::Finite(0)
} else {
ByteCount::Infinite
}
}
}
/// Encoder for writing padding bytes to output streams.
///
/// After `start_encoding` is called, it will write the specified padding byte repeatedly
/// until it the output stream reaches EOS.
#[derive(Debug, Default)]
pub struct PaddingEncoder {
padding_byte: Option<u8>,
}
impl PaddingEncoder {
/// Makes a new `PaddingEncoder` instance.
pub fn new() -> Self {
Self::default()
}
}
impl Encode for PaddingEncoder {
type Item = u8;
fn encode(&mut self, buf: &mut [u8], eos: Eos) -> Result<usize> {
if let Some(padding_byte) = self.padding_byte {
let n = buf.len();
for b in buf {
*b = padding_byte
}
if eos.is_reached() {
self.padding_byte = None;
}
Ok(n)
} else {
Ok(0)
}
}
fn start_encoding(&mut self, item: Self::Item) -> Result<()> {
track_assert!(self.is_idle(), ErrorKind::EncoderFull);
self.padding_byte = Some(item);
Ok(())
}
fn requiring_bytes(&self) -> ByteCount {
if self.is_idle() {
ByteCount::Finite(0)
} else {
ByteCount::Infinite
}
}
fn is_idle(&self) -> bool {
self.padding_byte.is_none()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::io::IoDecodeExt;
use crate::{Encode, EncodeExt, Eos};
#[test]
fn padding_encoder_works() {
let mut encoder = track_try_unwrap!(PaddingEncoder::with_item(3));
let mut buf = [0; 8];
track_try_unwrap!(encoder.encode(&mut buf[..], Eos::new(true)));
assert_eq!(buf, [3; 8]);
assert!(encoder.is_idle());
}
#[test]
fn padding_decoder_works() {
let mut decoder = PaddingDecoder::new(None);
assert!(decoder.decode_exact(&[0; 8][..]).is_ok());
let mut decoder = PaddingDecoder::new(Some(1));
assert!(decoder.decode_exact(&[1; 8][..]).is_ok());
assert!(decoder.decode_exact(&[0; 8][..]).is_err());
}
}
| true
|
000556ccf27a9f01b6b4cb0c92082019388e4b92
|
Rust
|
AnthonyMeehan/CartesianGeneticProgrammingRust
|
/cgprs/src/dataset.rs
|
UTF-8
| 2,804
| 3.375
| 3
|
[] |
no_license
|
extern crate csv; // for CSV parsing
use std::fs::File;
use std::io::{BufReader, BufRead};
///A series of input examples matched-up with output examples, for testing CGP genomes
pub struct Dataset {
pub input_examples: Vec<f64>,
pub output_examples: Vec<f64>,
}
///Extracts a dataset from a CSV, using a CSV library
pub fn dataset_from_csv(filename: String) -> Dataset {
//Try and load the file
let mut reader = csv::Reader::from_file(filename).unwrap().has_headers(false);
let mut the_dataset = Dataset {
input_examples: Vec::new(),
output_examples: Vec::new(),
};
//Extract CSV contents into dataset
for record in reader.decode() {
let (input_example, output_example): (f64, f64) = record.unwrap(); //Unwrapped replaces wrapped
the_dataset.input_examples.push(input_example);
the_dataset.output_examples.push(output_example);
println!("({}, {})", input_example, output_example);
}
return the_dataset;
}
///Extracts a dataset from a CSV, without using any dependencies
pub fn dataset_from_csv_no_dependencies(filename: String) -> Dataset {
//Try and load the file
let the_file = match File::open(&filename) {
Ok(f) => f,
Err(e) => panic!("Could not find file: {} \n{}", filename, e),
};
let the_reader = BufReader::new(the_file);
let mut the_dataset = Dataset {
input_examples: Vec::new(),
output_examples: Vec::new(),
};
//Extract CSV contents into dataset
for line in the_reader.lines() {
let mut examples = match line {
Ok(ref l) => l.split(","),
Err(e) => panic!(e)
};
let input_example = examples.next().unwrap().trim().parse().expect("float needed from first CSV column");
let output_example = examples.next().unwrap().trim().parse().expect("float needed from second CSV column");
the_dataset.input_examples.push(input_example);
the_dataset.output_examples.push(output_example);
println!("({}, {})", input_example, output_example);
}
return the_dataset;
}
///Check that the data extractors work correctly on a test dataset
#[test]
fn test_dataset() {
println!(file!());
let datasets = vec![
dataset_from_csv_no_dependencies(String::from("src\\sin.csv")),
dataset_from_csv(String::from("src\\sin.csv")),
];
for dataset in datasets {
assert_eq!(dataset.input_examples[0], 0.0);
assert_eq!(dataset.output_examples[0], 0.0);
assert_eq!(dataset.input_examples[1], 0.1);
assert_eq!(dataset.output_examples[1], 0.0998334166468282);
assert_eq!(*dataset.input_examples.last().unwrap(), 6.2);
assert_eq!(*dataset.output_examples.last().unwrap(), -0.0830894028174964);
}
}
| true
|
26b73fbbddf5c3cf15461f51f7c58c62890173af
|
Rust
|
DeTeam/advent-2018
|
/day2/src/main.rs
|
UTF-8
| 1,841
| 3.609375
| 4
|
[] |
no_license
|
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
fn get_score(s: &str) -> (bool, bool) {
let mut letters = HashMap::new();
for c in s.chars() {
let counter = letters.entry(c).or_insert(0);
*counter += 1;
}
let collected_values: Vec<_> = letters.values().collect();
let mut values = collected_values.clone();
values.sort();
values.dedup();
let final_values = values.clone();
// OMG, refactor that part and understand the whole function better
(final_values.contains(&&2), final_values.contains(&&3))
}
fn task1(s: &str) {
let lines = s.lines();
let mut threes = 0;
let mut twos = 0;
for line in lines {
let result = get_score(line);
twos = if result.0 { twos + 1 } else { twos };
threes = if result.1 { threes + 1 } else { threes };
}
let result = threes * twos;
println!("First task result: {}", result);
}
fn get_common_part(s1: &str, s2: &str) -> String {
let mut result = String::new();
for (c1, c2) in s1.chars().zip(s2.chars()) {
if c1 == c2 {
result.push(c1);
}
}
result
}
fn task2(s: &str) {
let lines = s.lines();
'outer: for (i, l1) in lines.clone().enumerate() {
let other_lines = lines.clone().skip(i);
for l2 in other_lines {
let common_part = &get_common_part(l1, l2);
if l1.len() - common_part.len() == 1 {
println!("Common part: {}", common_part);
break 'outer;
}
}
}
}
fn main() {
let mut f = File::open("input.txt").expect("File not found");
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("something went wrong reading the file");
task1(&contents);
task2(&contents);
}
| true
|
3c8c3c00b27706b0e3c969d19a0d014a6cc93586
|
Rust
|
Ainevsia/Leetcode-Rust
|
/1044. Longest Duplicate Substring/src/main.rs
|
UTF-8
| 3,046
| 3.625
| 4
|
[
"BSD-2-Clause"
] |
permissive
|
fn main() {
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).expect("Failed to read line");
buf.pop();
// let buf: Vec<char> = buf.chars().collect();
// println!("buf[0] = {:#?}", buf[0]);
// println!("buf[buf.len()-1] = {:#?}", buf[buf.len()-1]);
println!("buf.len() = {:#?}", buf.len());
let s = Solution::longest_dup_substring(buf);
println!("s = {:#?}", s);
}
struct Solution {}
impl Solution {
pub fn longest_dup_substring(s: String) -> String {
if s.len() == 0 { return "".to_string() }
let mut l_max = s.len() - 1; // inclusive
let mut l_min = 2;
while l_min <= l_max {
let l = if l_max == l_min + 1 { l_max } else { (l_max + l_min) / 2 };
println!("l_min = {:#?}, l_max = {:#?}", l_min, l_max);
println!("l = {:#?}", l);
if let Some(substr) = Self::test(&s, l) {
l_min = l;
if l_max == l_min { return substr.to_owned() }
} else {
l_max = l - 1;
}
}
"".to_string()
}
pub fn test(s_: &str, l: usize) -> Option<&str> {
let s: Vec<usize> = s_.chars().map(|x| x as usize - 'a' as usize).collect();
use std::collections::HashSet;
let mut set: HashSet<usize> = HashSet::new();
let modu = 2usize.pow(63) - 1;
let p = Self::pow(26, l, modu);
println!("p = {:#?}", p);
let mut num = s.iter().take(l).fold(0, |sum, x| (sum*26 + x)%modu);
set.insert(num);
for tail in l..s.len() {
num = (num*26 + s[tail] - s[tail-l]*p)%modu;
if !set.insert(num) { return Some(&s_[tail-l+1..=tail]) }
}
None
}
pub fn pow(x: usize, mut y: usize, modu: usize) -> usize {
let mut res: u128 = x as u128;
while y > 1 {
// println!("res = {:#?}", res);
// println!("modu = {:#?}", modu);
// println!("res > modu = {:#?}", res > modu as u128);
res *= x as u128;
y -= 1;
if res > modu as u128 { res %= modu as u128 }
}
res as usize
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
assert_eq!(Solution::longest_dup_substring(String::from("ababa")), String::from("aba"));
assert_eq!(Solution::longest_dup_substring(String::from("abcd")), String::from(""));
assert_eq!(Solution::longest_dup_substring(String::from("abcdab")), String::from("ab"));
assert_eq!(Solution::longest_dup_substring(String::from("abc")), String::from(""));
assert_eq!(Solution::longest_dup_substring(String::from("")), String::from(""));
assert_eq!(Solution::longest_dup_substring(String::from("")), String::from(""));
}
#[test]
fn pow() {
assert_eq!(Solution::pow(2, 2, 3), 1);
assert_eq!(Solution::pow(26, 3, 33333333333), 17576);
assert_eq!(Solution::pow(26, 50000, 9223372036854775807), 8527440374548257796);
}
}
| true
|
cc0cf4f7e203653ff787fcd45c41ac549801f25d
|
Rust
|
paulkoerbitz/git-pivot
|
/src/statistics/punchcard.rs
|
UTF-8
| 1,823
| 2.953125
| 3
|
[] |
no_license
|
use chrono::prelude::*;
use git2::Commit;
use crate::statistics::PerCommitStatistic;
pub struct Punchcard {
punches: [[u32; 24]; 7],
}
impl Punchcard {
pub fn new() -> Punchcard {
Punchcard {
punches: [[0; 24]; 7]
}
}
fn commits_for_weekday(&self, weekday: &Weekday) -> &[u32; 24] {
&self.punches[weekday.num_days_from_monday() as usize]
}
fn at(&mut self, weekday: &Weekday, hour: u32) -> &mut u32 {
&mut self.punches[weekday.num_days_from_monday() as usize][hour as usize]
}
}
impl PerCommitStatistic for Punchcard {
fn process_commit(&mut self, commit: &Commit) -> () {
let ctime = commit.time();
let datetime = FixedOffset::east(ctime.offset_minutes() * 60).timestamp(ctime.seconds(), 0);
let count = self.at(&datetime.weekday(), datetime.hour());
*count += 1;
}
fn print_result(&self) -> () {
let header: Vec<String> = (0..24).map(|hour| { left_pad(hour, 5) }).collect();
println!("Punchcard");
println!("=========\n");
println!(" | {} |", header.join(" | "));
println!("----+-{}-+", &["-----"; 24].join("-+-"));
for day in &["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] {
let weekday = day.parse::<Weekday>().unwrap();
let commits: Vec<String> = self.commits_for_weekday(&weekday).into_iter().map(|hour| { left_pad(*hour, 5) }).collect();
println!(
"{} | {} |",
day,
commits.join(" | ")
);
}
}
}
fn left_pad(hour: u32, size: usize) -> String {
let hour = hour.to_string();
let mut result = String::new();
while hour.len() + result.len() < size {
result.push(' ');
}
result.push_str(&hour);
result
}
| true
|
19695be3616c7e424fa01f9cc74b2c8e311ecc5d
|
Rust
|
moshthepitt/vipers
|
/src/assert.rs
|
UTF-8
| 4,041
| 3.0625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//! Various assertions.
/// Asserts that two accounts share the same key.
#[macro_export]
macro_rules! assert_keys {
($account_a: expr, $account_b: expr $(,)?) => {
assert_keys!($account_a, $account_b, "key mismatch")
};
($account_a: expr, $account_b: expr, $msg: expr $(,)?) => {
let __account_a = anchor_lang::Key::key(&$account_a);
let __account_b = anchor_lang::Key::key(&$account_b);
if __account_a != __account_b {
msg!(
"Key mismatch: {}: {} (left) != {} (right)",
$msg,
__account_a,
__account_b
);
return Err($crate::VipersError::KeyMismatch.into());
}
};
}
/// Asserts that the ATA is the one of the given owner/mint.
#[macro_export]
macro_rules! assert_ata {
($ata: expr, $owner: expr, $mint: expr $(,)?) => {
assert_ata!($ata, $owner, $mint, "ata mismatch")
};
($ata: expr, $owner: expr, $mint: expr, $msg: expr $(,)?) => {
let __owner = anchor_lang::Key::key(&$owner);
let __mint = anchor_lang::Key::key(&$mint);
let __ata = anchor_lang::Key::key(&$ata);
let __real_ata =
spl_associated_token_account::get_associated_token_address(&__owner, &__mint);
if __real_ata != __ata {
msg!(
"ATA mismatch: {}: {} (left) != {} (right)",
$msg,
__ata,
__real_ata
);
msg!("Owner: {}", __owner);
msg!("Mint: {}", __mint);
return Err($crate::VipersError::ATAMismatch.into());
}
};
}
/// Asserts that the account match the program id.
#[macro_export]
macro_rules! assert_program {
($account_a: expr, $program_id: tt $(,)?) => {
let __account_a = anchor_lang::Key::key(&$account_a);
let __program_id: Pubkey = $crate::program_ids::$program_id;
if __account_a != __program_id {
msg!(
"Program ID mismatch: expected {}, found {}",
__program_id,
__account_a
);
return Err($crate::VipersError::ProgramIDMismatch.into());
}
};
}
/// Ensures an [Option] can be unwrapped, otherwise returns the error
#[macro_export]
macro_rules! unwrap_or_err {
($option:expr, $error:tt $(,)?) => {
$option.ok_or_else(|| -> ProgramError { crate::ErrorCode::$error.into() })?
};
}
/// Unwraps the result of a checked integer operation.
#[macro_export]
macro_rules! unwrap_int {
($option:expr $(,)?) => {
$option.ok_or_else(|| -> ProgramError { $crate::VipersError::IntegerOverflow.into() })?
};
}
/// Tries to unwrap the [Result], otherwise returns the error
#[macro_export]
macro_rules! try_or_err {
($result:expr, $error:tt $(,)?) => {
$result.map_err(|_| -> ProgramError { crate::ErrorCode::$error.into() })?
};
}
/// Returns the given error as a program error.
#[macro_export]
macro_rules! program_err {
($error:tt $(,)?) => {
Err(crate::ErrorCode::$error.into())
};
}
/// Require or return a [ProgramError], logging the string representation to the program log.
#[macro_export]
macro_rules! prog_require {
($invariant:expr, $err:expr $(,)?) => {
if !($invariant) {
msg!("Invariant failed: {:?}", $err);
return Err($err.into());
}
};
}
#[cfg(test)]
mod tests {
use anchor_lang::prelude::*;
use anchor_spl::token;
use spl_associated_token_account::get_associated_token_address;
#[test]
fn test_compiles() -> ProgramResult {
assert_keys!(token::ID, token::ID, "token program");
assert_ata!(
get_associated_token_address(&token::ID, &token::ID),
token::ID,
token::ID,
"ATA"
);
assert_program!(token::ID, TOKEN_PROGRAM_ID);
let weird_math: Option<i32> = (1_i32).checked_add(2);
let _result = unwrap_int!(weird_math);
Ok(())
}
}
| true
|
98c9856d680690c4d970c5a2c25c99595deb9c98
|
Rust
|
EvilSuperstars/terraform-provider-wapc
|
/examples/rust/src/lib.rs
|
UTF-8
| 1,043
| 2.75
| 3
|
[
"Unlicense"
] |
permissive
|
extern crate wapc_guest as guest;
use guest::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::json;
#[no_mangle]
pub extern "C" fn wapc_init() {
register_function("hello", hello);
}
//
// Can be specified in HCL as:
// input = {
// "Name" = "waPC"
// "Uppercase" = true
// }
//
#[derive(Serialize, Deserialize)]
struct Input {
#[serde(rename = "Name")]
name: String,
#[serde(rename = "Uppercase")]
#[serde(default)]
uppercase: bool,
}
fn hello(msg: &[u8]) -> CallResult {
guest::console_log("[DEBUG] Enter hello");
let result = match serde_json::from_slice(msg) {
Ok(input @ Input { .. }) => {
let mut name = input.name;
if input.uppercase {
name = name.to_uppercase();
}
//
// Can be referenced in HCL as `result["Name"]`.
//
serde_json::to_vec(&json!({ "Name": name }))?
}
_ => vec![],
};
guest::console_log("[DEBUG] Exit hello");
Ok(result)
}
| true
|
8570e6b21dae628e2d26406b3d4a3e41dbdfd21d
|
Rust
|
joshuarli/fd
|
/src/regex_helper.rs
|
UTF-8
| 3,498
| 3.59375
| 4
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use regex_syntax::hir::Hir;
use regex_syntax::ParserBuilder;
/// Determine if a regex pattern contains a literal uppercase character.
pub fn pattern_has_uppercase_char(pattern: &str) -> bool {
let mut parser = ParserBuilder::new().allow_invalid_utf8(true).build();
parser
.parse(pattern)
.map(|hir| hir_has_uppercase_char(&hir))
.unwrap_or(false)
}
/// Determine if a regex expression contains a literal uppercase character.
fn hir_has_uppercase_char(hir: &Hir) -> bool {
use regex_syntax::hir::*;
match *hir.kind() {
HirKind::Literal(Literal::Unicode(c)) => c.is_uppercase(),
HirKind::Literal(Literal::Byte(b)) => char::from(b).is_uppercase(),
HirKind::Class(Class::Unicode(ref ranges)) => ranges
.iter()
.any(|r| r.start().is_uppercase() || r.end().is_uppercase()),
HirKind::Class(Class::Bytes(ref ranges)) => ranges
.iter()
.any(|r| char::from(r.start()).is_uppercase() || char::from(r.end()).is_uppercase()),
HirKind::Group(Group { ref hir, .. }) | HirKind::Repetition(Repetition { ref hir, .. }) => {
hir_has_uppercase_char(hir)
}
HirKind::Concat(ref hirs) | HirKind::Alternation(ref hirs) => {
hirs.iter().any(hir_has_uppercase_char)
}
_ => false,
}
}
/// Determine if a regex pattern only matches strings starting with a literal dot (hidden files)
pub fn pattern_matches_strings_with_leading_dot(pattern: &str) -> bool {
let mut parser = ParserBuilder::new().allow_invalid_utf8(true).build();
parser
.parse(pattern)
.map(|hir| hir_matches_strings_with_leading_dot(&hir))
.unwrap_or(false)
}
/// See above.
fn hir_matches_strings_with_leading_dot(hir: &Hir) -> bool {
use regex_syntax::hir::*;
// Note: this only really detects the simplest case where a regex starts with
// "^\\.", i.e. a start text anchor and a literal dot character. There are a lot
// of other patterns that ONLY match hidden files, e.g. ^(\\.foo|\\.bar) which are
// not (yet) detected by this algorithm.
match *hir.kind() {
HirKind::Concat(ref hirs) => {
let mut hirs = hirs.iter();
if let Some(hir) = hirs.next() {
if *hir.kind() != HirKind::Anchor(Anchor::StartText) {
return false;
}
} else {
return false;
}
if let Some(hir) = hirs.next() {
*hir.kind() == HirKind::Literal(Literal::Unicode('.'))
} else {
false
}
}
_ => false,
}
}
#[test]
fn pattern_has_uppercase_char_simple() {
assert!(pattern_has_uppercase_char("A"));
assert!(pattern_has_uppercase_char("foo.EXE"));
assert!(!pattern_has_uppercase_char("a"));
assert!(!pattern_has_uppercase_char("foo.exe123"));
}
#[test]
fn pattern_has_uppercase_char_advanced() {
assert!(pattern_has_uppercase_char("foo.[a-zA-Z]"));
assert!(!pattern_has_uppercase_char(r"\Acargo"));
assert!(!pattern_has_uppercase_char(r"carg\x6F"));
}
#[test]
fn matches_strings_with_leading_dot_simple() {
assert!(pattern_matches_strings_with_leading_dot("^\\.gitignore"));
assert!(!pattern_matches_strings_with_leading_dot("^.gitignore"));
assert!(!pattern_matches_strings_with_leading_dot("\\.gitignore"));
assert!(!pattern_matches_strings_with_leading_dot("^gitignore"));
}
| true
|
63a940f449fc3e6f88b69d59aaf102931f26e6be
|
Rust
|
lostatseajoshua/learning_rust
|
/fibonacci/src/main.rs
|
UTF-8
| 690
| 3.75
| 4
|
[] |
no_license
|
use std::io;
fn main() {
loop {
println!("Get fibonacci of:");
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => (),
Err(err) => {
println!("{:?}", err);
continue;
},
}
let input: u64 = match input.trim().parse() {
Ok(num) => num,
Err(err) => {
println!("{:?}", err);
continue;
},
};
println!("{:?}", fib(input));
break;
}
}
fn fib(x: u64) -> u64 {
match x {
0 => 0,
1 | 2 => 1,
_ => fib(x - 1) + fib(x - 2)
}
}
| true
|
60dca0824205653aa880315006d9f85110c59df5
|
Rust
|
ianprice943/rustBook
|
/chapter9/c9_3_to_panic_or_not_to_panic/src/main.rs
|
UTF-8
| 1,387
| 3.796875
| 4
|
[] |
no_license
|
fn main() {
use std::net::IpAddr;
// since this is a hard coded string it's reasonable to assume it cannot error out.
// if this was a user passed string however, you should do proper error handling
let home: IpAddr = "127.0.0.1".parse().unwrap();
// creating custom types for validation
// snippet from the guessing game with an update to see if the guess is less than 1
// or greater than 100
/*
loop {
let guess: i32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
if guess < 1 || guess > 100 {
println!("The secret number will be between 1 and 100.");
continue;
}
match guess.cmp(&secret_number) {
}
}
*/
// instead of checking that the guess is valid in many places throughout our code, it
// would be useful to create a custom type that does the validation for us
pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess must be between 1 and 100, got {}.", value);
}
Guess { value }
}
pub fn value(&self) -> i32 {
self.value
}
}
let guess = Guess::new(45);
println!("The guess was {}.", guess.value);
}
| true
|
b16236cf02c6f16f3bdf541e99e359ae497b56e2
|
Rust
|
hellow554/breeze-emu
|
/src/spc700/lib.rs
|
UTF-8
| 39,128
| 2.6875
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Implements the Audio Processing Unit (APU)
//!
//! The APU consists of 64 KB shared RAM, the SPC700 and the DSP. It is almost fully independent
//! from the rest of the SNES.
//!
//! The SPC700 is an independent audio coprocessor. The main CPU can transmit a program and audio
//! data into the shared RAM and then execute it. The program can manipulate DSP registers and
//! specify samples to play.
#![deny(warnings)]
#![deny(unused_import_braces, unused_qualifications, unused_extern_crates)]
#[macro_use] extern crate log;
#[macro_use] #[no_link] extern crate byte_array;
#[macro_use] extern crate libsavestate;
#[macro_use] mod once;
mod addressing;
mod dsp;
mod ipl;
mod statusreg;
mod timer;
use addressing::AddressingMode;
use dsp::Dsp;
use ipl::IPL_ROM;
use statusreg::StatusReg;
use timer::Timer;
const RAM_SIZE: usize = 65536;
byte_array!(Ram[RAM_SIZE] with u16 indexing, save state please);
const RESET_VEC: u16 = 0xFFFE;
/// The SPC700 is an 8-bit processor with a 16-bit address space.
///
/// It has 64 KB of RAM shared with the DSP. The last 64 Bytes in its address space are mapped to
/// the "IPL ROM", which contains a small piece of startup code that allows the main CPU to transfer
/// a program to the APU.
pub struct Spc700 {
/// 64KB of RAM, shared with DSP
mem: Ram,
/// The SPC700 starts with the IPL ROM mapped into the highest 64 Bytes of address space. It can
/// be unmapped by clearing bit 7 in `$f1` (`CONTROL`), which allows using this space as normal
/// RAM (writes to this area always go to RAM).
ipl_rom_mapped: bool,
/// `$f2` - DSP address selection (`$f3` - DSP data)
reg_dsp_addr: u8,
/// Values written to the IO Registers by the main CPU. The CPU will write values here. These
/// are read by the SPC, the CPU reads directly from RAM, while the SPC writes to RAM.
/// `$f4 - $f7`
io_vals: [u8; 4],
timers: [Timer; 3],
dsp: Dsp,
a: u8,
x: u8,
y: u8,
sp: u8,
pc: u16,
psw: StatusReg,
cy: u8,
pub trace: bool,
}
impl_save_state!(Spc700 { mem, ipl_rom_mapped, reg_dsp_addr, io_vals, timers, dsp, a, x, y, sp, pc,
psw } ignore { cy, trace });
impl Default for Spc700 {
fn default() -> Self {
let pcl = IPL_ROM[RESET_VEC as usize - 0xffc0] as u16;
let pch = IPL_ROM[RESET_VEC as usize - 0xffc0 + 1] as u16;
let pc = (pch << 8) | pcl;
Spc700 {
mem: Ram::default(),
ipl_rom_mapped: true,
reg_dsp_addr: 0,
io_vals: [0; 4],
timers: [Timer::new(); 3],
dsp: Dsp::new(),
a: 0,
x: 0,
y: 0,
sp: 0,
pc: pc,
psw: StatusReg(0), // FIXME is 0 correct?
cy: 0,
trace: false,
}
}
}
impl Spc700 {
/// Store a byte in an IO port (`0-3`)
///
/// SNES IO ports `$2140-$2143` are mapped to internal registers `$f4-$f7`
pub fn store_port(&mut self, port: u8, value: u8) {
debug_assert!(port < 4);
self.io_vals[port as usize] = value;
}
/// Load a byte from an IO port
pub fn read_port(&mut self, port: u8) -> u8 {
debug_assert!(port < 4);
let val = self.mem[0xf4 + port as u16];
val
}
fn load(&mut self, addr: u16) -> u8 {
match addr {
0xf0 => panic!("undocumented register unimplemented"),
0xf1 => {
once!(warn!("read from write-only control register"));
let t0 = if self.timers[0].enabled() { 0b001 } else { 0 };
let t1 = if self.timers[1].enabled() { 0b010 } else { 0 };
let t2 = if self.timers[2].enabled() { 0b100 } else { 0 };
t0 | t1 | t2 // not sure what else to return
}
0xfa ... 0xfc =>
panic!("APU attempted read from write-only register ${:02X}", addr),
0xf2 => self.reg_dsp_addr,
0xf3 => self.dsp.load(self.reg_dsp_addr),
0xf4 ... 0xf7 => self.io_vals[addr as usize - 0xf4],
0xfd => {
let val = self.timers[0].val;
self.timers[0].val = 0;
val
}
0xfe => {
let val = self.timers[1].val;
self.timers[1].val = 0;
val
}
0xff => {
let val = self.timers[2].val;
self.timers[2].val = 0;
val
}
// NB: $f8 and $f9 work like regular RAM
0xffc0 ... 0xffff if self.ipl_rom_mapped => IPL_ROM[addr as usize - 0xffc0],
_ => self.mem[addr],
}
}
fn store(&mut self, addr: u16, val: u8) {
// All writes are also passed to RAM
self.mem[addr] = val;
match addr {
0xf0 => {
if val != 0x0a {
once!({
warn!("SPC700 wrote ${:02X} to testing register ($f0)", val);
warn!("As a safety measure, only $0a is allowed. This write will be \
ignored! (This warning will only be printed for the first illegal \
write)");
});
}
}
0xf1 => {
self.timers[0].set_enable(val & 0x01 != 0);
self.timers[1].set_enable(val & 0x02 != 0);
self.timers[2].set_enable(val & 0x04 != 0);
if val & 0x10 != 0 {
self.io_vals[0] = 0;
self.io_vals[1] = 0;
}
if val & 0x20 != 0 {
self.io_vals[2] = 0;
self.io_vals[3] = 0;
}
self.ipl_rom_mapped = val & 0x80 != 0;
},
0xf2 => self.reg_dsp_addr = val,
0xf3 => self.dsp.store(self.reg_dsp_addr, val),
0xfa => self.timers[0].div = val,
0xfb => self.timers[1].div = val,
0xfc => self.timers[2].div = val,
0xfd ... 0xff => panic!("APU attempted to write to read-only register ${:04X}", addr),
// NB: Stores to 0xf4 - 0xf9 are just sent to RAM
_ => {}
}
}
fn loadw(&mut self, addr: u16) -> u16 {
let lo = self.load(addr) as u16;
let hi = self.load(addr + 1) as u16;
(hi << 8) | lo
}
fn fetchb(&mut self) -> u8 {
let pc = self.pc;
self.pc += 1;
self.load(pc)
}
fn fetchw(&mut self) -> u16 {
let lo = self.fetchb() as u16;
let hi = self.fetchb() as u16;
(hi << 8) | lo
}
fn trace_op(&self, pc: u16, opstr: &str) {
trace!("${:04X} {:02X} {:16} a:{:02X} x:{:02X} y:{:02X} sp:{:02X} {}",
pc,
self.mem[pc],
opstr,
self.a,
self.x,
self.y,
self.sp,
self.psw,
);
}
/// Dispatch an opcode
pub fn dispatch(&mut self) -> u8 {
use log::LogLevel::Trace;
// Cond. branches: +2 cycles if branch is taken
static CYCLE_TABLE: [u8; 256] = [
2,8,4,5,3,4,3,6, 2,6,5,4,5,4,6,8, // $00-$0f
2,8,4,5,4,5,5,6, 5,5,6,5,2,2,4,6, // $10-$1f
2,8,4,5,3,4,3,6, 2,6,5,4,5,4,5,4, // $20-$2f
2,8,4,5,4,5,5,6, 5,5,6,5,2,2,3,8, // $30-$3f
2,8,4,5,3,4,3,6, 2,6,4,4,5,4,6,6, // $40-$4f
2,8,4,5,4,5,5,6, 5,5,4,5,2,2,4,3, // $50-$5f
2,8,4,5,3,4,3,6, 2,6,4,4,5,4,5,5, // $60-$6f
2,8,4,5,4,5,5,6, 5,5,5,5,2,2,3,6, // $70-$7f
2,8,4,5,3,4,3,6, 2,6,5,4,5,2,4,5, // $80-$8f
2,8,4,5,4,5,5,6, 5,5,5,5,2,2,12,5, // $90-$9f
3,8,4,5,3,4,3,6, 2,6,4,4,5,2,4,4, // $a0-$af
2,8,4,5,4,5,5,6, 5,5,5,5,2,2,3,4, // $b0-$bf
3,8,4,5,4,5,4,7, 2,5,6,4,5,2,4,9, // $c0-$cf
2,8,4,5,5,6,6,7, 4,5,5,5,2,2,6,3, // $d0-$df
2,8,4,5,3,4,3,6, 2,4,5,3,4,3,4,3, // $e0-$ef (last one is SLEEP, unknown timing)
2,8,4,5,4,5,5,6, 3,4,5,4,2,2,5,3, // $f0-$ff (last one is STOP, unknown timing)
];
let pc = self.pc;
macro_rules! e {
($e:expr) => ($e)
}
macro_rules! instr {
( _ $name:ident ) => {{
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, stringify!($name));
}
self.$name()
}};
( $s:tt $name:ident ) => {{
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, e!($s));
}
self.$name()
}};
( _ $name:ident ($arg:tt) ) => {{
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, concat!(stringify!($name), " ", $arg));
}
self.$name(e!($arg))
}};
( _ $name:ident ($arg:tt) $am:ident ) => {{
let am = self.$am();
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, &format!(concat!(stringify!($name), " {}.", $arg), am));
}
self.$name(e!($arg), am)
}};
( $s:tt $name:ident ($arg:tt) $am:ident ) => {{
let am = self.$am();
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, &format!(e!($s), am));
}
self.$name(e!($arg), am)
}};
( _ $name:ident ($arg:tt) $am:ident $am2:ident ) => {{
let am = self.$am();
let am2 = self.$am2();
if log_enabled!(Trace) && self.trace {
self.trace_op(pc,
&format!(concat!(stringify!($name), " {}.", $arg, ", {}"), am, am2));
}
self.$name(e!($arg), am, am2)
}};
( $s:tt $name:ident ($arg:tt) $am:ident $am2:ident ) => {{
let am = self.$am();
let am2 = self.$am2();
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, &format!(e!($s), am, am2));
}
self.$name(e!($arg), am, am2)
}};
( _ $name:ident $am:ident ) => {{
let am = self.$am();
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, &format!(concat!(stringify!($name), " {}"), am));
}
self.$name(am)
}};
( $s:tt $name:ident $am:ident ) => {{
let am = self.$am();
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, &format!(e!($s), am));
}
self.$name(am)
}};
( _ $name:ident $am:ident $am2:ident ) => {{
let am = self.$am();
let am2 = self.$am2();
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, &format!(concat!(stringify!($name), " {1}, {0}"), am, am2));
}
self.$name(am, am2)
}};
( $s:tt $name:ident $am:ident $am2:ident ) => {{
let am = self.$am();
let am2 = self.$am2();
if log_enabled!(Trace) && self.trace {
self.trace_op(pc, &format!(e!($s), am, am2));
}
self.$name(am, am2)
}};
}
let op = self.fetchb();
self.cy = CYCLE_TABLE[op as usize];
match op {
// Processor status
0x20 => instr!(_ clrp),
0x40 => instr!(_ setp),
0x60 => instr!(_ clrc),
0x80 => instr!(_ setc),
0xed => instr!(_ notc),
0xc0 => instr!(_ di),
0xa0 => instr!(_ ei),
// Arithmetic
0x9c => instr!(_ dec a),
0x1d => instr!(_ dec x),
0xdc => instr!(_ dec y),
0x8b => instr!(_ dec direct),
0x9b => instr!(_ dec direct_indexed_x),
0x8c => instr!(_ dec abs),
0xbc => instr!(_ inc a),
0x3d => instr!(_ inc x),
0xfc => instr!(_ inc y),
0xab => instr!(_ inc direct),
0xbb => instr!(_ inc direct_indexed_x),
0xac => instr!(_ inc abs),
0x3a => instr!(_ incw direct),
0x1a => instr!(_ decw direct),
0x28 => instr!(_ and immediate a),
0x26 => instr!(_ and indirect_x a),
0x37 => instr!(_ and indirect_indexed_y a),
0x27 => instr!(_ and indexed_x_indirect a),
0x24 => instr!(_ and direct a),
0x34 => instr!(_ and direct_indexed_x a),
0x25 => instr!(_ and abs a),
0x35 => instr!(_ and abs_indexed_x a),
0x36 => instr!(_ and abs_indexed_y a),
0x29 => instr!(_ and direct direct),
0x38 => instr!(_ and immediate direct),
//0x19 => instr!(_ or indirect_y indirect_x), TODO
0x08 => instr!(_ or immediate a),
0x06 => instr!(_ or indirect_x a),
0x17 => instr!(_ or indirect_indexed_y a),
0x07 => instr!(_ or indexed_x_indirect a),
0x04 => instr!(_ or direct a),
0x14 => instr!(_ or direct_indexed_x a),
0x05 => instr!(_ or abs a),
0x15 => instr!(_ or abs_indexed_x a),
0x16 => instr!(_ or abs_indexed_y a),
0x09 => instr!(_ or direct direct),
0x18 => instr!(_ or immediate direct),
//0x59 => instr!(_ eor indirect_y indirect_x), TODO
0x48 => instr!(_ eor immediate a),
0x44 => instr!(_ eor direct a),
0x46 => instr!(_ eor indirect_x a),
0x57 => instr!(_ eor indirect_indexed_y a),
0x47 => instr!(_ eor indexed_x_indirect a),
0x54 => instr!(_ eor direct_indexed_x a),
0x45 => instr!(_ eor abs a),
0x55 => instr!(_ eor abs_indexed_x a),
0x56 => instr!(_ eor abs_indexed_y a),
0x49 => instr!(_ eor direct direct),
0x58 => instr!(_ eor immediate direct),
0x1c => instr!(_ asl a),
0x0b => instr!(_ asl direct),
0x1b => instr!(_ asl direct_indexed_x),
0x0c => instr!(_ asl abs),
0x5c => instr!(_ lsr a),
0x4b => instr!(_ lsr direct),
0x5b => instr!(_ lsr direct_indexed_x),
0x4c => instr!(_ lsr abs),
0x3c => instr!(_ rol a),
0x2b => instr!(_ rol direct),
0x3b => instr!(_ rol direct_indexed_x),
0x2c => instr!(_ rol abs),
0x7c => instr!(_ ror a),
0x6b => instr!(_ ror direct),
0x7b => instr!(_ ror direct_indexed_x),
0x6c => instr!(_ ror abs),
//0x99 => instr!(_ adc indirect_y indirect_x), TODO
0x88 => instr!(_ adc immediate a),
0x86 => instr!(_ adc indirect_x a),
0x97 => instr!(_ adc indirect_indexed_y a),
0x87 => instr!(_ adc indexed_x_indirect a),
0x84 => instr!(_ adc direct a),
0x94 => instr!(_ adc direct_indexed_x a),
0x85 => instr!(_ adc abs a),
0x95 => instr!(_ adc abs_indexed_x a),
0x96 => instr!(_ adc abs_indexed_y a),
0x89 => instr!(_ adc direct direct),
0x98 => instr!(_ adc immediate direct),
0x7a => instr!("addw ya, {}" addw direct),
0xa8 => instr!(_ sbc immediate a),
0xa4 => instr!(_ sbc direct a),
0xb4 => instr!(_ sbc direct_indexed_x a),
0xa9 => instr!(_ sbc direct direct),
0xa6 => instr!(_ sbc indirect_x a),
0xa5 => instr!(_ sbc abs a),
0xb5 => instr!(_ sbc abs_indexed_x a),
0xb6 => instr!(_ sbc abs_indexed_y a),
0x9a => instr!("subw ya, {0}" subw direct),
0xcf => instr!("mul ya" mul),
0x9e => instr!("div ya, x" div),
0x9f => instr!(_ xcn a),
// Control flow and comparisons
0x78 => instr!(_ cmp immediate direct),
0x64 => instr!(_ cmp direct a),
0x3e => instr!(_ cmp direct x),
0x7e => instr!(_ cmp direct y),
0x74 => instr!(_ cmp direct_indexed_x a),
0x69 => instr!(_ cmp direct direct),
0x66 => instr!(_ cmp indirect_x a),
0x77 => instr!(_ cmp indirect_indexed_y a), // cmp a, [d]+Y
0x67 => instr!(_ cmp indexed_x_indirect a), // cmp a, [d+X]
0x68 => instr!(_ cmp immediate a),
0xc8 => instr!(_ cmp immediate x),
0xad => instr!(_ cmp immediate y),
0x65 => instr!(_ cmp abs a),
0x1e => instr!(_ cmp abs x),
0x5e => instr!(_ cmp abs y),
0x75 => instr!(_ cmp abs_indexed_x a),
0x76 => instr!(_ cmp abs_indexed_y a),
0x5a => instr!(_ cmpw direct),
0xde => instr!("cbne {}, {}" cbne direct_indexed_x rel),
0x2e => instr!("cbne {}, {}" cbne direct rel),
0xfe => instr!("dbnz {}, {}" dbnz y rel),
0x6e => instr!("dbnz {}, {}" dbnz direct rel),
0xea => instr!(_ not1 abs_bits),
0x0e => instr!(_ tset1 abs),
0x4e => instr!(_ tclr1 abs),
0x02 => instr!(_ set1(0) direct),
0x22 => instr!(_ set1(1) direct),
0x42 => instr!(_ set1(2) direct),
0x62 => instr!(_ set1(3) direct),
0x82 => instr!(_ set1(4) direct),
0xa2 => instr!(_ set1(5) direct),
0xc2 => instr!(_ set1(6) direct),
0xe2 => instr!(_ set1(7) direct),
0x12 => instr!(_ clr1(0) direct),
0x32 => instr!(_ clr1(1) direct),
0x52 => instr!(_ clr1(2) direct),
0x72 => instr!(_ clr1(3) direct),
0x92 => instr!(_ clr1(4) direct),
0xb2 => instr!(_ clr1(5) direct),
0xd2 => instr!(_ clr1(6) direct),
0xf2 => instr!(_ clr1(7) direct),
0x13 => instr!(_ bbc(0) direct rel),
0x33 => instr!(_ bbc(1) direct rel),
0x53 => instr!(_ bbc(2) direct rel),
0x73 => instr!(_ bbc(3) direct rel),
0x93 => instr!(_ bbc(4) direct rel),
0xb3 => instr!(_ bbc(5) direct rel),
0xd3 => instr!(_ bbc(6) direct rel),
0xf3 => instr!(_ bbc(7) direct rel),
0x03 => instr!(_ bbs(0) direct rel),
0x23 => instr!(_ bbs(1) direct rel),
0x43 => instr!(_ bbs(2) direct rel),
0x63 => instr!(_ bbs(3) direct rel),
0x83 => instr!(_ bbs(4) direct rel),
0xa3 => instr!(_ bbs(5) direct rel),
0xc3 => instr!(_ bbs(6) direct rel),
0xe3 => instr!(_ bbs(7) direct rel),
0x5f => instr!("jmp {}" bra abs), // reuse `bra` fn
0x1f => instr!("jmp {}" bra abs_indexed_x_indirect), // reuse `bra` fn
0x2f => instr!(_ bra rel),
0xf0 => instr!(_ beq rel),
0xd0 => instr!(_ bne rel),
0xb0 => instr!(_ bcs rel),
0x90 => instr!(_ bcc rel),
0x30 => instr!(_ bmi rel),
0x10 => instr!(_ bpl rel),
0x3f => instr!(_ call abs),
0x6f => instr!(_ ret),
0x01 => instr!(_ tcall(0)),
0x11 => instr!(_ tcall(1)),
0x21 => instr!(_ tcall(2)),
0x31 => instr!(_ tcall(3)),
0x41 => instr!(_ tcall(4)),
0x51 => instr!(_ tcall(5)),
0x61 => instr!(_ tcall(6)),
0x71 => instr!(_ tcall(7)),
0x81 => instr!(_ tcall(8)),
0x91 => instr!(_ tcall(9)),
0xa1 => instr!(_ tcall(10)),
0xb1 => instr!(_ tcall(11)),
0xc1 => instr!(_ tcall(12)),
0xd1 => instr!(_ tcall(13)),
0xe1 => instr!(_ tcall(14)),
0xf1 => instr!(_ tcall(15)),
0x2d => instr!(_ push a),
0x4d => instr!(_ push x),
0x6d => instr!(_ push y),
0xae => instr!(_ pop a),
0xce => instr!(_ pop x),
0xee => instr!(_ pop y),
// "mov"
// NB: For moves, "a x" means "mov x, a" or "a -> x"
// NB: Moves into registers will always set N and Z
0x8f => instr!(_ mov immediate direct),
0xe8 => instr!(_ mov immediate a),
0xcd => instr!(_ mov immediate x),
0x8d => instr!(_ mov immediate y),
0x5d => instr!(_ mov a x),
0xfd => instr!(_ mov a y),
0xc4 => instr!(_ mov a direct),
0xd4 => instr!(_ mov a direct_indexed_x),
0xc5 => instr!(_ mov a abs),
0xd5 => instr!(_ mov a abs_indexed_x),
0xd6 => instr!(_ mov a abs_indexed_y),
0xc6 => instr!(_ mov a indirect_x),
0xd7 => instr!(_ mov a indirect_indexed_y),
0x7d => instr!(_ mov x a),
0xd8 => instr!(_ mov x direct),
0xd9 => instr!(_ mov x direct_indexed_x),
0xc9 => instr!(_ mov x abs),
0xdd => instr!(_ mov y a),
0xcb => instr!(_ mov y direct),
0xdb => instr!(_ mov y direct_indexed_x),
0xcc => instr!(_ mov y abs),
0xe4 => instr!(_ mov direct a),
0xf8 => instr!(_ mov direct x),
0xeb => instr!(_ mov direct y),
0xfa => instr!(_ mov direct direct),
0xf4 => instr!(_ mov direct_indexed_x a),
0xfb => instr!(_ mov direct_indexed_x y),
0xe6 => instr!(_ mov indirect_x a),
0xe7 => instr!(_ mov indexed_x_indirect a),
0xf7 => instr!(_ mov indirect_indexed_y a),
0xe5 => instr!(_ mov abs a),
0xe9 => instr!(_ mov abs x),
0xec => instr!(_ mov abs y),
0xf5 => instr!(_ mov abs_indexed_x a),
0xf6 => instr!(_ mov abs_indexed_y a),
0xba => instr!("movw ya, {}" movw_l direct),
0xda => instr!("movw {}, ya" movw_s direct),
0xbd => instr!("mov sp, x" mov_sp_x),
0xaf => instr!("mov (x++), a" mov_xinc),
// `nop` is usually not used and can be a sign of something going very wrong!
//0x00 => instr!(_ nop),
_ => {
instr!(_ ill);
panic!("illegal APU opcode: ${:02X}", op);
}
}
self.timers[0].update(128, self.cy);
self.timers[1].update(128, self.cy);
self.timers[2].update(16, self.cy);
self.cy
}
fn pushb(&mut self, b: u8) {
let sp = 0x0100 | self.sp as u16;
self.store(sp, b);
// FIXME This wraps, but we'll let it crash
self.sp -= 1;
}
/// Pushes the high byte, then the low byte
fn pushw(&mut self, w: u16) {
let lo = w as u8;
let hi = (w >> 8) as u8;
self.pushb(hi);
self.pushb(lo);
}
fn popb(&mut self) -> u8 {
self.sp += 1;
let sp = 0x0100 | self.sp as u16;
self.load(sp)
}
/// Pops the low byte, then the high byte
fn popw(&mut self) -> u16 {
let lo = self.popb() as u16;
let hi = self.popb() as u16;
(hi << 8) | lo
}
/// Performs a call: Pushes PCh and PCl onto the stack and sets PC to `addr`.
fn call_addr(&mut self, addr: u16) {
let pc = self.pc;
self.pushw(pc);
self.pc = addr;
}
}
/// Opcode implementations
impl Spc700 {
fn push(&mut self, am: AddressingMode) {
let v = am.loadb(self);
self.pushb(v);
}
fn pop(&mut self, dest: AddressingMode) {
let v = self.popb();
dest.storeb(self, v);
}
fn ret(&mut self) {
let pc = self.popw();
self.pc = pc;
}
fn call(&mut self, am: AddressingMode) {
let addr = am.address(self);
self.call_addr(addr);
}
/// `call [$ffc0 + (15 - p) * 2]`
fn tcall(&mut self, p: u8) {
// Since all possible addresses are stored in IPL ROM area, it makes no sense to have it
// mapped.
if self.ipl_rom_mapped {
once!(warn!("`tcall {}` while IPL ROM is mapped!", p));
}
let addr = self.loadw(0xffc0 + (15 - p as u16) * 2);
self.call_addr(addr);
}
/// Clear direct page bit
fn clrp(&mut self) { self.psw.set_direct_page(false) }
/// Set direct page bit
fn setp(&mut self) { self.psw.set_direct_page(true) }
/// Clear carry
fn clrc(&mut self) { self.psw.set_carry(false) }
/// Set carry
fn setc(&mut self) { self.psw.set_carry(true) }
fn notc(&mut self) {
let c = self.psw.carry();
self.psw.set_carry(!c);
}
fn di(&mut self) {
self.psw.set_interrupt_enable(false);
}
fn ei(&mut self) {
self.psw.set_interrupt_enable(true);
}
/// `cmp b, a` - Set N, Z, C according to `b - a`
fn cmp(&mut self, a: AddressingMode, b: AddressingMode) {
// Sets N, Z and C
let b = b.loadb(self) as i16;
let a = a.loadb(self) as i16;
let diff = b - a;
self.psw.set_nz(diff as u8);
self.psw.set_carry(diff >= 0); // FIXME Not <0 right?
}
/// `cmpw YA, d` - Set N, Z (FIXME And maybe C?) according to `YA - d` (word comparison)
fn cmpw(&mut self, am: AddressingMode) {
let val = am.loadw(self);
let ya = ((self.y as u16) << 8) | self.a as u16;
let res = ya.wrapping_sub(val);
self.psw.set_zero(res == 0);
self.psw.set_negative(res & 0x80 != 0);
}
/// Invert a single bit of a 13-bit absolute addressed value
fn not1(&mut self, am: AddressingMode) {
// FIXME seems to set no flags, but is that true?
if let AddressingMode::AbsBits(addr) = am {
let bit = addr >> 13;
let mut val = am.clone().loadb(self);
val ^= 1 << bit;
am.storeb(self, val);
} else {
panic!("invalid addressing mode for not1 instr: {}", am);
}
}
fn tset1(&mut self, am: AddressingMode) {
// Sets N and Z
let val = am.clone().loadb(self);
let a = self.a;
am.storeb(self, val | a);
self.psw.set_nz(a.wrapping_sub(val)); // FIXME is this correct?
}
fn tclr1(&mut self, am: AddressingMode) {
// Sets N and Z
let val = am.clone().loadb(self);
let a = self.a;
am.storeb(self, val & !a);
self.psw.set_nz(a.wrapping_sub(val)); // FIXME is this correct?
}
/// Set bit
fn set1(&mut self, bit: u8, am: AddressingMode) {
// Sets no flags
let mut val = am.clone().loadb(self);
val |= 1 << bit;
am.storeb(self, val);
}
/// Clear bit
fn clr1(&mut self, bit: u8, am: AddressingMode) {
// Sets no flags
let mut val = am.clone().loadb(self);
val &= !(1 << bit);
am.storeb(self, val);
}
/// Branch if bit clear
fn bbc(&mut self, bit: u8, val: AddressingMode, addr: AddressingMode) {
let val = val.loadb(self);
let addr = addr.address(self);
if val & (1 << bit) == 0 {
self.pc = addr;
self.cy += 2;
}
}
/// Branch if bit set
fn bbs(&mut self, bit: u8, val: AddressingMode, addr: AddressingMode) {
let val = val.loadb(self);
let addr = addr.address(self);
if val & (1 << bit) != 0 {
self.pc = addr;
self.cy += 2;
}
}
/// Decrement and branch if not zero
fn dbnz(&mut self, val: AddressingMode, addr: AddressingMode) {
let v = val.clone().loadb(self);
let a = addr.address(self);
let res = v.wrapping_sub(1);
val.storeb(self, res);
if res != 0 {
self.pc = a;
self.cy += 2;
}
}
/// Compare and branch if not equal
fn cbne(&mut self, cmp: AddressingMode, addr: AddressingMode) {
let cmp = cmp.loadb(self);
let a = addr.address(self);
if cmp != self.a {
self.pc = a;
self.cy += 2;
}
}
fn bra(&mut self, am: AddressingMode) {
let addr = am.address(self);
self.pc = addr;
}
fn beq(&mut self, am: AddressingMode) {
let addr = am.address(self);
if self.psw.zero() {
self.pc = addr;
self.cy += 2;
}
}
fn bne(&mut self, am: AddressingMode) {
let addr = am.address(self);
if !self.psw.zero() {
self.pc = addr;
self.cy += 2;
}
}
/// Branch if carry set
fn bcs(&mut self, am: AddressingMode) {
let addr = am.address(self);
if self.psw.carry() {
self.pc = addr;
self.cy += 2;
}
}
/// Branch if carry clear
fn bcc(&mut self, am: AddressingMode) {
let addr = am.address(self);
if !self.psw.carry() {
self.pc = addr;
self.cy += 2;
}
}
fn bmi(&mut self, am: AddressingMode) {
let addr = am.address(self);
if self.psw.negative() {
self.pc = addr;
self.cy += 2;
}
}
fn bpl(&mut self, am: AddressingMode) {
let addr = am.address(self);
if !self.psw.negative() {
self.pc = addr;
self.cy += 2;
}
}
/// Exchange nibbles of byte
fn xcn(&mut self, am: AddressingMode) {
// Sets N and Z
let val = am.clone().loadb(self);
let res = (val >> 4) | (val << 4);
self.psw.set_nz(res);
am.storeb(self, res);
}
/// `mul ya`: ya = y * a
fn mul(&mut self) {
// Sets N and Z (on Y only). Y = High, A = Low.
let res = (self.y as u16).wrapping_mul(self.a as u16);
self.y = self.psw.set_nz((res >> 8) as u8);
self.a = res as u8;
}
/// A=YA/X, Y=mod(YA,X)
fn div(&mut self) {
// Sets N, Z, V, H
// FIXME Set H and check if this is correct
let mut yva = ((self.y as u32) << 8) | self.a as u32;
let x = (self.x as u32) << 9;
for _ in 0..9 {
// 7-bit left rotation:
yva <<= 1;
if yva & 0x20000 != 0 {
yva = (yva & 0x1ffff) | 1;
}
if yva >= x { yva ^= 1; }
if yva & 1 != 0 { yva = yva.wrapping_sub(x) & 0x1ffff; }
}
self.psw.set_overflow(yva & 0x100 != 0);
self.y = (yva >> 9) as u8;
self.a = self.psw.set_nz(yva as u8);
}
fn adc(&mut self, src: AddressingMode, dest: AddressingMode) {
// Sets N, V, H, Z and C
let c = if self.psw.carry() { 1 } else { 0 };
let a = dest.clone().loadb(self);
let b = src.loadb(self);
let res = a as u16 + b as u16 + c as u16;
self.psw.set_carry(res > 255);
self.psw.set_half_carry(((a & 0x0f) + (b & 0x0f) + c) & 0xf0 != 0);
let res = res as u8;
self.psw.set_overflow((a ^ b) & 0x80 == 0 && (a ^ res) & 0x80 == 0x80);
self.psw.set_nz(res);
dest.storeb(self, res);
}
fn addw(&mut self, am: AddressingMode) {
// Sets N, V, H, Z and C (H on high byte)
// FIXME: Set H and check if this is correct
// YA := YA + <byte> (Y = High, A = Low)
let ya = ((self.y as u16) << 8) | self.a as u16;
let val = am.loadw(self);
let res = ya as u32 + val as u32;
self.psw.set_carry(res & 0xffff0000 != 0);
let res = res as u16;
self.psw.set_overflow((ya ^ val) & 0x8000 == 0 && (ya ^ res) & 0x8000 == 0x8000);
self.psw.set_negative(res & 0x8000 != 0);
self.psw.set_zero(res == 0);
self.y = (res >> 8) as u8;
self.a = res as u8;
}
fn sbc(&mut self, src: AddressingMode, dest: AddressingMode) {
// Sets N, V, H, Z and C
// FIXME Set H and V
let c = if self.psw.carry() { 0 } else { 1 }; // Borrow flag
let a = dest.clone().loadb(self) as i16;
let b = src.loadb(self) as i16;
let res = a - b - c;
self.psw.set_carry(res >= 0); // `>= 0` because borrow
self.psw.set_nz(res as u8);
dest.storeb(self, res as u8);
}
/// Subtract from YA (Carry is set, but ignored for the operation)
fn subw(&mut self, am: AddressingMode) {
// Sets N, V, H (on high byte), Z, C
// FIXME Set V and H
let ya = ((self.y as i32) << 8) | self.a as i32;
let sub = am.loadw(self) as i32;
let res = ya - sub;
self.psw.set_carry(res >= 0);
self.psw.set_negative(res & 0x8000 != 0);
self.psw.set_zero(res == 0);
self.y = (ya >> 8) as u8;
self.a = ya as u8;
}
fn and(&mut self, r: AddressingMode, l: AddressingMode) {
// Sets N and Z
// l := l & r
let rb = r.loadb(self);
let lb = l.clone().loadb(self);
let res = self.psw.set_nz(lb & rb);
l.storeb(self, res);
}
fn or(&mut self, r: AddressingMode, l: AddressingMode) {
// Sets N and Z
// l := l | r
let rb = r.loadb(self);
let lb = l.clone().loadb(self);
let res = self.psw.set_nz(lb | rb);
l.storeb(self, res);
}
/// Exclusive Or
fn eor(&mut self, r: AddressingMode, l: AddressingMode) {
// Sets N and Z
// l := l ^ r
let rb = r.loadb(self);
let lb = l.clone().loadb(self);
let res = self.psw.set_nz(lb ^ rb);
l.storeb(self, res);
}
/// Left shift
fn asl(&mut self, op: AddressingMode) {
let val = op.clone().loadb(self);
self.psw.set_carry(val & 0x80 != 0);
let res = self.psw.set_nz(val << 1);
op.storeb(self, res);
}
/// Right shift
fn lsr(&mut self, op: AddressingMode) {
let val = op.clone().loadb(self);
self.psw.set_carry(val & 0x01 != 0);
let res = self.psw.set_nz(val >> 1);
op.storeb(self, res);
}
/// Rotate left
fn rol(&mut self, op: AddressingMode) {
let val = op.clone().loadb(self);
let c = if self.psw.carry() { 1 } else { 0 };
self.psw.set_carry(val & 0x80 != 0);
let res = self.psw.set_nz((val << 1) | c);
op.storeb(self, res);
}
/// Rotate right
fn ror(&mut self, op: AddressingMode) {
let val = op.clone().loadb(self);
let c = if self.psw.carry() { 0x80 } else { 0 };
self.psw.set_carry(val & 0x01 != 0);
let res = self.psw.set_nz((val >> 1) | c);
op.storeb(self, res);
}
fn dec(&mut self, am: AddressingMode) {
// Sets N and Z
let val = am.clone().loadb(self);
let res = self.psw.set_nz(val.wrapping_sub(1));
am.storeb(self, res);
}
fn inc(&mut self, am: AddressingMode) {
// Sets N and Z
let val = am.clone().loadb(self);
let res = self.psw.set_nz(val.wrapping_add(1));
am.storeb(self, res);
}
fn incw(&mut self, am: AddressingMode) {
// Sets N and Z
let val = am.clone().loadw(self);
let res = val.wrapping_add(1);
// FIXME Are the flags set right?
self.psw.set_negative(res & 0x8000 != 0);
self.psw.set_zero(res == 0);
am.storew(self, res);
}
fn decw(&mut self, am: AddressingMode) {
// Sets N and Z
let val = am.clone().loadw(self);
let res = val.wrapping_sub(1);
// FIXME Are the flags set right?
self.psw.set_negative(res & 0x8000 != 0);
self.psw.set_zero(res == 0);
am.storew(self, res);
}
/// `mov (X++), A` - Move A to the address pointed to by X, then increment X
fn mov_xinc(&mut self) {
// No flags changed
let addr = self.x as u16 + match self.psw.direct_page() {
true => 0x0100,
false => 0x0000,
};
let a = self.a;
self.store(addr, a);
self.x = self.x.wrapping_add(1);
}
/// movw-load. Fetches a word from the addressing mode and puts it into Y (high) and A (low)
/// (`movw ya, {X}`)
fn movw_l(&mut self, am: AddressingMode) {
// FIXME Are the flags set right?
let val = am.loadw(self);
self.y = self.psw.set_nz((val >> 8) as u8);
self.a = val as u8;
}
/// movw-store. Stores Y (high) and A (low) at the given address.
/// (`movw {X}, ya`)
fn movw_s(&mut self, am: AddressingMode) {
// No flags modified, Reads the low byte first
let y = self.y as u16;
let a = self.a as u16;
am.clone().loadb(self);
am.storew(self, (y << 8) | a);
}
/// Copy a byte
fn mov(&mut self, src: AddressingMode, dest: AddressingMode) {
// No flags modified, except when the destination is a register
let val = src.loadb(self);
if dest.is_register() {
self.psw.set_nz(val);
}
dest.storeb(self, val);
}
fn mov_sp_x(&mut self) {
// No flags modified
self.sp = self.x;
}
#[allow(dead_code)]
fn nop(&mut self) {}
fn ill(&mut self) {}
}
/// Addressing mode construction
impl Spc700 {
fn direct(&mut self) -> AddressingMode {
AddressingMode::Direct(self.fetchb())
}
fn direct_indexed_x(&mut self) -> AddressingMode {
AddressingMode::DirectIndexedX(self.fetchb())
}
fn indirect_x(&mut self) -> AddressingMode {
AddressingMode::IndirectX
}
fn indirect_indexed_y(&mut self) -> AddressingMode {
AddressingMode::IndirectIndexedY(self.fetchb())
}
fn indexed_x_indirect(&mut self) -> AddressingMode {
AddressingMode::IndexedXIndirect(self.fetchb())
}
fn abs_indexed_x_indirect(&mut self) -> AddressingMode {
AddressingMode::AbsIndexedXIndirect(self.fetchw())
}
fn abs(&mut self) -> AddressingMode {
AddressingMode::Abs(self.fetchw())
}
fn abs_indexed_x(&mut self) -> AddressingMode {
AddressingMode::AbsIndexedX(self.fetchw())
}
fn abs_indexed_y(&mut self) -> AddressingMode {
AddressingMode::AbsIndexedY(self.fetchw())
}
fn abs_bits(&mut self) -> AddressingMode {
AddressingMode::AbsBits(self.fetchw())
}
fn immediate(&mut self) -> AddressingMode {
AddressingMode::Immediate(self.fetchb())
}
fn rel(&mut self) -> AddressingMode {
AddressingMode::Rel(self.fetchb() as i8)
}
fn a(&mut self) -> AddressingMode {
AddressingMode::A
}
fn x(&mut self) -> AddressingMode {
AddressingMode::X
}
fn y(&mut self) -> AddressingMode {
AddressingMode::Y
}
}
| true
|
9cc1d6d1f3df5834a26ecf483648438b93cc3c52
|
Rust
|
jvff/netlink
|
/rtnetlink/src/lib.rs
|
UTF-8
| 5,326
| 3.484375
| 3
|
[
"MITNFA"
] |
permissive
|
//! This crate contains building blocks for the route netlink protocol.
//!
//! # Messages
//!
//! This crate provides two representations of most netlink packets:
//!
//! - **Buffer** types: [`NetlinkBuffer`](struct.NetlinkBuffer.html),
//! [`LinkBuffer`](struct.LinkBuffer.html), [`NlaBuffer`](struct.NlaBuffer.html), etc. These types
//! wrappers around actual byte buffers, and provide safe accessors to the various fields of the
//! packet they represent. These types are useful if you manipulate byte streams, but everytime
//! data is accessed, it must be parsed or encoded.
//!
//! - **Message** and **Nla** types: [`NetlinkMessage`](struct.NetlinkMessage.html),
//! [`LinkMessage`](struct.LinkMessage.html), [`LinkNla`](struct.LinkNla.html),
//! [`AddressNla`](struct.AddressNla.html) etc. These are higher level representations of netlink
//! packets and are the prefered way to build packets.
//!
//! ## Using buffer types to parse messages
//!
//! It is possible to go from on representation to another. Actually, the buffer types are used to
//! parse byte buffers into messages types, using the [`Parseable`](trait.Parseable.html) trait. In
//! the list of implementors, we can see for instance:
//!
//! ```no_rust
//! impl<'buffer, T: AsRef<[u8]> + 'buffer> Parseable<NetlinkMessage> for NetlinkBuffer<&'buffer T>
//! ```
//!
//! That means a `NetlinkBuffer` is parseable into a `NetlinkMessage`:
//!
//! ```rust
//! extern crate rtnetlink;
//! use rtnetlink::{NetlinkBuffer, NetlinkMessage, Parseable};
//! use rtnetlink::constants::{RTM_GETLINK, NLM_F_ROOT, NLM_F_REQUEST, NLM_F_MATCH};
//!
//! // a packet captured with tcpdump that was sent when running `ip link show`
//! static PKT: [u8; 40] = [
//! 0x28, 0x00, 0x00, 0x00, // length
//! 0x12, 0x00, // message type
//! 0x01, 0x03, // flags
//! 0x34, 0x0e, 0xf9, 0x5a, // sequence number
//! 0x00, 0x00, 0x00, 0x00, // port id
//! // payload
//! 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
//! 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
//! 0x08, 0x00, 0x1d, 0x00, 0x01, 0x00, 0x00, 0x00];
//!
//! fn main() {
//! let pkt: NetlinkMessage =
//! // Create a buffer. Notice the double &&. That is because Parseable<NetlinkMessage> is
//! // implemented for NetlinkBuffer<&T> not NetlinkBuffer<T>. The reason behing this is
//! // that we want the storage T to be able to outlive our NetlinkBuffer, if necessary. It
//! // feels a bit weird here but can be useful in other circumstances.
//! NetlinkBuffer::new_checked(&&PKT[..])
//! .unwrap()
//! // Convert the buffer into an actual message. This is when the parsing occurs.
//! .parse()
//! .unwrap();
//!
//! println!("{:#?}", pkt);
//! }
//! ```
//!
//! This prints:
//!
//! ```no_rust
//! NetlinkMessage {
//! header: NetlinkHeader {
//! length: 40,
//! message_type: 18,
//! flags: NetlinkFlags(769),
//! sequence_number: 1526271540,
//! port_number: 0
//! },
//! message: GetLink(
//! LinkMessage {
//! header: LinkHeader {
//! address_family: 17,
//! index: 0,
//! link_layer_type: Netrom,
//! flags: LinkFlags(0),
//! change_mask: LinkFlags(0)
//! },
//! nlas: [ExtMask(1)]
//! }
//! ),
//! finalized: true
//! }
//! ```
//!
//! ## Emitting messages
//!
//! TODO
//!
//!
//! ## Should I use Buffer types or Message type (`NetlinkBuffer` or `NetlinkMessage`)?
//!
//! Message types are much more convenient to work with. They are full blown rust types, and easier
//! to manipulate. I use buffer types mostly as temporary intermediate representations between
//! bytes and message types.
//!
//! However, if you have to treat large quantities of packets and are only interested in a few of
//! them, buffer types may be useful, because they allow to perform quick check on the messages
//! without actually parsing them.
//!
//! TODO
//!
//! # Tokio integration
//!
//! TODO
//!
#![cfg_attr(feature = "nightly", feature(tool_attributes))]
#![cfg_attr(feature = "nightly", feature(custom_attribute))]
#![cfg_attr(feature = "nightly", allow(unused_attributes))]
#![cfg_attr(feature = "nightly", rustfmt::skip)]
extern crate byteorder;
extern crate bytes;
extern crate core;
extern crate libc;
extern crate netlink_socket;
pub mod constants;
// We do not re-export all the constants. They are used internally and re-exported in submodules.
mod bindgen_constants;
/// Types representing netlink packets, and providing message serialization and deserialization.
mod packets;
pub use self::packets::*;
mod errors;
pub use self::errors::*;
// Tokio
#[cfg(feature = "tokio_support")] #[macro_use] extern crate log;
#[cfg(feature = "tokio_support")] #[macro_use] extern crate futures;
#[cfg(feature = "tokio_support")] extern crate tokio_io;
#[cfg(feature = "tokio_support")] extern crate tokio_reactor;
#[cfg(feature = "tokio_support")] mod framed;
#[cfg(feature = "tokio_support")] mod codecs;
#[cfg(feature = "tokio_support")] pub use codecs::*;
#[cfg(feature = "tokio_support")] pub use self::framed::*;
// Tests
#[cfg(test)] #[macro_use] extern crate lazy_static;
| true
|
56d8b4864de1c1890f9814fc7f6f075aee490f34
|
Rust
|
telumo/rust_design_pattern
|
/src/builder/mod.rs
|
UTF-8
| 2,238
| 3.59375
| 4
|
[] |
no_license
|
// ここから
trait Builder {
fn make_title(&mut self, title: String);
fn make_string(&mut self, str: String);
fn make_items(&mut self, items: Vec<String>);
fn close(&mut self);
fn get_result(&mut self) -> String;
}
struct Director<T: Builder> {
builder: T,
}
// ここまでフレームワーク
impl<T: Builder + Copy> Director<T> {
fn new(builder: &T ) -> Self {
let director : Director<T> = Director {
builder: *builder
};
director
}
fn construct(&mut self) {
self.builder.make_title("Greeting".into());
self.builder.make_string("from morning to midday".into());
self.builder
.make_items(vec!["Good Morning".into(), "Hello".into()]);
self.builder.make_string("after evening".into());
self.builder.make_items(vec![
"Good evening".into(),
"Good night".into(),
"See you tomorrow".into(),
]);
self.builder.close();
}
}
// TODO: コピートレイトが実装できない
#[derive(Copy)]
struct TextBuilder {
buffer: Vec<String>,
}
impl TextBuilder {
fn new() -> Self {
TextBuilder {
buffer: Vec::new()
}
}
}
impl Builder for TextBuilder {
fn make_title(&mut self, title: String) {
self.buffer.push("=============================\n".into());
self.buffer.push(format!("[ {} ] \n", title));
self.buffer.push("\n".into());
}
fn make_string(&mut self, str: String) {
self.buffer.push(format!("■{}\n", str));
self.buffer.push("\n".into());
}
fn make_items(&mut self, items: Vec<String>) {
for item in items {
self.buffer.push(format!(" ・{}\n", item));
}
self.buffer.push("\n".into());
}
fn close(&mut self) {
self.buffer.push("=============================\n".into());
}
fn get_result(&mut self) -> String {
self.buffer.clone().into_iter().collect()
}
}
pub fn run() {
let mut textBuilder = TextBuilder::new();
let mut director = Director::new(&mut textBuilder);
director.construct();
let result = textBuilder.get_result();
println!("{:?}", result);
}
| true
|
cd733061e160715a2e5159bf2d372b0134bcb153
|
Rust
|
mechiru/iso-4217
|
/src/error.rs
|
UTF-8
| 542
| 3.515625
| 4
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::fmt;
/// An error which can be returned when parsing `&str` or `u32`.
#[derive(Debug, PartialEq, Clone)]
pub enum ParseCodeError {
Alpha(String),
Num(u32),
}
impl fmt::Display for ParseCodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use ParseCodeError::*;
match self {
Alpha(v) => write!(f, "`{}` is no match any alphabetic code.", v),
Num(v) => write!(f, "{} is no match numeric code.", v),
}
}
}
impl std::error::Error for ParseCodeError {}
| true
|
eb095d9db12438244179d77e54033de972526a0d
|
Rust
|
urnest/urnest
|
/ruf/ruf_newtype/test-newtype.rs
|
UTF-8
| 7,629
| 3
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
// Copyright (c) 2021 Trevor Taylor
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all.
// Trevor Taylor makes no representations about the suitability of this
// software for any purpose. It is provided "as is" without express or
// implied warranty.
//
extern crate ruf_newtype;
extern crate ruf_assert;
// Unique* types each based on specified BaseType. Where BaseType is a
// primitive type, the new type will have most of the methods of the base type
// (but cannot be used where the BaseType is required).
//
// * For example, I1 cannot be used where I2 is required and vice-versa.
//
struct I1_; impl ruf_newtype::Tag for I1_ { type BaseType = i32;}
struct I2_; impl ruf_newtype::Tag for I2_ { type BaseType = f64;}
struct B1_; impl ruf_newtype::Tag for B1_ { type BaseType = bool;}
struct S1_; impl ruf_newtype::Tag for S1_ { type BaseType = String;}
type I1 = ruf_newtype::T<I1_>;
type I2 = ruf_newtype::T<I2_>;
type B1 = ruf_newtype::T<B1_>;
type S1 = ruf_newtype::T<S1_>;
// REVISIT: macro so that can write ruf_newtype::NewType!(I1,i32);
use std::hash::Hasher;
use std::hash::Hash;
use ruf_assert as assert;
fn main() {
let a = I1 {value: 22};
let b = I1 {value: -6};
let c = a + b;
assert::equal(&c, &I1{value:16});
assert::less(&c, &I1{value:17});
assert::less_equal(&c, &I1{value:17});
assert::less_equal(&c, &I1{value:16});
/*
** does not work see "two strings added together" comment in mod.rs
assert::equal(& (S1{value: String::from("fred")}+S1{value: String::from(" jones")}),
& S1{value: String::from("fred jones")});
*/
let mut d = I1 {value: 3};
d += I1{value:4};
assert::greater_equal(&d, &I1{value:7});
assert::greater(&d, &I1{value:6});
assert::equal(&d, &I1{value:7});
/* REVISIT: wtf?
let mut d = S1{value: String::from("fred")};
d += S1{value: String::from(" jones")};
assert::equal(&d, & S1{value: String::from("fred jones")});
*/
assert::equal(&(I2{value:0.0} + I2::new(66.0)), &I2::new(66.0));
assert::equal(&format!("{:b}", I1{value:8}).as_str(), &"1000"); // Binary
assert::equal(&(I1{value:2} & I1::new(3)), &I1::new(2));
let mut d = I1 {value: 3};
d &= I1{value:2};
assert::equal(&d, &I1::new(2));
assert::equal(&(I1{value:6} | I1::new(3)), &I1::new(7));
let mut d = I1 {value: 6};
d |= I1{value:3};
assert::equal(&d, &I1::new(7));
assert::equal(&(I1{value:6} ^ I1::new(3)), &I1::new(5));
let mut d = I1 {value: 6};
d ^= I1{value:3};
assert::equal(&d, &I1::new(5));
let mut d = I1 {value: 6}.clone();
assert::equal(&d, &I1::new(6));
d.clone_from(&I1::new(7));
assert::equal(&d, &I1::new(7));
let c = I1 {value: 6};
let d = c; // copy
assert::equal(&c, &d);
assert::equal(&format!("{:?}", I1{value:8}).as_str(), &"8"); // Debug
let c = I1::default();
assert::equal(&c, &I1{value: Default::default()});
assert::equal(&format!("{}", I1{value:8}).as_str(), &"8"); // Display
let a = I1 {value: 22};
let b = I1 {value: 11};
let c = a / b;
assert::equal(&c, &I1{value:2});
let mut d = I1 {value: 8};
d /= I1{value:2};
assert::equal(&d, &I1{value:4});
//let d = NonZeroI32{ 6 };
//REVISIT: awaits implementation assert::equal(&I1::from(d), &I1{value:6});
let d = I1 {value: 8};
let mut h1 = std::collections::hash_map::DefaultHasher::new();
d.hash(&mut h1);
let mut h2 = std::collections::hash_map::DefaultHasher::new();
let f : i32 = 8;
f.hash(&mut h2);
assert::equal(&h1.finish(), &h2.finish());
assert::equal(&format!("{:e}", I1{value:42}).as_str(), &"4.2e1"); // LowerExp
assert::equal(&format!("{:x}", I1{value:42}).as_str(), &"2a"); // LowerHex
assert::equal(&(I2{value:2.0} * I2::new(66.0)), &I2::new(132.0));
let mut d = I1 {value: 3};
d *= I1{value:4};
assert::equal(&d, &I1{value:12});
assert::equal(& -I2{value:2.0}, &I2::new(-2.0));
assert::equal(& !B1{value:true}, &B1::new(false));
assert::equal(&format!("{:o}", I1{value:42}).as_str(), &"52"); // Octal
let d = [ I1{value:2}, I1{value:3} ];
let e = d.iter().product();
assert::equal(&e, &I1{value:6});
assert::equal(& (I1{value: 10} % I1{value: 3}), &I1{value: 1});
let mut d = I1{value: 10};
d %= I1{value: 3};
assert::equal(&d, &I1{value: 1});
assert::equal(& (I1{value: 1} << 2), &I1{value: 4});
let mut d = I1{value: 1};
d <<= 2;
assert::equal(&d, &I1{value: 4});
assert::equal(& (I1{value: 4} >> 2), &I1{value: 1});
let mut d = I1{value: 4};
d >>= 2;
assert::equal(&d, &I1{value: 1});
assert::equal(& (I1{value: 4} - I1{value: 2}), &I1{value: 2});
let mut d = I1{value: 4};
d -= I1{value:2};
assert::equal(&d, &I1{value: 2});
let d = [ I1{value:2}, I1{value:3} ];
let e = d.iter().sum();
assert::equal(&e, &I1{value:5});
assert::equal(&format!("{:E}", I1{value:42}).as_str(), &"4.2E1"); // LowerExp
assert::equal(&format!("{:X}", I1{value:42}).as_str(), &"2A"); // LowerHex
let mut d = S1{value: String::from("fred")};
let e = d.clone();
assert::equal(&d, &e);
d.clear();
assert::not_equal(&d, &e);
assert::equal(&d, &S1::from(""));
assert::equal(&I1 {value: -6}.abs(), &I1{value:6});
assert::equal(&S1::from("fred").as_bytes(), &String::from("fred").as_bytes());
assert::equal(&S1::with_capacity(10).capacity(), &10);
let mut d = S1{value: String::from("fred")};
d.drain(2..);
assert::equal(&d, &S1::from("fr"));
// 𝄞music
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
0x0073, 0x0069, 0x0063];
assert::equal(&S1::from("𝄞music"), &S1::from_utf16(v).unwrap());
// 𝄞mu<invalid>ic
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
0xD800, 0x0069, 0x0063];
assert::equal(&S1::from_utf16(v).is_err(), &true);
// 𝄞mus<invalid>ic<invalid>
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
0x0073, 0xDD1E, 0x0069, 0x0063,
0xD834];
assert::equal(&S1::from("𝄞mus\u{FFFD}ic\u{FFFD}"),&S1::from_utf16_lossy(v));
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = S1::from_utf8(sparkle_heart).unwrap();
assert::equal(&S1::from("💖"), &sparkle_heart);
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
let sparkle_heart = unsafe {
S1::from_utf8_unchecked(sparkle_heart)
};
assert::equal(&S1::from("💖"), &sparkle_heart);
let s = S1::from("hello");
let bytes = s.into_bytes();
assert::equal(&bytes[1], &101);
let mut s = S1::from("fred");
s.reserve(3);
assert::greater_equal(&s.capacity(), &7);
let mut s = S1::from("fred");
s.reserve_exact(3);
assert::greater_equal(&s.capacity(), &7);
let mut x = S1::from("");
x.push('a');
assert::equal(&x, &S1::from("a"));
assert::equal(&x.pop().unwrap(), &'a');
let mut x = S1::from("fred");
x.remove(2);
assert::equal(&x, &S1::from("frd"));
x.retain(|c| c != 'r');
assert::equal(&x, &S1::from("fd"));
assert::equal(&x.split_off(1), &S1::from("d"));
assert::equal(&x, &S1::from("f"));
let mut x = S1::from("fred");
x.truncate(2);
assert::equal(&x, &S1::from("fr"));
}
| true
|
761493a99aee8b13c3c468e6255e6d8e2d1f24a8
|
Rust
|
dsherret/swc
|
/ecmascript/minifier/src/compress/optimize/join_vars.rs
|
UTF-8
| 4,682
| 3
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use super::Optimizer;
use crate::{compress::util::is_directive, mode::Mode};
use swc_common::util::take::Take;
use swc_ecma_ast::*;
use swc_ecma_utils::StmtLike;
/// Methods related to option `join_vars`.
impl<M> Optimizer<'_, M>
where
M: Mode,
{
/// Join variables.
///
/// This method may move variables to head of for statements like
///
/// `var a; for(var b;;);` => `for(var a, b;;);`
pub(super) fn join_vars<T>(&mut self, stmts: &mut Vec<T>)
where
T: StmtLike,
{
if !self.options.join_vars {
return;
}
{
// Check if we can join variables.
let can_work =
stmts
.windows(2)
.any(|stmts| match (stmts[0].as_stmt(), stmts[1].as_stmt()) {
(Some(Stmt::Decl(Decl::Var(l))), Some(r)) => match r {
Stmt::Decl(Decl::Var(r)) => l.kind == r.kind,
Stmt::For(ForStmt { init: None, .. }) => l.kind == VarDeclKind::Var,
Stmt::For(ForStmt {
init:
Some(VarDeclOrExpr::VarDecl(VarDecl {
kind: VarDeclKind::Var,
..
})),
..
}) => l.kind == VarDeclKind::Var,
_ => false,
},
_ => false,
});
if !can_work {
return;
}
}
tracing::debug!("join_vars: Joining variables");
self.changed = true;
let mut cur: Option<VarDecl> = None;
let mut new = vec![];
for stmt in stmts.take() {
match stmt.try_into_stmt() {
Ok(stmt) => {
if is_directive(&stmt) {
new.push(T::from_stmt(stmt));
continue;
}
match stmt {
Stmt::Decl(Decl::Var(var)) => match &mut cur {
Some(v) if var.kind == v.kind => {
v.decls.extend(var.decls);
}
_ => {
new.extend(
cur.take().map(Decl::Var).map(Stmt::Decl).map(T::from_stmt),
);
cur = Some(var)
}
},
Stmt::For(mut stmt) => match &mut stmt.init {
Some(VarDeclOrExpr::VarDecl(var)) => match &mut cur {
Some(cur) if cur.kind == var.kind => {
// Merge
cur.decls.append(&mut var.decls);
var.decls = cur.decls.take();
new.push(T::from_stmt(Stmt::For(stmt)))
}
_ => {
new.extend(
cur.take().map(Decl::Var).map(Stmt::Decl).map(T::from_stmt),
);
new.push(T::from_stmt(Stmt::For(stmt)))
}
},
None => {
stmt.init = cur.take().map(VarDeclOrExpr::VarDecl);
new.push(T::from_stmt(Stmt::For(stmt)))
}
_ => {
new.extend(
cur.take().map(Decl::Var).map(Stmt::Decl).map(T::from_stmt),
);
new.push(T::from_stmt(Stmt::For(stmt)))
}
},
_ => {
new.extend(cur.take().map(Decl::Var).map(Stmt::Decl).map(T::from_stmt));
new.push(T::from_stmt(stmt))
}
}
}
Err(item) => {
new.extend(cur.take().map(Decl::Var).map(Stmt::Decl).map(T::from_stmt));
new.push(item);
}
}
}
new.extend(cur.take().map(Decl::Var).map(Stmt::Decl).map(T::from_stmt));
*stmts = new;
}
}
| true
|
5983b336c57b3b72eaaf846c61108a31f4ba065c
|
Rust
|
tokio-rs/tokio
|
/tokio/src/io/util/write_int.rs
|
UTF-8
| 4,601
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
use crate::io::AsyncWrite;
use bytes::BufMut;
use pin_project_lite::pin_project;
use std::future::Future;
use std::io;
use std::marker::PhantomPinned;
use std::mem::size_of;
use std::pin::Pin;
use std::task::{Context, Poll};
macro_rules! writer {
($name:ident, $ty:ty, $writer:ident) => {
writer!($name, $ty, $writer, size_of::<$ty>());
};
($name:ident, $ty:ty, $writer:ident, $bytes:expr) => {
pin_project! {
#[doc(hidden)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct $name<W> {
#[pin]
dst: W,
buf: [u8; $bytes],
written: u8,
// Make this future `!Unpin` for compatibility with async trait methods.
#[pin]
_pin: PhantomPinned,
}
}
impl<W> $name<W> {
pub(crate) fn new(w: W, value: $ty) -> Self {
let mut writer = Self {
buf: [0; $bytes],
written: 0,
dst: w,
_pin: PhantomPinned,
};
BufMut::$writer(&mut &mut writer.buf[..], value);
writer
}
}
impl<W> Future for $name<W>
where
W: AsyncWrite,
{
type Output = io::Result<()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut me = self.project();
if *me.written == $bytes as u8 {
return Poll::Ready(Ok(()));
}
while *me.written < $bytes as u8 {
*me.written += match me
.dst
.as_mut()
.poll_write(cx, &me.buf[*me.written as usize..])
{
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),
Poll::Ready(Ok(0)) => {
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
}
Poll::Ready(Ok(n)) => n as u8,
};
}
Poll::Ready(Ok(()))
}
}
};
}
macro_rules! writer8 {
($name:ident, $ty:ty) => {
pin_project! {
#[doc(hidden)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct $name<W> {
#[pin]
dst: W,
byte: $ty,
// Make this future `!Unpin` for compatibility with async trait methods.
#[pin]
_pin: PhantomPinned,
}
}
impl<W> $name<W> {
pub(crate) fn new(dst: W, byte: $ty) -> Self {
Self {
dst,
byte,
_pin: PhantomPinned,
}
}
}
impl<W> Future for $name<W>
where
W: AsyncWrite,
{
type Output = io::Result<()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let me = self.project();
let buf = [*me.byte as u8];
match me.dst.poll_write(cx, &buf[..]) {
Poll::Pending => Poll::Pending,
Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())),
Poll::Ready(Ok(0)) => Poll::Ready(Err(io::ErrorKind::WriteZero.into())),
Poll::Ready(Ok(1)) => Poll::Ready(Ok(())),
Poll::Ready(Ok(_)) => unreachable!(),
}
}
}
};
}
writer8!(WriteU8, u8);
writer8!(WriteI8, i8);
writer!(WriteU16, u16, put_u16);
writer!(WriteU32, u32, put_u32);
writer!(WriteU64, u64, put_u64);
writer!(WriteU128, u128, put_u128);
writer!(WriteI16, i16, put_i16);
writer!(WriteI32, i32, put_i32);
writer!(WriteI64, i64, put_i64);
writer!(WriteI128, i128, put_i128);
writer!(WriteF32, f32, put_f32);
writer!(WriteF64, f64, put_f64);
writer!(WriteU16Le, u16, put_u16_le);
writer!(WriteU32Le, u32, put_u32_le);
writer!(WriteU64Le, u64, put_u64_le);
writer!(WriteU128Le, u128, put_u128_le);
writer!(WriteI16Le, i16, put_i16_le);
writer!(WriteI32Le, i32, put_i32_le);
writer!(WriteI64Le, i64, put_i64_le);
writer!(WriteI128Le, i128, put_i128_le);
writer!(WriteF32Le, f32, put_f32_le);
writer!(WriteF64Le, f64, put_f64_le);
| true
|
536343782279d933282a5455c5d3f92b5c3356a9
|
Rust
|
Dooskington/LD46-Lighthouse-Keeper
|
/src/game/transform.rs
|
UTF-8
| 769
| 2.71875
| 3
|
[
"Zlib"
] |
permissive
|
use crate::game::{Point2f, Vector2d, Vector2f};
use specs::prelude::*;
#[derive(Debug)]
pub struct TransformComponent {
pub position: Vector2d,
pub last_position: Vector2d,
pub scale: Vector2f,
}
impl Component for TransformComponent {
type Storage = FlaggedStorage<Self, VecStorage<Self>>;
}
impl TransformComponent {
pub fn new(position: Vector2d, scale: Vector2f) -> Self {
TransformComponent {
position,
last_position: position,
scale,
}
}
}
impl Default for TransformComponent {
fn default() -> Self {
TransformComponent {
position: Vector2d::zeros(),
last_position: Vector2d::zeros(),
scale: Vector2f::new(1.0, 1.0),
}
}
}
| true
|
df9e84eee25a67f9c1f63a7728093ea681969d8d
|
Rust
|
AlexEne/wasm_interp
|
/wasm/src/core/executor/stack_ops.rs
|
UTF-8
| 1,686
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
use std::convert::{TryFrom, TryInto};
use crate::core::{stack_entry::StackEntry, Stack};
use anyhow::{anyhow, Result};
pub fn get_stack_top(stack: &mut Stack, n: usize) -> Result<&[StackEntry]> {
if stack.working_count() < n {
Err(anyhow!("Not enough values on stack"))
} else {
Ok(stack.working_top(n))
}
}
pub fn unary_op<
ParamType: Sized + TryFrom<StackEntry, Error = anyhow::Error>,
RetType: Into<StackEntry>,
Func: Fn(ParamType) -> RetType,
>(
stack: &mut Stack,
func: Func,
) -> Result<()> {
let arg = get_stack_top(stack, 1)?[0];
stack.pop();
let ret = func(arg.try_into()?);
stack.push(ret.into());
Ok(())
}
pub fn unary_boolean_op<
ParamType: Sized + TryFrom<StackEntry, Error = anyhow::Error>,
Func: Fn(ParamType) -> bool,
>(
stack: &mut Stack,
func: Func,
) -> Result<()> {
unary_op(stack, |p: ParamType| if func(p) { 1u32 } else { 0u32 })
}
pub fn binary_op<
ParamType: Sized + TryFrom<StackEntry, Error = anyhow::Error>,
RetType: Into<StackEntry>,
Func: Fn(ParamType, ParamType) -> RetType,
>(
stack: &mut Stack,
func: Func,
) -> Result<()> {
let args = get_stack_top(stack, 2)?;
let args = [args[0], args[1]];
stack.pop_n(2);
let ret = func(args[0].try_into()?, args[1].try_into()?);
stack.push(ret.into());
Ok(())
}
pub fn binary_boolean_op<
ParamType: Sized + TryFrom<StackEntry, Error = anyhow::Error>,
Func: Fn(ParamType, ParamType) -> bool,
>(
stack: &mut Stack,
func: Func,
) -> Result<()> {
binary_op(
stack,
|p1: ParamType, p2: ParamType| if func(p1, p2) { 1u32 } else { 0u32 },
)
}
| true
|
600f2eb6a45fcd32b51ccc70a80dc305016da376
|
Rust
|
Unesty/Doing
|
/attempts/petgraph5/src/ps_utils.rs
|
UTF-8
| 2,576
| 3.421875
| 3
|
[] |
no_license
|
use crate::avr_interpreter::{ProcessorState, execute_instruction};
// Generate all valid states from a list of instructions
pub fn generate_states(instructions: &[u8]) -> Vec<ProcessorState> {
let mut states = vec![];
for i in 0..256 {
let mut state = ProcessorState::new();
state.pc = 0;
state.registers[0] = i;
for &instr in instructions {
execute_instruction(&mut state, instr);
}
states.push(state);
}
states
}
// Count the number of possibilities for a processor state
pub fn count_possibilities(state: &ProcessorState) -> u32 {
let mut count = 0;
let mut visited = vec![false; 256];
let mut current_state = state.clone();
visited[current_state.registers[0] as usize] = true;
while !visited[current_state.registers[0] as usize] {
visited[current_state.registers[0] as usize] = true;
current_state.pc = 0;
for &instr in ¤t_state.memory {
execute_instruction(&mut current_state, instr);
}
count += 1;
}
count
}
// Calculates the number of possibilities of the system starting from the given state.
pub fn count_possibilities2(state: &ProcessorState) -> u64 {
// Create a memory region with all instructions set to zero
let mut mem_region = MemoryRegion::default();
// Set the instructions in the memory region to match the state
for (i, &instr) in state.instructions.iter().enumerate() {
mem_region.set_instruction(i as u8, instr);
}
// Execute the memory region and count the number of times each instruction is executed
let mut instruction_counts = [0; 256];
let mut pc = 0;
while pc < mem_region.len() {
let instr = mem_region.get_instruction(pc).unwrap();
instruction_counts[instr as usize] += 1;
pc += 1;
}
// Calculate the number of possibilities as the product of the number of times each instruction is executed
let mut possibilities = 1;
for count in instruction_counts.iter() {
if *count > 0 {
possibilities *= *count;
}
}
possibilities
}
// Compare two processor states and return a score
// A higher score indicates a state with better survival chances
pub fn compare_states(state1: &ProcessorState, state2: &ProcessorState) -> u32 {
let count1 = count_possibilities(state1);
let count2 = count_possibilities(state2);
if count1 == count2 {
return 0;
}
if count1 > count2 {
count1 - count2
} else {
count2 - count1
}
}
| true
|
04429e256c0ab92d97c5d0b216d5b635a867d02b
|
Rust
|
khollbach/advent
|
/2019/rust/12/src/lib.rs
|
UTF-8
| 4,726
| 3.625
| 4
|
[] |
no_license
|
use lazy_static::lazy_static;
use num::integer;
use regex::Regex;
use std::cmp::Ordering;
use std::fmt;
use std::io::prelude::*;
pub fn read_input<R: BufRead>(input: R) -> Vec<Moon> {
const I: &str = r"(-?\d+)";
lazy_static! {
static ref RE: Regex = Regex::new(&format!("^<x={}, y={}, z={}>$", I, I, I)).unwrap();
}
let moons: Vec<_> = input
.lines()
.map(|line| {
let line = line.unwrap();
let caps = RE.captures(&line).unwrap();
let x: i64 = caps[1].parse().unwrap();
let y: i64 = caps[2].parse().unwrap();
let z: i64 = caps[3].parse().unwrap();
Moon::new(Point { x, y, z })
})
.collect();
assert_eq!(moons.len(), 4);
moons
}
/// Simulate the system for `time_steps` rounds and the output the total energy at the end.
pub fn simulate(mut moons: Vec<Moon>, time_steps: usize) -> i64 {
assert_eq!(moons.len(), 4);
for _ in 0..time_steps {
time_step(&mut moons);
}
moons.iter().map(|m| m.total_energy()).sum()
}
/// Simulate the system for 1 time step.
fn time_step(moons: &mut Vec<Moon>) {
let n = moons.len();
// Apply gravity to each pair of moons, update their velocities.
for i in 0..n - 1 {
for j in i + 1..n {
let (fst, snd) = moons.split_at_mut(j);
Moon::apply_gravity(&mut fst[i], &mut snd[0]);
}
}
// Apply velocity to each moon, updating its position.
for m in moons {
m.apply_vel();
}
}
/// How many steps does it take to return to a previous state? Note that the first repeated state
/// is always the initial state, since the state transition function is one-to-one. (You can check
/// this yourself; I won't prove it here.)
///
/// We take the following shortcut. Compute the time it takes for the (position, velocity) to
/// repeat in the x coordinate. Then do the same for the y coordinate, and the z coordinate. Find
/// the LCM of all these numbers, and you're done! It turns out the state transitions of each
/// coordinate are entirely independant of one another, so this suffices.
pub fn repeat_time(moons: Vec<Moon>) -> i64 {
let x_time = repeat_time_coord(moons.clone(), |p| p.x);
let y_time = repeat_time_coord(moons.clone(), |p| p.y);
let z_time = repeat_time_coord(moons.clone(), |p| p.z);
// lcm(a, b, c) == lcm(a, lcm(b, c))
integer::lcm(x_time, integer::lcm(y_time, z_time))
}
fn repeat_time_coord<F>(mut moons: Vec<Moon>, coord: F) -> i64
where
F: Fn(Point) -> i64,
{
let coord_state = |moons: &[Moon]| -> (Vec<i64>, Vec<i64>) {
let pos = moons.iter().map(|m| coord(m.pos)).collect();
let vel = moons.iter().map(|m| coord(m.vel)).collect();
(pos, vel)
};
let init = coord_state(&moons);
for t in 0.. {
if t != 0 && coord_state(&moons) == init {
return t;
}
time_step(&mut moons);
}
unreachable!()
}
#[derive(Clone)]
pub struct Moon {
pos: Point,
vel: Point,
}
impl Moon {
fn new(initial_pos: Point) -> Self {
Self {
pos: initial_pos,
vel: Point::origin(),
}
}
fn apply_gravity(a: &mut Self, b: &mut Self) {
Self::apply_gravity_coord(a, b, |p| &mut p.x);
Self::apply_gravity_coord(a, b, |p| &mut p.y);
Self::apply_gravity_coord(a, b, |p| &mut p.z);
}
fn apply_gravity_coord<F>(a: &mut Self, b: &mut Self, coord: F)
where
F: Fn(&mut Point) -> &mut i64,
{
let dir = match coord(&mut a.pos).cmp(&mut coord(&mut b.pos)) {
Ordering::Less => 1,
Ordering::Greater => -1,
Ordering::Equal => 0,
};
*coord(&mut a.vel) += dir;
*coord(&mut b.vel) += -1 * dir;
}
fn apply_vel(&mut self) {
self.pos.x += self.vel.x;
self.pos.y += self.vel.y;
self.pos.z += self.vel.z;
}
fn total_energy(&self) -> i64 {
let potential = self.pos.energy();
let kinetic = self.vel.energy();
potential * kinetic
}
}
impl fmt::Debug for Moon {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "pos={:?}, vel={:?}", self.pos, self.vel)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct Point {
x: i64,
y: i64,
z: i64,
}
impl Point {
fn origin() -> Self {
Self { x: 0, y: 0, z: 0 }
}
/// L1 norm.
fn energy(self) -> i64 {
self.x.abs() + self.y.abs() + self.z.abs()
}
}
impl fmt::Debug for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "<x={:3}, y={:3}, z={:3}>", self.x, self.y, self.z)
}
}
| true
|
033a752d42e76d44ee4376d243711042d8f7f4f9
|
Rust
|
martingallagher/html5minify
|
/htmlminify_cli/src/main.rs
|
UTF-8
| 1,364
| 2.8125
| 3
|
[] |
no_license
|
use std::{fs::File, io, path::PathBuf};
use html5minify::Minifier;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(name = "html5minify", about = "HTML5Minify options")]
struct Opt {
/// Preserve whitespace
#[structopt(short = "w", long = "whitespace")]
disable_collapse_whitespace: bool,
/// Omit HTML5 doctype
#[structopt(short = "d", long = "doctype")]
omit_doctype: bool,
/// Preserve HTML comments
#[structopt(short = "c", long = "comments")]
preserve_comments: bool,
/// Input file
#[structopt(parse(from_os_str))]
input: PathBuf,
/// Output file, stdout if not set
#[structopt(parse(from_os_str))]
output: Option<PathBuf>,
}
fn main() -> io::Result<()> {
let opt = Opt::from_args();
let mut input = File::open(&opt.input)?;
if let Some(output) = &opt.output {
Minifier::new(&mut File::create(&output)?)
.collapse_whitespace(!opt.disable_collapse_whitespace)
.omit_doctype(opt.omit_doctype)
.preserve_comments(opt.preserve_comments)
.minify(&mut input)
} else {
Minifier::new(&mut io::stdout())
.collapse_whitespace(!opt.disable_collapse_whitespace)
.omit_doctype(opt.omit_doctype)
.preserve_comments(opt.preserve_comments)
.minify(&mut input)
}
}
| true
|
8e7396c8b4e368921ddf4575d40efee570104bf4
|
Rust
|
facebookincubator/antlir
|
/antlir/bzl/shape2/serialize_shape.rs
|
UTF-8
| 3,990
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// TODO(T139523690) this whole binary can be removed when target_tagger is dead,
// which will be shortly after buck1 is dead, after what I expect will be an
// extremely painful migration. In the meantime, the marked parts of this can be
// deleted as soon as we no longer support buck1.
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use absolute_path::AbsolutePathBuf;
use anyhow::Context;
use anyhow::Result;
use clap::Parser;
use serde_json::Value;
#[derive(Parser)]
struct Args {
input: PathBuf,
output: PathBuf,
}
// TODO(T139523690) this can be removed when buck1 is dead, since all paths will
// be relative.
fn rewrite_locations<P: AsRef<Path>>(project_root: P, shape: Value) -> Value {
match shape {
Value::Object(mut map) => {
if map.contains_key("__I_AM_TARGET__") {
map.entry("path").and_modify(|path_val| {
// On buck1, this will be a full path, but let's serialize
// it as a relpath for consistency with buck2, and to make
// it cacheable
let path = Path::new(path_val.as_str().expect("'path' must be a string"));
let relpath = match path.strip_prefix(project_root.as_ref()) {
Ok(relpath) => relpath,
// it must have already been relative
Err(_) => path,
};
*path_val = relpath.to_str().expect("always valid utf8").into()
});
map.remove("__I_AM_TARGET__");
map.into()
} else {
map.into_iter()
.map(|(k, v)| (k, rewrite_locations(project_root.as_ref(), v)))
.collect()
}
}
Value::Array(arr) => arr
.into_iter()
.map(|v| rewrite_locations(project_root.as_ref(), v))
.collect(),
other => other,
}
}
fn main() -> Result<()> {
let args = Args::parse();
let infile = stdio_path::open(&args.input).context("while opening input")?;
let outfile = stdio_path::create(&args.output).context("while opening output")?;
let shape: Value = serde_json::from_reader(infile).context("while deserializing shape")?;
let project_root = find_root::find_repo_root(
&AbsolutePathBuf::new(std::env::current_exe().expect("could not get argv[0]"))
.expect("argv[0] was not absolute"),
)
.context("while looking for repo root")?;
let shape = rewrite_locations(&project_root, shape);
serde_json::to_writer_pretty(&outfile, &shape).context("while serializing shape")?;
writeln!(&outfile).context("while writing trailing newline")?;
Ok(())
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn test_rewrite() {
assert_eq!(
json!({
"hello": "world",
"some": {
"nested": {
"target": {
"name": "foo//bar:baz",
"path": "this/is/relative",
}
}
}
}),
rewrite_locations(
"/but/it/was/absolute",
json!({
"hello": "world",
"some": {
"nested": {
"target": {
"name": "foo//bar:baz",
"path": "/but/it/was/absolute/this/is/relative",
"__I_AM_TARGET__": true,
}
}
}
})
),
);
}
}
| true
|
20e939b6222402e07a9421e641f01c382a976f71
|
Rust
|
WilliamVenner/rust-analyzer
|
/xtask/src/codegen/gen_lint_completions.rs
|
UTF-8
| 3,802
| 2.765625
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! Generates descriptors structure for unstable feature from Unstable Book
use std::path::{Path, PathBuf};
use quote::quote;
use walkdir::WalkDir;
use xshell::{cmd, read_file};
use crate::{
codegen::{project_root, reformat, update, Mode, Result},
run_rustfmt,
};
pub fn generate_lint_completions(mode: Mode) -> Result<()> {
if !Path::new("./target/rust").exists() {
cmd!("git clone --depth=1 https://github.com/rust-lang/rust ./target/rust").run()?;
}
let ts_features = generate_descriptor("./target/rust/src/doc/unstable-book/src".into())?;
cmd!("curl http://rust-lang.github.io/rust-clippy/master/lints.json --output ./target/clippy_lints.json").run()?;
let ts_clippy = generate_descriptor_clippy(&Path::new("./target/clippy_lints.json"))?;
let ts = quote! {
use crate::completions::attribute::LintCompletion;
#ts_features
#ts_clippy
};
let contents = reformat(ts.to_string().as_str())?;
let destination = project_root().join("crates/completion/src/generated_lint_completions.rs");
update(destination.as_path(), &contents, mode)?;
run_rustfmt(mode)?;
Ok(())
}
fn generate_descriptor(src_dir: PathBuf) -> Result<proc_macro2::TokenStream> {
let definitions = ["language-features", "library-features"]
.iter()
.flat_map(|it| WalkDir::new(src_dir.join(it)))
.filter_map(|e| e.ok())
.filter(|entry| {
// Get all `.md ` files
entry.file_type().is_file() && entry.path().extension().unwrap_or_default() == "md"
})
.map(|entry| {
let path = entry.path();
let feature_ident = path.file_stem().unwrap().to_str().unwrap().replace("-", "_");
let doc = read_file(path).unwrap();
quote! { LintCompletion { label: #feature_ident, description: #doc } }
});
let ts = quote! {
pub(super) const FEATURES: &[LintCompletion] = &[
#(#definitions),*
];
};
Ok(ts)
}
#[derive(Default)]
struct ClippyLint {
help: String,
id: String,
}
fn generate_descriptor_clippy(path: &Path) -> Result<proc_macro2::TokenStream> {
let file_content = read_file(path)?;
let mut clippy_lints: Vec<ClippyLint> = vec![];
for line in file_content.lines().map(|line| line.trim()) {
if line.starts_with(r#""id":"#) {
let clippy_lint = ClippyLint {
id: line
.strip_prefix(r#""id": ""#)
.expect("should be prefixed by id")
.strip_suffix(r#"","#)
.expect("should be suffixed by comma")
.into(),
help: String::new(),
};
clippy_lints.push(clippy_lint)
} else if line.starts_with(r#""What it does":"#) {
// Typical line to strip: "What is doest": "Here is my useful content",
let prefix_to_strip = r#""What it does": ""#;
let suffix_to_strip = r#"","#;
let clippy_lint = clippy_lints.last_mut().expect("clippy lint must already exist");
clippy_lint.help = line
.strip_prefix(prefix_to_strip)
.expect("should be prefixed by what it does")
.strip_suffix(suffix_to_strip)
.expect("should be suffixed by comma")
.into();
}
}
let definitions = clippy_lints.into_iter().map(|clippy_lint| {
let lint_ident = format!("clippy::{}", clippy_lint.id);
let doc = clippy_lint.help;
quote! { LintCompletion { label: #lint_ident, description: #doc } }
});
let ts = quote! {
pub(super) const CLIPPY_LINTS: &[LintCompletion] = &[
#(#definitions),*
];
};
Ok(ts)
}
| true
|
e2f534fe1a096809ff10da1cf4d35661223210a8
|
Rust
|
GuMiner/rust-experiments
|
/cross/src/cross/analysis.rs
|
UTF-8
| 4,249
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
//! Performs separate-threaded analysis of images
use crate::egui::ColorImage;
use crate::egui::Rgba;
use std::sync::mpsc;
use clustering;
use super::config::Config;
// Doc comments: https://doc.rust-lang.org/reference/comments.html#:~:text=Comments%20in%20Rust%20code%20follow%20the%20general%20C%2B%2B,comments%20are%20interpreted%20as%20a%20form%20of%20whitespace.
// Might need to derive a few traits here
// https://doc.rust-lang.org/rust-by-example/trait/derive.html
#[derive(Clone, PartialEq)]
pub struct ColorPoint {
pub x: f64,
pub y: f64,
pub c: Rgba,
}
impl clustering::Elem for ColorPoint {
fn dimensions(&self) -> usize {
3
}
fn at(&self, i: usize) -> f64 {
self.c[i] as f64
}
}
pub struct AvgColor {
pub avg: [f32;3],
pub num: i32,
}
impl AvgColor {
fn new() -> Self {
AvgColor {
avg: [0.0, 0.0, 0.0],
num: 0,
}
}
fn add_color(&mut self, c: Rgba) {
self.avg[0] += c[0];
self.avg[1] += c[1];
self.avg[2] += c[2];
self.num += 1;
}
fn compute_average(&mut self) {
if self.num != 0 {
self.avg[0] /= self.num as f32;
self.avg[1] /= self.num as f32;
self.avg[2] /= self.num as f32;
}
}
}
pub fn update_pattern(image: ColorImage, config: Config, canceller: mpsc::Receiver<bool>) -> Vec<ColorPoint> {
let mut points = Vec::new();
// Config If: Take points then constrict to color limit.
pass_through(image, &config, &mut points, &canceller);
if points.len() > 0 {
let limited_points = limit_colors(&config, &mut points, &canceller);
limited_points
} else {
points
}
}
fn limit_colors(config: &Config, points: &mut Vec<ColorPoint>, canceller: &mpsc::Receiver<bool>) -> Vec<ColorPoint> {
// Config If: Find-closest and merge
// No need to reinvent the wheel, can use kmeans clustering
// Cluster
let mut limited_points = Vec::new();
let clusters = clustering::kmeans(config.num_colors as usize, &points, 100); // max-iters
match canceller.try_recv() {
Ok(_) => return limited_points,
Err(_) => {}
}
// print!("Computed a total of {} clusters\n", clusters.centroids.len());
// Find average colors for each cluster
let mut avg_cluster_colors = vec![];
for _ in 0..clusters.centroids.len() {
avg_cluster_colors.push(AvgColor::new());
}
for i in 0..clusters.membership.len() {
let cluster_id = clusters.membership[i];
avg_cluster_colors[cluster_id].add_color(clusters.elements[i].c);
}
for i in 0..clusters.centroids.len() {
avg_cluster_colors[i].compute_average();
}
// Expand out the clusters into a new set of colors
for i in 0..clusters.elements.len() {
let cluster_id = clusters.membership[i];
let cluster_color = avg_cluster_colors[cluster_id].avg;
limited_points.push(ColorPoint {
x: clusters.elements[i].x,
y: clusters.elements[i].y,
c: Rgba::from_rgb(cluster_color[0], cluster_color[1], cluster_color[2])});
}
limited_points
}
fn pass_through(image: ColorImage, config: &Config, points: &mut Vec<ColorPoint>, canceller: &mpsc::Receiver<bool>) {
if image.size[0] == 0 {
return
}
// Iterate in floating point to avoid rounding errors that generate slightly more expected points.
let y_step = image.size[1] as f64 / (config.num_height as f64);
let x_step = image.size[0] as f64 / (config.num_width as f64);
for y in 0..config.num_height {
// Early-exit if any data received.
match canceller.try_recv() {
Ok(_) => return,
Err(_) => {}
}
for x in 0..config.num_width {
// Round steps to avoid scrolling issues at image ends.
let x_eff = (x_step * (x as f64)) as usize;
let y_eff = (y_step * (y as f64)) as usize;
let color = image.pixels[x_eff + y_eff * image.size[0]];
points.push(ColorPoint {
x: x_eff as f64,
y: (y_eff as f64)*-1.0,
c: Rgba::from(color)});
}
}
}
| true
|
2031ef28d719f9401ed47a4496e3a899b137e960
|
Rust
|
VulkanWorks/korangar
|
/src/interface/windows/builder.rs
|
UTF-8
| 4,053
| 2.75
| 3
|
[] |
no_license
|
use cgmath::Vector2;
use graphics::Color;
use super::super::*;
const FRAME_WIDTH: f32 = 1.0;
const TOP_FRAME_HEIGHT: f32 = 22.0;
const FRAME_COLOR: Color = Color::new(30, 30, 30);
const TITLE_TEXT_COLOR: Color = Color::new(70, 70, 70);
const TITLE_TEXT_OFFSET: Vector2<f32> = Vector2::new(10.0, 4.0);
const TITLE_TEXT_SIZE: f32 = 13.0;
const ELEMENT_GAP: f32 = 4.0;
pub struct WindowBuilder {
counter: usize,
window_width: f32,
left_offset: f32,
top_offset: f32,
row_height: f32,
}
impl WindowBuilder {
pub fn new(window_width: f32) -> Self {
let counter = 0;
let top_offset = 0.0;
let left_offset = 0.0;
let row_height = 0.0;
return Self { counter, window_width, top_offset, left_offset, row_height };
}
pub fn reset(&mut self) {
self.top_offset = 0.0;
self.left_offset = 0.0;
self.row_height = 0.0;
}
pub fn inner_width(&self) -> f32 {
return self.window_width - FRAME_WIDTH * 2.0;
}
pub fn remaining_width(&self) -> f32 {
return self.inner_width() - self.left_offset;
}
pub fn new_row(&mut self) {
self.top_offset += self.row_height + ELEMENT_GAP;
self.left_offset = 0.0;
self.row_height = 0.0;
}
pub fn new_row_spaced(&mut self, spacing: f32) {
self.top_offset += self.row_height + ELEMENT_GAP + spacing;
self.left_offset = 0.0;
self.row_height = 0.0;
}
pub fn position(&mut self, size: Vector2<f32>) -> Vector2<f32> {
if self.left_offset + size.x > self.inner_width() {
self.new_row();
}
let position = Vector2::new(self.left_offset, self.top_offset);
self.left_offset += size.x + ELEMENT_GAP;
if size.y > self.row_height {
self.row_height = size.y;
}
return position;
}
pub fn unique_identifier(&mut self) -> usize {
let index = self.counter;
self.counter += 1;
return index;
}
fn finalize(&mut self) {
if self.row_height != 0.0 {
self.new_row();
}
}
fn window_background(&mut self, elements: Vec<Element>) -> Component {
let element_index = self.unique_identifier();
let position = Vector2::new(FRAME_WIDTH, TOP_FRAME_HEIGHT);
let size = Vector2::new(self.inner_width(), self.top_offset - FRAME_WIDTH);
//let background = Component::Rectangle(RectangleComponent::new(Vector2::new(0.0, 0.0), size, BACKGROUND_COLOR, BACKGROUND_COLOR));
let container = Component::Container(ContainerComponent::new(elements));
let hoverable = Component::Hoverable(HoverableComponent::new(size));
let components = vec![/*background,*/ hoverable, container];
let elements = vec![Element::new(components, element_index, position)];
return Component::Container(ContainerComponent::new(elements));
}
pub fn framed_window(&mut self, interface_state: &mut InterfaceState, title: &str, elements: Vec<Element>, position: Vector2<f32>) -> Element {
self.finalize();
let element_index = self.unique_identifier();
let frame_position = Vector2::new(0.0, 0.0);
let frame_size = Vector2::new(self.window_width, self.top_offset + TOP_FRAME_HEIGHT);
let frame_corner_radius = Vector4::new(8.0, 8.0, 8.0, 8.0);
let frame = Component::Rectangle(RectangleComponent::new(frame_position, frame_size, frame_corner_radius, FRAME_COLOR, FRAME_COLOR));
let title_text = Component::Text(TextComponent::new(TITLE_TEXT_OFFSET, title.to_string(), TITLE_TEXT_COLOR, TITLE_TEXT_SIZE));
let hoverable = Component::Hoverable(HoverableComponent::new(frame_size));
let draggable = Component::Draggable(DraggableComponent::new(interface_state));
let background = self.window_background(elements);
let components = vec![frame, title_text, hoverable, draggable, background];
return Element::new(components, element_index, position);
}
}
| true
|
cfe0bb68aee1e8a18d2015714add70256b555b80
|
Rust
|
ViliLipo/mini-pascal-compiler
|
/src/symboltable.rs
|
UTF-8
| 7,162
| 2.875
| 3
|
[] |
no_license
|
use crate::typedast::*;
use crate::address::Address;
use std::collections::HashMap;
#[derive(PartialEq)]
pub enum ConstructCategory {
SimpleVar,
ArrayVar,
Function(Vec<NodeType>, NodeType),
Procedure(Vec<NodeType>),
TypeId,
Special,
}
pub struct Entry {
pub name: String,
pub category: ConstructCategory,
pub value: String,
pub entry_type: NodeType,
pub scope_number: i32,
pub address: Address,
}
pub struct Scope {
pub scope_number: i32,
pub enclosing_scope_number: i32,
pub is_closed: bool,
}
impl Copy for Scope {}
impl Clone for Scope {
fn clone(&self) -> Scope {
*self
}
}
pub struct Symboltable {
scopestack: Vec<i32>,
current_scope_number: i32,
table: HashMap<i32, HashMap<String, Entry>>,
scope_information_table: HashMap<i32, Scope>,
generator_no: i32,
}
impl Symboltable {
fn get_new_scope_number(&mut self) -> i32 {
let no = self.generator_no;
self.generator_no = self.generator_no + 1;
no
}
pub fn enter_scope(&mut self, scope: Scope) {
self.scope_information_table
.insert(scope.scope_number, scope.clone());
self.scopestack.push(scope.scope_number);
self.current_scope_number = scope.scope_number;
}
pub fn get_current_scope_number(&self) -> i32 {
self.current_scope_number
}
pub fn new_scope_in_current_scope(&mut self, is_closed: bool) -> i32 {
match self.scopestack.last() {
Some(scope_number) => {
let enclosing_scope_number = scope_number.clone();
let no = self.get_new_scope_number();
let scope = Scope {
enclosing_scope_number,
scope_number: no,
is_closed,
};
self.table.insert(scope.scope_number, HashMap::new());
self.enter_scope(scope);
no
}
None => -1,
}
}
pub fn exit_scope(&mut self) {
self.scopestack.pop();
if let Some(no) = self.scopestack.last() {
self.current_scope_number = *no;
} else {
self.current_scope_number = 0;
}
}
pub fn add_entry(&mut self, entry: Entry) {
match self.table.get_mut(&entry.scope_number) {
Some(scope) => {
scope.insert(entry.name.clone(), entry);
}
None => (),
}
}
pub fn lookup(&self, name: &String) -> Option<&Entry> {
let mut scope_number: Option<&i32> = self.scopestack.last();
loop {
match scope_number {
Some(scope_no) => match self.lookup_explicit_scope(name, *scope_no) {
Some(entry) => return Some(entry),
None => {
match self.scope_information_table.get(scope_no) {
Some(scope) => {
scope_number = Some(&scope.enclosing_scope_number);
}
None => return None,
};
}
},
None => return None,
}
}
}
fn lookup_explicit_scope(&self, name: &String, scope_number: i32) -> Option<&Entry> {
match self.table.get(&scope_number) {
Some(scope) => match scope.get(name) {
Some(entry) => Some(entry),
None => None,
},
None => None,
}
}
pub fn in_current_scope(&self, name: &String) -> bool {
match self.scopestack.last() {
Some(scope) => match self.lookup_explicit_scope(name, *scope) {
Some(_entry) => true,
None => false,
},
None => false,
}
}
}
fn predefined_ids() -> Vec<Entry> {
let mut entries = Vec::new();
entries.push(Entry {
name: String::from("boolean"),
category: ConstructCategory::TypeId,
value: String::from("0"),
entry_type: NodeType::Simple(SimpleType::Boolean),
scope_number: 0,
address: Address::new_simple(0),
});
entries.push(Entry {
name: String::from("integer"),
category: ConstructCategory::TypeId,
value: String::from("0"),
entry_type: NodeType::Simple(SimpleType::Integer),
scope_number: 0,
address:Address::new_simple(0),
});
entries.push(Entry {
name: String::from("real"),
category: ConstructCategory::TypeId,
value: String::from("0"),
entry_type: NodeType::Simple(SimpleType::Real),
scope_number: 0,
address: Address::new_simple(0),
});
entries.push(Entry {
name: String::from("string"),
category: ConstructCategory::TypeId,
value: String::from(""),
entry_type: NodeType::Simple(SimpleType::String),
scope_number: 0,
address: Address::new_simple(0),
});
entries.push(Entry {
name: String::from("false"),
category: ConstructCategory::SimpleVar,
value: String::from("0"),
entry_type: NodeType::Simple(SimpleType::Boolean),
scope_number: 0,
address: Address::new_simple(0),
});
entries.push(Entry {
name: String::from("true"),
category: ConstructCategory::SimpleVar,
value: String::from("1"),
entry_type: NodeType::Simple(SimpleType::Boolean),
scope_number: 0,
address: Address::new_simple(1),
});
entries.push(Entry {
name: String::from("writeln"),
category: ConstructCategory::Special,
value: String::from(""),
entry_type: NodeType::Simple(SimpleType::String),
scope_number: 0,
address: Address::new_simple(0),
});
entries.push(Entry {
name: String::from("read"),
category: ConstructCategory::Special,
value: String::from(""),
entry_type: NodeType::Simple(SimpleType::String),
scope_number: 0,
address: Address::new_simple(0),
});
entries.push(Entry {
name: String::from("size"),
category: ConstructCategory::Special,
value: String::from(""),
entry_type: NodeType::Simple(SimpleType::Integer),
address: Address::new_simple(0),
scope_number: 0,
});
entries
}
pub fn get_symbol_table() -> Symboltable {
let scope_zero_info = Scope {
scope_number: 0,
enclosing_scope_number: -1,
is_closed: false,
};
let mut scope_zero: HashMap<String, Entry> = HashMap::new();
for entry in predefined_ids() {
scope_zero.insert(entry.name.clone(), entry);
}
let mut table: HashMap<i32, HashMap<String, Entry>> = HashMap::new();
let mut scope_table: HashMap<i32, Scope> = HashMap::new();
table.insert(0, scope_zero);
scope_table.insert(0, scope_zero_info);
Symboltable {
scope_information_table: scope_table,
table,
scopestack: vec![0],
current_scope_number: 0,
generator_no: 1,
}
}
| true
|
e4fdea5be72e7a388ed7737164231efa1be1daa7
|
Rust
|
HarrisonMc555/exercism
|
/rust/high-scores/src/lib.rs
|
UTF-8
| 743
| 3.03125
| 3
|
[] |
no_license
|
type Score = u32;
#[derive(Debug)]
pub struct HighScores {
scores: Vec<Score>,
sorted_scores: Vec<Score>,
}
impl HighScores {
pub fn new(scores: &[Score]) -> Self {
let mut sorted_scores = scores.to_vec();
sorted_scores.sort();
HighScores {
scores: scores.to_vec(),
sorted_scores,
}
}
pub fn scores(&self) -> &[Score] {
&self.scores
}
pub fn latest(&self) -> Option<Score> {
self.scores.last().copied()
}
pub fn personal_best(&self) -> Option<Score> {
self.sorted_scores.last().copied()
}
pub fn personal_top_three(&self) -> Vec<Score> {
self.sorted_scores.iter().rev().take(3).copied().collect()
}
}
| true
|
b0d4c660f26c10391e6de736b933b2661166b5e1
|
Rust
|
1ok1/droid-rust
|
/src/lib.rs
|
UTF-8
| 1,942
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
use std::os::raw::{c_char};
use std::ffi::{CString, CStr};
/// Expose the JNI interface for android below
#[cfg(target_os="android")]
#[allow(non_snake_case)]
pub mod android {
extern crate jni;
use super::*;
use self::jni::JNIEnv;
use self::jni::objects::{JClass, JString};
use self::jni::sys::{jstring};
#[no_mangle]
pub unsafe extern fn Java_com_lok1_rustndkexample_Greetings_greeting(env: JNIEnv, _: JClass, java_pattern: JString) -> jstring {
// Our Java companion code might pass-in "world" as a string, hence the name.
let world = rust_greeting(env.get_string(java_pattern).expect("invalid pattern string").as_ptr());
// Retake pointer so that we can use it below and allow memory to be freed when it goes out of scope.
let world_ptr = CString::from_raw(world);
let output = env.new_string(world_ptr.to_str().unwrap()).expect("Couldn't create java string!");
output.into_inner()
}
#[no_mangle]
pub unsafe extern fn Java_Greetings_welcome(env: JNIEnv, _: JClass, java_pattern: JString) -> jstring {
// Our Java companion code might pass-in "world" as a string, hence the name.
let world = rust_greeting(env.get_string(java_pattern).expect("invalid pattern string").as_ptr());
// Retake pointer so that we can use it below and allow memory to be freed when it goes out of scope.
let world_ptr = CString::from_raw(world);
let output = env.new_string(world_ptr.to_str().unwrap()).expect("Couldn't create java string!");
output.into_inner()
}
#[no_mangle]
pub extern fn rust_greeting(to: *const c_char) -> *mut c_char {
let c_str = unsafe { CStr::from_ptr(to) };
let recipient = match c_str.to_str() {
Err(_) => "there",
Ok(string) => string,
};
CString::new("Hello There - ".to_owned() + recipient).unwrap().into_raw()
}
}
| true
|
ff061b5ee54a02f79f53118e072a58432c5287e4
|
Rust
|
wehrwein1/advent-of-code
|
/2016/day01/day01.rs
|
UTF-8
| 4,093
| 3.3125
| 3
|
[] |
no_license
|
// https://adventofcode.com/2016/day/1
// First time doing something non-trivial in Rust (won't be pretty)
use std::collections::HashSet;
use std::option::Option;
mod geometry; // include geometry.rs
type Point = geometry::Point<i32>;
type Vector = geometry::Vector;
pub fn main() {
println!("part 1: blocks away: {}", blocks_away(include_str!("../input/01_INPUT.txt")).0);
println!("part 2: first location visited twice blocks away: {}", blocks_away(include_str!("../input/01_INPUT.txt")).1);
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum Direction {
North = 0,
East,
South,
West,
}
impl Direction {
const DIRECTIONS: [Direction; 4] = [
Direction::North,
Direction::East,
Direction::South,
Direction::West,
];
fn to_vector(&self) -> Vector {
let origin = Point { x: 0, y : 0};
match *self {
Direction::North => Vector{ start: origin, end: Point{ x: 0, y: 1}}, // up
Direction::South => Vector{ start: origin, end: Point{ x: 0, y: -1}}, // down
Direction::East => Vector{ start: origin, end: Point{ x: 1, y: 0}},
Direction::West => Vector{ start: origin, end: Point{ x: -1, y: 0}},
}
}
fn turn_left(self) -> Direction {
let len = Direction::DIRECTIONS.len();
return Direction::DIRECTIONS[(self as usize + len - 1) % len].clone();
}
fn turn_right(self) -> Direction {
let len = Direction::DIRECTIONS.len();
return Direction::DIRECTIONS[(self as usize + len + 1) % len].clone();
}
}
fn blocks_away(instructions: &str) -> (i32, i32) {
let mut last_ended_at: Point = Point{ x: 0, y: 0 };
let mut facing_direction: Direction = Direction::North;
let mut visited_points: HashSet<Point> = HashSet::new();
let mut first_point_visited_twice: Option<Point> = None;
let instruction = instructions.split(", ");
// println!("Start facing {:?}", facing_direction);
for (i, token) in instruction.enumerate() {
let (turnchar, distancechars) = token.split_at(1);
// println!(" {} {}: facing {:?} pos {}", turnchar, distancechars, facing_direction, pos);
let initial_pos = last_ended_at;
let initial_facing = facing_direction;
// turn
match turnchar {
"L" => facing_direction = facing_direction.turn_left(),
"R" => facing_direction = facing_direction.turn_right(),
_ => {
panic!("{}", format!("unknown Turn: '{}'", turnchar));
}
}
// move / check path points
let distance: i32 = distancechars.parse::<i32>().unwrap();
let walked_path = facing_direction.to_vector().times_scalar(distance).project_from(initial_pos);
let walked_points = &walked_path.to_points();
// println!(" about to walk from {:?} to {:?}: pts -> {:?}", pos, walked_path.end, walked_points);
for walked_point in walked_points {
if first_point_visited_twice.is_none() && (last_ended_at != *walked_point) && visited_points.contains(walked_point) {
println!("!! visited before {:?}", walked_point);
first_point_visited_twice = Some(*walked_point);
}
visited_points.insert(*walked_point);
}
last_ended_at = walked_path.end;
println!("{:03} {} facing {:?} -> {}{} ({})-> {} facing {:?}", i, initial_pos, initial_facing, turnchar, distance, walked_points.len(), last_ended_at, facing_direction);
}
return (manhattan_distance(last_ended_at), manhattan_distance(first_point_visited_twice.unwrap_or_default()));
}
fn manhattan_distance(pos: Point) -> i32 {
return pos.x.abs() + pos.y.abs();
}
#[cfg(test)]
mod day01_tests {
use super::*;
#[test]
fn test_day_part1() {
assert_eq!(1, blocks_away("R1").0);
assert_eq!(5, blocks_away("R2, L3").0);
assert_eq!(2, blocks_away("R2, R2, R2").0);
assert_eq!(12, blocks_away("R5, L5, R5, R3").0);
}
#[test]
fn test_direction() {
assert_eq!(Direction::North.turn_left(), Direction::West);
assert_eq!(Direction::North.turn_right(), Direction::East);
assert_eq!(Direction::West.turn_left(), Direction::South)
}
#[test]
fn test_day_part2() {
assert_eq!(4, blocks_away("R8, R4, R4, R8").1);
}
}
| true
|
79f15ce028afe519c1ef82ba0ddb448dfab03560
|
Rust
|
danleechina/Leetcode
|
/Rust_Sol/src/archive0/s263.rs
|
UTF-8
| 347
| 3.015625
| 3
|
[] |
no_license
|
impl Solution {
pub fn is_ugly(num: i32) -> bool {
if num <= 0 {
return false;
}
let mut cp = num;
while cp % 2 == 0 {
cp /= 2;
}
while cp % 3 == 0 {
cp /= 3;
}
while cp % 5 == 0 {
cp /= 5;
}
return cp == 1;
}
}
| true
|
1050d0064950f8279d9b0ca58671dad199e51177
|
Rust
|
loewenheim/pueue
|
/daemon/network/message_handler/stash.rs
|
UTF-8
| 869
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
use pueue_lib::network::message::*;
use pueue_lib::state::SharedState;
use pueue_lib::task::TaskStatus;
use crate::network::response_helper::*;
/// Invoked when calling `pueue stash`.
/// Stash specific queued tasks.
/// They won't be executed until they're enqueued or explicitely started.
pub fn stash(task_ids: Vec<usize>, state: &SharedState) -> Message {
let (matching, mismatching) = {
let mut state = state.lock().unwrap();
let (matching, mismatching) = state.filter_tasks(
|task| matches!(task.status, TaskStatus::Queued | TaskStatus::Locked),
Some(task_ids),
);
for task_id in &matching {
state.change_status(*task_id, TaskStatus::Stashed { enqueue_at: None });
}
(matching, mismatching)
};
compile_task_response("Tasks are stashed", matching, mismatching)
}
| true
|
6776a0673e386d446eb48fe0fc5ed0e6122b3b9b
|
Rust
|
feenkcom/gtoolkit-boxer
|
/boxer-ffi/array_point_f32.rs
|
UTF-8
| 1,753
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
use boxer::array::BoxerArrayPointF32;
use boxer::point::BoxerPointF32;
use boxer::{ValueBox, ValueBoxPointer};
#[no_mangle]
pub fn boxer_array_point_f32_create() -> *mut ValueBox<BoxerArrayPointF32> {
BoxerArrayPointF32::boxer_array_create()
}
#[no_mangle]
pub fn boxer_array_point_f32_create_with(
element_ptr: *mut ValueBox<BoxerPointF32>,
amount: usize,
) -> *mut ValueBox<BoxerArrayPointF32> {
element_ptr.with_not_null_value_return(std::ptr::null_mut(), |point| {
BoxerArrayPointF32::boxer_array_create_with(point, amount)
})
}
#[no_mangle]
pub fn boxer_array_point_f32_create_from_data(
_data: *mut BoxerPointF32,
amount: usize,
) -> *mut ValueBox<BoxerArrayPointF32> {
BoxerArrayPointF32::boxer_array_create_from_data(_data, amount)
}
#[no_mangle]
pub fn boxer_array_point_f32_drop(ptr: *mut ValueBox<BoxerArrayPointF32>) {
BoxerArrayPointF32::boxer_array_drop(ptr);
}
#[no_mangle]
pub fn boxer_array_point_f32_get_length(ptr: *mut ValueBox<BoxerArrayPointF32>) -> usize {
BoxerArrayPointF32::boxer_array_get_length(ptr)
}
#[no_mangle]
pub fn boxer_array_point_f32_get_capacity(ptr: *mut ValueBox<BoxerArrayPointF32>) -> usize {
BoxerArrayPointF32::boxer_array_get_capacity(ptr)
}
#[no_mangle]
pub fn boxer_array_point_f32_get_data(
ptr: *mut ValueBox<BoxerArrayPointF32>,
) -> *mut BoxerPointF32 {
BoxerArrayPointF32::boxer_array_get_data(ptr)
}
#[cfg(test)]
mod test {
use crate::array_point_f32::boxer_array_point_f32_create_with;
use crate::point_f32::{boxer_point_f32_create, boxer_point_f32_default};
#[test]
fn create_with_point() {
let point = boxer_point_f32_default();
let array = boxer_array_point_f32_create_with(point, 10);
}
}
| true
|
49a6e7757f6cee3f334e88e077881fdf194512b2
|
Rust
|
yaowenqiang/cargo_workspace
|
/network_programming/src/custom-errors.rs
|
UTF-8
| 1,119
| 3.578125
| 4
|
[] |
no_license
|
use std::fmt;
use std::error::Error;
#[derive(Debug)]
enum OperationsError {
DividedByZeroError,
}
impl fmt::Display for OperationsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
OperationsError::DividedByZeroError => f.write_str("Cannot divide by zero"),
}
}
}
impl Error for OperationsError {
fn description(&self) -> &str{
match *self {
OperationsError::DividedByZeroError => "Cannot divide by zero",
}
}
}
//fn divide(dividend: u32, divisor: u32) -> Result<u32, OperationsError> {
fn divide(dividend: u32, divisor: u32) -> Option<u32> {
if divisor == 0u32 {
//Err(OperationsError::DividedByZeroError)
None
} else {
//Ok(dividend / divisor)
Some(dividend / divisor)
}
}
fn main () {
let result1 = divide(100, 0);
match result1 {
None => println!("Error occurred"),
Some(result) => println!("The result is {}", result),
}
println!("{:?}", result1);
let result2 = divide(100, 2);
println!("{:?}", result2.unwrap());
}
| true
|
c306f7fff4f2b002e473a9889ab7575c16af56c3
|
Rust
|
FortechRomania/ternary-tree-minimization
|
/src/main.rs
|
UTF-8
| 892
| 2.625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
extern crate linked_hash_map;
mod literal_value;
mod product_term;
mod ternary_node;
mod ternary_tree_minimization;
use std::collections::HashSet;
fn main() {
let mut term = product_term::ProductTerm::new();
term.add_literal(String::from("A"), literal_value::LiteralValue::False);
term.add_literal(String::from("B"), literal_value::LiteralValue::True);
let mut other = product_term::ProductTerm::new();
other.add_literal(String::from("A"), literal_value::LiteralValue::True);
other.add_literal(String::from("B"), literal_value::LiteralValue::True);
let mut set = HashSet::new();
set.insert(term);
set.insert(other);
let mut vec = vec!["A".to_string(), "B".to_string()];
if let Ok(result_set) = ternary_tree_minimization::TernaryTreeMinimization::apply(&set, &mut vec)
{
for term in result_set {
println!("{}", term.to_boolean_expression());
}
}
}
| true
|
fa5f7d9fee50508f574e0e7d2ccc57b215971ad7
|
Rust
|
nulldevelopmenthr/rust-eventsourcing-demo
|
/code/poc/ver1/src/open_bank_account.rs
|
UTF-8
| 1,489
| 2.859375
| 3
|
[] |
no_license
|
use super::prelude::*;
use std::sync::Arc;
pub struct OpenBankAccountHandler<T>
where
T: BankAccountRepository,
{
pub repository: Arc<T>,
}
impl<T: BankAccountRepository> OpenBankAccountHandler<T> {
pub fn handle(&self, command: OpenBankAccountPayload) -> Result<(), BankAccountError> {
let result: Result<Vec<BankAccountEvent>, BankAccountError> =
BankAccountAggregate::open_acc(command);
let events = result?;
let repo = Arc::clone(&self.repository);
let result = repo.save_events(events)?;
Ok(result)
}
}
#[test]
fn open_bank_account_handler() {
let repo = std::sync::Arc::new(TestBankAccountRepository {});
let handler = OpenBankAccountHandler { repository: repo };
let result = handler.handle(OpenBankAccountPayload {
id: 100,
customer_id: 20,
});
assert_eq!(Ok(()), result);
}
impl OpenBankAccountHandler<TestBankAccountRepository> {}
pub struct TestBankAccountRepository {}
impl BankAccountRepository for TestBankAccountRepository {
fn save_events(&self, events: Vec<BankAccountEvent>) -> Result<(), BankAccountRepositoryError> {
let expected = vec![BankAccountEvent::acc_opened(100, 20)];
match events == expected {
true => Ok(()),
false => Err(BankAccountRepositoryError::Unexpected),
}
}
fn get_events(&self) -> Result<Vec<BankAccountEvent>, BankAccountRepositoryError> {
Ok(Vec::new())
}
}
| true
|
3b1a75a596844a98e259066bacd421ec63b2b565
|
Rust
|
Aaron1011/oauth1-request-rs
|
/oauth1-request/src/util.rs
|
UTF-8
| 8,952
| 2.84375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::fmt::{self, Display, Formatter, Write};
use std::str;
use percent_encoding::AsciiSet;
macro_rules! options {
($(
$(#[$attr:meta])*
pub struct $O:ident<$lifetime:tt> {
$(#[$ctor_attr:meta])* $ctor:ident;
$($field:tt)*
}
)*) => {$(
$(#[$attr])*
pub struct $O<$lifetime> {
$($field)*
}
impl<$lifetime> $O<$lifetime> {
$(#[$ctor_attr])*
pub fn $ctor() -> Self {
Default::default()
}
impl_setters! { $($field)* }
}
)*};
}
macro_rules! impl_setters {
($(#[$attr:meta])* $setter:ident: Option<NonZeroU64>, $($rest:tt)*) => {
$(#[$attr])*
pub fn $setter(&mut self, $setter: impl Into<Option<u64>>) -> &mut Self {
self.$setter = $setter.into().and_then(NonZeroU64::new);
self
}
impl_setters! { $($rest)* }
};
($(#[$attr:meta])* $setter:ident: Option<$t:ty>, $($rest:tt)*) => {
$(#[$attr])*
pub fn $setter(&mut self, $setter: impl Into<Option<$t>>) -> &mut Self {
self.$setter = $setter.into();
self
}
impl_setters! { $($rest)* }
};
($(#[$attr:meta])* $setter:ident: bool, $($rest:tt)*) => {
$(#[$attr])*
pub fn $setter(&mut self, $setter: bool) -> &mut Self {
self.$setter = $setter;
self
}
impl_setters! { $($rest)* }
};
($(#[$attr:meta])* $setter:ident: $t:ty, $($rest:tt)*) => {
$(#[$attr])*
pub fn $setter(&mut self, $setter: impl Into<Option<$t>>) -> &mut Self {
self.$setter = $setter;
self
}
impl_setters! { $($rest)* }
};
() => {};
}
pub struct DoublePercentEncode<D>(pub D);
// TODO: Use `!` type once it's stable and we've bumped minimum supported Rust version.
#[allow(clippy::empty_enum)]
#[derive(Clone, Debug)]
pub enum Never {}
pub struct PercentEncode<D>(pub D);
/// A map from ASCII character byte to a bool representing if the character
/// should be percent encoded.
///
/// Every character that is not an "unreserved character" in RFC 3986 should be encoded.
/// https://tools.ietf.org/html/rfc3986#section-2.3
#[rustfmt::skip]
const ENCODE_MAP: [bool; 0x100] = [
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, false, false, true,
false, false, false, false, false, false, false, false,
false, false, true, true, true, true, true, true,
true, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false,
false, false, false, true, true, true, true, false,
true, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false,
false, false, false, true, true, true, false, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
];
const RESERVED: &AsciiSet = &percent_encoding::NON_ALPHANUMERIC
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
impl<D: Display> Display for DoublePercentEncode<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
struct Adapter<'a, 'b>(&'a mut Formatter<'b>);
impl<'a, 'b: 'a> Write for Adapter<'a, 'b> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let mut bytes = s.as_bytes();
while let Some((&b, rem)) = bytes.split_first() {
if ENCODE_MAP[b as usize] {
self.0.write_str(double_encode_byte(b))?;
bytes = rem;
continue;
}
// Write as much characters as possible at once:
if let Some((i, &b)) = bytes
.iter()
.enumerate()
.skip(1)
.find(|&(_, &b)| ENCODE_MAP[b as usize])
{
let rem = &bytes[i + 1..];
let s = &bytes[..i];
debug_assert!(s.is_ascii());
self.0.write_str(unsafe { str::from_utf8_unchecked(s) })?;
self.0.write_str(double_encode_byte(b))?;
bytes = rem;
} else {
debug_assert!(bytes.is_ascii());
return self.0.write_str(unsafe { str::from_utf8_unchecked(bytes) });
}
}
Ok(())
}
}
write!(Adapter(f), "{}", self.0)
}
}
impl<D: Display> Display for PercentEncode<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
struct Adapter<'a, 'b>(&'a mut Formatter<'b>);
impl<'a, 'b: 'a> Write for Adapter<'a, 'b> {
fn write_str(&mut self, s: &str) -> fmt::Result {
Display::fmt(&percent_encode(s), self.0)
}
}
write!(Adapter(f), "{}", self.0)
}
}
fn double_encode_byte(b: u8) -> &'static str {
const ENCODE: &[u8; 0x100 * 5] = b"\
%2500%2501%2502%2503%2504%2505%2506%2507%2508%2509%250A%250B%250C%250D%250E%250F\
%2510%2511%2512%2513%2514%2515%2516%2517%2518%2519%251A%251B%251C%251D%251E%251F\
%2520%2521%2522%2523%2524%2525%2526%2527%2528%2529%252A%252B%252C%252D%252E%252F\
%2530%2531%2532%2533%2534%2535%2536%2537%2538%2539%253A%253B%253C%253D%253E%253F\
%2540%2541%2542%2543%2544%2545%2546%2547%2548%2549%254A%254B%254C%254D%254E%254F\
%2550%2551%2552%2553%2554%2555%2556%2557%2558%2559%255A%255B%255C%255D%255E%255F\
%2560%2561%2562%2563%2564%2565%2566%2567%2568%2569%256A%256B%256C%256D%256E%256F\
%2570%2571%2572%2573%2574%2575%2576%2577%2578%2579%257A%257B%257C%257D%257E%257F\
%2580%2581%2582%2583%2584%2585%2586%2587%2588%2589%258A%258B%258C%258D%258E%258F\
%2590%2591%2592%2593%2594%2595%2596%2597%2598%2599%259A%259B%259C%259D%259E%259F\
%25A0%25A1%25A2%25A3%25A4%25A5%25A6%25A7%25A8%25A9%25AA%25AB%25AC%25AD%25AE%25AF\
%25B0%25B1%25B2%25B3%25B4%25B5%25B6%25B7%25B8%25B9%25BA%25BB%25BC%25BD%25BE%25BF\
%25C0%25C1%25C2%25C3%25C4%25C5%25C6%25C7%25C8%25C9%25CA%25CB%25CC%25CD%25CE%25CF\
%25D0%25D1%25D2%25D3%25D4%25D5%25D6%25D7%25D8%25D9%25DA%25DB%25DC%25DD%25DE%25DF\
%25E0%25E1%25E2%25E3%25E4%25E5%25E6%25E7%25E8%25E9%25EA%25EB%25EC%25ED%25EE%25EF\
%25F0%25F1%25F2%25F3%25F4%25F5%25F6%25F7%25F8%25F9%25FA%25FB%25FC%25FD%25FE%25FF\
";
let b = usize::from(b);
unsafe { str::from_utf8_unchecked(&ENCODE[b * 5..(b + 1) * 5]) }
}
pub fn percent_encode(input: &str) -> percent_encoding::PercentEncode<'_> {
percent_encoding::utf8_percent_encode(input, RESERVED)
}
#[cfg(test)]
mod tests {
use super::*;
use percent_encoding::percent_encode_byte;
#[test]
fn double_percent_encode() {
for b in 0u8..=0xFF {
assert_eq!(
double_encode_byte(b),
&percent_encode(percent_encode_byte(b)).to_string(),
);
}
}
#[test]
fn encode_set() {
for b in 0u8..=0xFF {
let expected = match b {
// Unreserved characters
b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'-' | b'.' | b'_' | b'~' => false,
_ => true,
};
assert_eq!(
ENCODE_MAP[b as usize],
expected,
"byte = {} ({:?})",
b,
char::from(b),
);
}
}
}
| true
|
38f5da435cee0a1f3937ae5def57dd3c99fd3fb9
|
Rust
|
aemreaydin/rust-chip8
|
/src/chip8/cpu.rs
|
UTF-8
| 22,201
| 2.96875
| 3
|
[] |
no_license
|
use std::time::Duration;
use super::display;
use rand::Rng;
const FONTS: [u8; 80] = [
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80, // F
];
trait FontMemStart {
const FONT_MEM_START: usize = 0x050;
}
#[derive(Debug)]
pub struct CPU {
pub memory: [u8; 4096],
pub v_reg: [u8; 16],
pub i_reg: u16,
pub delay_reg: u8,
pub sound_reg: u8,
pub prog_counter: u16,
pub stack_ptr: u8,
pub stack: [u16; 16],
pub opcodes: Vec<u16>,
pub display: display::Display,
}
impl FontMemStart for CPU {}
impl CPU {
pub fn new(rom_buf: &[u8]) -> Self {
let opcodes = CPU::convert_rom_to_opcodes(rom_buf);
let mut cpu = CPU {
memory: [0; 4096],
v_reg: [0; 16],
i_reg: 0,
delay_reg: 0,
sound_reg: 0,
prog_counter: 0x200,
stack_ptr: 0,
stack: [0; 16],
opcodes, // Is used for debugging purposes
display: display::Display::new(640, 320),
};
// Initialize fonts in the interpreter btw. 0x000-0x1FF
// Fonts will be stored between 0x050-0x09F
cpu.init_fonts();
// Load the rom into memory starting from 0x200
// PC will point to 0x200 initially
cpu.load_rom_into_memory(rom_buf);
cpu
}
fn init_fonts(&mut self) {
for (ind, font) in FONTS.iter().enumerate() {
self.memory[CPU::FONT_MEM_START + ind] = *font;
}
}
fn load_rom_into_memory(&mut self, rom_buf: &[u8]) {
for (ind, byte) in rom_buf.iter().enumerate() {
self.memory[(self.prog_counter as usize) + ind] = *byte;
}
}
fn convert_rom_to_opcodes(rom_buf: &[u8]) -> Vec<u16> {
let mut opcodes: Vec<u16> = Vec::new();
for index in 0..(rom_buf.len() / 2) {
let val0 = rom_buf[2 * index];
let val1 = rom_buf[2 * index + 1];
let opcode = ((val0 as u16) << 8) | val1 as u16;
opcodes.push(opcode);
}
opcodes
}
fn fetch_current_instruction(&mut self) -> u16 {
((self.memory[self.prog_counter as usize] as u16) << 8)
| (self.memory[(self.prog_counter + 1) as usize] as u16)
}
pub fn run(&mut self) {
'running: loop {
let opcode = self.fetch_current_instruction();
println!("{:04X}", opcode);
self.run_instruction(opcode);
let should_break = self.display.update();
if should_break {
break 'running;
}
if self.delay_reg > 0 {
self.delay_reg -= 1;
}
if self.sound_reg > 0 {
if self.sound_reg == 1 {
println!("BEEP");
}
self.sound_reg -= 1;
}
::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60));
}
}
pub fn run_instruction(&mut self, opcode: u16) {
let (op0, op1, op2, op3): (u8, u8, u8, u8) = (
((opcode & 0xF000) >> 12) as u8,
((opcode & 0x0F00) >> 8) as u8,
((opcode & 0x00F0) >> 4) as u8,
(opcode & 0x000F) as u8,
);
let nnn = ((op1 as u16) << 8) | ((op2 as u16) << 4) | (op3 as u16);
let nn: u8 = ((op2 as u8) << 4) | (op3 as u8);
let n = op3;
let vx = op1;
let vy = op2;
match (op0, op1, op2, op3) {
(0x0, 0x0, 0xE, 0x0) => self.clear_display(),
(0x0, 0x0, 0xE, 0xE) => self.return_from_subroutine(),
(0x1, _, _, _) => self.jump_to_address(nnn),
(0x2, _, _, _) => self.call_subroutine_at_address(nnn),
(0x3, _, _, _) => self.skip_if_vx_eq_nn(vx, nn),
(0x4, _, _, _) => self.skip_if_vx_neq_nn(vx, nn),
(0x5, _, _, _) => self.skip_if_vx_eq_vy(vx, vy),
(0x6, _, _, _) => self.set_vx_to_nn(vx, nn),
(0x7, _, _, _) => self.add_vx_nn(vx, nn),
(0x8, _, _, 0x0) => self.set_vx_to_vy(vx, vy),
(0x8, _, _, 0x1) => self.set_vx_to_vx_or_vy(vx, vy),
(0x8, _, _, 0x2) => self.set_vx_to_vx_and_vy(vx, vy),
(0x8, _, _, 0x3) => self.set_vx_to_vx_xor_vy(vx, vy),
(0x8, _, _, 0x4) => self.add_vx_vy(vx, vy),
(0x8, _, _, 0x5) => self.sub_vx_vy(vx, vy),
(0x8, _, _, 0x6) => self.shift_vx_right(vx),
(0x8, _, _, 0x7) => self.sub_vy_vx(vx, vy),
(0x8, _, _, 0xE) => self.shift_vx_left(vx),
(0x9, _, _, _) => self.skip_if_vx_neq_vy(vx, vy),
(0xA, _, _, _) => self.set_ind_reg_to_address(nnn),
(0xB, _, _, _) => self.jump_to_v0_plus_address(nnn),
(0xC, _, _, _) => self.set_vx_to_rnd_and_nn(vx, nn),
(0xD, _, _, _) => self.display_sprite(vx, vy, n),
(0xE, _, 0x9, 0xE) => self.skip_if_key_eq_vx_pressed(vx),
(0xE, _, 0xA, 0x1) => self.skip_if_key_eq_vx_not_pressed(vx),
(0xF, _, 0x0, 0x7) => self.set_vx_to_delay_timer(vx),
(0xF, _, 0x0, 0xA) => self.set_vx_to_key_press(vx),
(0xF, _, 0x1, 0x5) => self.set_delay_timer_to_vx(vx),
(0xF, _, 0x1, 0x8) => self.set_sound_timer_to_vx(vx),
(0xF, _, 0x1, 0xE) => self.add_ind_reg_vx(vx),
(0xF, _, 0x2, 0x9) => self.set_ind_reg_to_loc_of_sprite_for_digit_vx(vx),
(0xF, _, 0x3, 0x3) => self.store_bcd_vx_in_ind_reg(vx),
(0xF, _, 0x5, 0x5) => self.store_v_reg_in_memory_from_ind_reg(vx),
(0xF, _, 0x6, 0x5) => self.read_v_reg_from_ind_reg(vx),
_ => println!("NEXT_INST"),
}
}
// 00E0
fn clear_display(&mut self) {
self.display.clear();
self.prog_counter += 2;
}
// 00EE
fn return_from_subroutine(&mut self) {
self.stack_ptr -= 1;
self.prog_counter = self.stack[(self.stack_ptr as usize)];
self.prog_counter += 2;
self.stack[self.stack_ptr as usize] = 0;
}
// 1NNN
fn jump_to_address(&mut self, address: u16) {
self.prog_counter = address;
}
// 2NNN
fn call_subroutine_at_address(&mut self, address: u16) {
// Store the program counter in the stack
self.stack[(self.stack_ptr as usize)] = self.prog_counter;
self.stack_ptr += 1;
self.prog_counter = address;
}
// 3XNN
fn skip_if_vx_eq_nn(&mut self, vx: u8, nn: u8) {
if self.v_reg[(vx as usize)] == nn {
self.prog_counter += 2;
}
self.prog_counter += 2;
}
// 4XNN
fn skip_if_vx_neq_nn(&mut self, vx: u8, nn: u8) {
if self.v_reg[vx as usize] != nn {
self.prog_counter += 2;
}
self.prog_counter += 2;
}
// 5XY0
fn skip_if_vx_eq_vy(&mut self, vx: u8, vy: u8) {
if self.v_reg[vx as usize] == self.v_reg[vy as usize] {
self.prog_counter += 2;
}
self.prog_counter += 2;
}
// 6XNN
fn set_vx_to_nn(&mut self, vx: u8, nn: u8) {
self.v_reg[vx as usize] = nn;
self.prog_counter += 2;
}
// 7XNN
fn add_vx_nn(&mut self, vx: u8, nn: u8) {
self.v_reg[vx as usize] = self.v_reg[vx as usize].wrapping_add(nn);
self.prog_counter += 2;
}
// 8XY0
fn set_vx_to_vy(&mut self, vx: u8, vy: u8) {
self.v_reg[vx as usize] = self.v_reg[vy as usize];
self.prog_counter += 2;
}
// 8XY1
fn set_vx_to_vx_or_vy(&mut self, vx: u8, vy: u8) {
self.v_reg[vx as usize] |= self.v_reg[vy as usize];
self.prog_counter += 2;
}
// 8XY2
fn set_vx_to_vx_and_vy(&mut self, vx: u8, vy: u8) {
self.v_reg[vx as usize] &= self.v_reg[vy as usize];
self.prog_counter += 2;
}
// 8XY3
fn set_vx_to_vx_xor_vy(&mut self, vx: u8, vy: u8) {
self.v_reg[vx as usize] ^= self.v_reg[vy as usize];
self.prog_counter += 2;
}
// 8XY4
fn add_vx_vy(&mut self, vx: u8, vy: u8) {
let val_x = self.v_reg[vx as usize];
let val_y = self.v_reg[vy as usize];
let (sum, did_overflow) = val_x.overflowing_add(val_y);
self.v_reg[vx as usize] = sum;
self.v_reg[0xF] = if did_overflow { 1 } else { 0 };
self.prog_counter += 2;
}
// 8XY5
fn sub_vx_vy(&mut self, vx: u8, vy: u8) {
let val_x = self.v_reg[vx as usize];
let val_y = self.v_reg[vy as usize];
self.v_reg[0xF] = if val_x > val_y { 1 } else { 0 };
self.v_reg[vx as usize] = val_x.wrapping_sub(val_y);
self.prog_counter += 2;
}
// 8XY6
fn shift_vx_right(&mut self, vx: u8) {
let val_x = self.v_reg[vx as usize];
self.v_reg[0xF] = val_x & 1;
self.v_reg[vx as usize] >>= 1;
self.prog_counter += 2;
}
// 8XY7
fn sub_vy_vx(&mut self, vx: u8, vy: u8) {
let val_x = self.v_reg[vx as usize];
let val_y = self.v_reg[vy as usize];
self.v_reg[0xF] = if val_y > val_x { 1 } else { 0 };
self.v_reg[vx as usize] = val_y.wrapping_sub(val_x);
self.prog_counter += 2;
}
// 8XYE
fn shift_vx_left(&mut self, vx: u8) {
self.v_reg[0xF] = (self.v_reg[vx as usize] & 0b10000000) >> 7;
self.v_reg[vx as usize] <<= 1;
self.prog_counter += 2;
}
// 9XY0
fn skip_if_vx_neq_vy(&mut self, vx: u8, vy: u8) {
if self.v_reg[vx as usize] != self.v_reg[vy as usize] {
self.prog_counter += 2;
}
self.prog_counter += 2;
}
// ANNN
fn set_ind_reg_to_address(&mut self, address: u16) {
self.i_reg = address;
self.prog_counter += 2;
}
// BNNN
fn jump_to_v0_plus_address(&mut self, address: u16) {
self.prog_counter = (self.v_reg[0] as u16) + address;
}
// CXNN
fn set_vx_to_rnd_and_nn(&mut self, vx: u8, nn: u8) {
let mut rng = rand::thread_rng();
let rnd: u8 = rng.gen();
self.v_reg[vx as usize] = rnd & nn;
self.prog_counter += 2;
}
// DXYN
fn display_sprite(&mut self, vx: u8, vy: u8, n: u8) {
let x_coords = self.v_reg[vx as usize];
let y_coords = self.v_reg[vy as usize];
self.v_reg[0xF] = 0;
for row in 0..n {
if (self.i_reg + row as u16) >= 4096 {
continue;
}
let sprite = self.memory[(self.i_reg as usize) + row as usize];
let y_coord = (y_coords + row) as u32 % display::BASE_HEIGHT;
for bit in 0..8u8 {
let x_coord = (x_coords + bit) as u32 % display::BASE_WIDTH;
let pixel = self.display.get_pixel(x_coord, y_coord);
let sprite_bit = sprite >> (7 - bit) & 1;
self.v_reg[0x0F] = pixel & sprite_bit;
self.display.set_pixel(x_coord, y_coord, pixel ^ sprite_bit);
}
}
self.display.draw(false);
self.prog_counter += 2;
}
// EX9E
fn skip_if_key_eq_vx_pressed(&mut self, _vx: u8) {
self.prog_counter += 2;
}
// EXA1
fn skip_if_key_eq_vx_not_pressed(&mut self, _vx: u8) {
self.prog_counter += 2;
}
// FX07
fn set_vx_to_delay_timer(&mut self, vx: u8) {
self.v_reg[vx as usize] = self.delay_reg;
self.prog_counter += 2;
}
// FX0A
fn set_vx_to_key_press(&mut self, _vx: u8) {
self.prog_counter += 2;
}
// FX15
fn set_delay_timer_to_vx(&mut self, vx: u8) {
self.delay_reg = self.v_reg[vx as usize];
self.prog_counter += 2;
}
// FX18
fn set_sound_timer_to_vx(&mut self, vx: u8) {
self.sound_reg = self.v_reg[vx as usize];
self.prog_counter += 2;
}
// FX1E
fn add_ind_reg_vx(&mut self, vx: u8) {
self.i_reg += self.v_reg[vx as usize] as u16;
self.v_reg[0xF] = if self.i_reg > 0x0F00 { 1 } else { 0 };
self.prog_counter += 2;
}
// FX29
fn set_ind_reg_to_loc_of_sprite_for_digit_vx(&mut self, vx: u8) {
let x = self.v_reg[vx as usize];
self.i_reg = (x as u16) * 5;
self.prog_counter += 2;
}
// FX33
fn store_bcd_vx_in_ind_reg(&mut self, vx: u8) {
let ones = self.v_reg[vx as usize] % 10;
let tens = (self.v_reg[vx as usize] / 10) % 10;
let hundreds = (self.v_reg[vx as usize] % 100) % 10;
self.memory[(self.i_reg) as usize] = hundreds;
self.memory[(self.i_reg + 1) as usize] = tens;
self.memory[(self.i_reg + 2) as usize] = ones;
self.prog_counter += 2;
}
// FX55
fn store_v_reg_in_memory_from_ind_reg(&mut self, vx: u8) {
for ind in 0..=(vx as usize) {
self.memory[(self.i_reg as usize) + ind] = self.v_reg[ind];
}
self.prog_counter += 2;
}
// FX65
fn read_v_reg_from_ind_reg(&mut self, vx: u8) {
for ind in 0..=(vx as usize) {
self.v_reg[ind] = self.memory[(self.i_reg as usize) + ind];
}
self.prog_counter += 2;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::prelude::*;
// This is probably not the right way to do this, oh well...
fn read_test_opcode() -> Vec<u8> {
let mut file = File::open("roms/ibm_logo.ch8").unwrap();
let mut rom_buf = Vec::new();
file.read_to_end(&mut rom_buf).unwrap();
rom_buf
}
#[test]
fn converts_opcode() {
let test_opcode = read_test_opcode();
let cpu = CPU::new(&test_opcode);
// Just test the first few to make sure they're correct
assert_eq!(
cpu.opcodes[0..=5],
vec![0x00E0, 0xA22A, 0x600C, 0x6108, 0xD01F, 0x7009,]
);
// And test the last two to make sure it works
assert_eq!(cpu.opcodes[(cpu.opcodes.len() - 2)..], vec![0x00E0, 0x00E0]);
}
#[test]
fn jumps_to_address() {
let mut cpu = CPU::new(&[]);
let addr = 0x300;
cpu.jump_to_address(addr);
assert_eq!(cpu.prog_counter, addr);
}
#[test]
fn calls_and_returns_from_subroutine() {
let mut cpu = CPU::new(&[]);
let addr = 0x300;
cpu.call_subroutine_at_address(addr);
assert_eq!(cpu.prog_counter, addr);
cpu.return_from_subroutine();
assert_eq!(cpu.prog_counter, 0x200);
}
#[test]
fn skips_if_vx_eq_nn() {
let mut cpu = CPU::new(&[]);
let val = 0xCC;
cpu.v_reg[0] = val;
// Skip
cpu.skip_if_vx_eq_nn(0, val);
assert_eq!(cpu.prog_counter, 0x0204);
}
#[test]
fn skips_if_vx_neq_nn() {
let mut cpu = CPU::new(&[]);
let val = 0xCC;
cpu.v_reg[0] = val;
// Skip
cpu.skip_if_vx_neq_nn(0, 0xCD);
assert_eq!(cpu.prog_counter, 0x204);
}
#[test]
fn skips_if_vx_eq_vy() {
let mut cpu = CPU::new(&[]);
let val = 0xCC;
let vx: u8 = 0;
let vy: u8 = 1;
cpu.v_reg[(vx as usize)] = val;
cpu.v_reg[(vy as usize)] = val;
cpu.skip_if_vx_eq_vy(vx, vy);
assert_eq!(cpu.prog_counter, 0x204);
}
#[test]
fn sets_vx_to_nn() {
let mut cpu = CPU::new(&[]);
let val = 0xFF;
cpu.set_vx_to_nn(0, val);
assert_eq!(cpu.v_reg[0], val);
}
#[test]
fn adds_vx_nn() {
let mut cpu = CPU::new(&[]);
let val = 0x01;
cpu.v_reg[0] = 0x02;
cpu.add_vx_nn(0, val);
assert_eq!(cpu.v_reg[0], 0x03);
}
#[test]
fn sets_vx_to_vy() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x02;
cpu.v_reg[1] = 0x03;
cpu.set_vx_to_vy(0, 1);
assert_eq!(cpu.v_reg[0], cpu.v_reg[1]);
}
#[test]
fn sets_vx_to_vx_or_vy() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x02;
cpu.v_reg[1] = 0x03;
cpu.set_vx_to_vx_or_vy(0, 1);
assert_eq!(cpu.v_reg[0], 0x02 | 0x03);
}
#[test]
fn sets_vx_to_vx_and_vy() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x02;
cpu.v_reg[1] = 0x03;
cpu.set_vx_to_vx_and_vy(0, 1);
assert_eq!(cpu.v_reg[0], 0x02 & 0x03);
}
#[test]
fn sets_vx_to_vx_xor_vy() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x02;
cpu.v_reg[1] = 0x03;
cpu.set_vx_to_vx_xor_vy(0, 1);
assert_eq!(cpu.v_reg[0], 0x02 ^ 0x03);
}
#[test]
fn adds_vx_vy() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x02;
cpu.v_reg[1] = 0x03;
cpu.add_vx_vy(0, 1);
assert_eq!(cpu.v_reg[0], 0x05);
assert_eq!(cpu.v_reg[0xF], 0);
cpu.v_reg[0] = 0xFF;
cpu.v_reg[1] = 0x01;
cpu.add_vx_vy(0, 1);
assert_eq!(cpu.v_reg[0], 0);
assert_eq!(cpu.v_reg[0xF], 1);
}
#[test]
fn subs_vx_vy() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x03;
cpu.v_reg[1] = 0x02;
cpu.sub_vx_vy(0, 1);
assert_eq!(cpu.v_reg[0], 0x01);
assert_eq!(cpu.v_reg[0xF], 1);
cpu.v_reg[0] = 0x00;
cpu.v_reg[1] = 0x01;
cpu.sub_vx_vy(0, 1);
assert_eq!(cpu.v_reg[0], 0xFF);
assert_eq!(cpu.v_reg[0xF], 0);
}
#[test]
fn shifts_vx_right() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x03;
cpu.shift_vx_right(0);
assert_eq!(cpu.v_reg[0], 1);
assert_eq!(cpu.v_reg[0xF], 1);
}
#[test]
fn subs_vy_vx() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x02;
cpu.v_reg[1] = 0x04;
cpu.sub_vy_vx(0, 1);
assert_eq!(cpu.v_reg[0], 0x02);
assert_eq!(cpu.v_reg[0xF], 1);
cpu.v_reg[0] = 0x01;
cpu.v_reg[1] = 0x00;
cpu.sub_vy_vx(0, 1);
assert_eq!(cpu.v_reg[0], 0xFF);
assert_eq!(cpu.v_reg[0xF], 0);
}
#[test]
fn shifts_vx_left() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x0F;
cpu.shift_vx_left(0);
assert_eq!(cpu.v_reg[0], 0x1E);
assert_eq!(cpu.v_reg[0xF], 0);
cpu.v_reg[0] = 0xFF;
cpu.shift_vx_left(0);
assert_eq!(cpu.v_reg[0xF], 1);
}
#[test]
fn skips_if_vx_neq_vy() {
let mut cpu = CPU::new(&[]);
let val = 0xCC;
cpu.v_reg[0] = val;
cpu.v_reg[1] = val + 1;
cpu.skip_if_vx_neq_vy(0, 1);
assert_eq!(cpu.prog_counter, 0x204);
}
#[test]
fn sets_ind_reg_to_address() {
let mut cpu = CPU::new(&[]);
let address = 0x0ABC;
cpu.set_ind_reg_to_address(address);
assert_eq!(cpu.i_reg, address);
}
#[test]
fn jumps_to_v0_plus_address() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0xFF;
let address = 0xABC;
cpu.jump_to_v0_plus_address(address);
assert_eq!(cpu.prog_counter, 0xFF + address);
}
#[test]
fn sets_vx_to_rnd_and_nn() {
let mut cpu = CPU::new(&[]);
cpu.set_vx_to_rnd_and_nn(0, 0x0F);
assert_eq!(cpu.v_reg[0] & 0xF0, 0);
}
#[test]
#[ignore = "not yet implemented"]
fn displays_sprite() {
todo!();
}
#[test]
#[ignore = "not yet implemented"]
fn skips_if_key_eq_vx_pressed() {
todo!();
}
#[test]
#[ignore = "not yet implemented"]
fn skips_if_key_eq_vx_not_pressed() {
todo!();
}
#[test]
fn sets_vx_to_delay_timer() {
let mut cpu = CPU::new(&[]);
cpu.delay_reg = 0x03;
cpu.set_vx_to_delay_timer(0);
assert_eq!(cpu.v_reg[0], cpu.delay_reg);
}
#[test]
#[ignore = "not yet implemented"]
fn sets_vx_to_key_press() {
todo!();
}
#[test]
fn sets_delay_timer_to_vx() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x03;
cpu.set_delay_timer_to_vx(0);
assert_eq!(cpu.v_reg[0], cpu.delay_reg);
}
#[test]
fn sets_sound_timer_to_vx() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 0x03;
cpu.set_sound_timer_to_vx(0);
assert_eq!(cpu.v_reg[0], cpu.sound_reg);
}
#[test]
fn adds_ind_reg_vx() {
let mut cpu = CPU::new(&[]);
cpu.i_reg = 0x02;
cpu.v_reg[0] = 0x03;
cpu.add_ind_reg_vx(0);
assert_eq!(cpu.i_reg, 0x05);
}
#[test]
#[ignore = "not yet implemented"]
fn sets_ind_reg_to_loc_of_sprite_for_digit_vx() {
todo!();
}
#[test]
fn stores_bcd_vx_in_ind_reg() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 143;
cpu.store_bcd_vx_in_ind_reg(0);
assert_eq!(cpu.memory[cpu.i_reg as usize], 1);
assert_eq!(cpu.memory[(cpu.i_reg + 1) as usize], 4);
assert_eq!(cpu.memory[(cpu.i_reg + 2) as usize], 3);
}
#[test]
fn stores_v_reg_in_memory_from_ind_reg() {
let mut cpu = CPU::new(&[]);
cpu.v_reg[0] = 143;
cpu.v_reg[1] = 255;
cpu.v_reg[2] = 12;
cpu.store_v_reg_in_memory_from_ind_reg(2);
assert_eq!(cpu.memory[cpu.i_reg as usize], 143);
assert_eq!(cpu.memory[(cpu.i_reg + 1) as usize], 255);
assert_eq!(cpu.memory[(cpu.i_reg + 2) as usize], 12);
}
#[test]
fn reads_v_reg_from_ind_reg() {
let mut cpu = CPU::new(&[]);
cpu.memory[cpu.i_reg as usize] = 143;
cpu.memory[(cpu.i_reg + 1) as usize] = 255;
cpu.memory[(cpu.i_reg + 2) as usize] = 3;
cpu.read_v_reg_from_ind_reg(2);
assert_eq!(cpu.v_reg[0], 143);
assert_eq!(cpu.v_reg[1], 255);
assert_eq!(cpu.v_reg[2], 3);
}
}
| true
|
e3150ce481cac3f5fab53b3ebab0b80d62000671
|
Rust
|
standardgalactic/toornament-rs
|
/src/opponents.rs
|
UTF-8
| 1,242
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
use crate::common::MatchResultSimple;
use crate::participants::Participant;
/// An opponent involved in a match.
#[derive(
Clone, Default, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
)]
pub struct Opponent {
/// Number of the opponent
pub number: i64,
/// The participant represented in this opponent.
#[serde(skip_serializing_if = "Option::is_none")]
pub participant: Option<Participant>,
/// The result of the opponent. This property is only available on "duel" match format.
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<MatchResultSimple>,
/// Rank of the opponent, compared to other opponents' ranks.
/// This property is only available on matches of type "ffa".
#[serde(skip_serializing_if = "Option::is_none")]
pub rank: Option<i64>,
/// The score of this game.
#[serde(skip_serializing_if = "Option::is_none")]
pub score: Option<i64>,
/// Whether the opponent has forfeited or not.
pub forfeit: bool,
}
/// List of the opponents involved in this match.
#[derive(
Clone, Default, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
)]
pub struct Opponents(pub Vec<Opponent>);
| true
|
bebeba38c99d4c1a9451d56d52c9b13635389488
|
Rust
|
rabisg0/rust-clippy
|
/clippy_lints/src/mem_discriminant.rs
|
UTF-8
| 3,255
| 2.84375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use crate::utils::{match_def_path, paths, snippet, span_lint_and_then, walk_ptrs_ty_depth};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::{BorrowKind, Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use std::iter;
declare_clippy_lint! {
/// **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.
///
/// **Why is this bad?** The value of `mem::discriminant()` on non-enum types
/// is unspecified.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// use std::mem;
///
/// mem::discriminant(&"hello");
/// mem::discriminant(&&Some(2));
/// ```
pub MEM_DISCRIMINANT_NON_ENUM,
correctness,
"calling `mem::descriminant` on non-enum type"
}
declare_lint_pass!(MemDiscriminant => [MEM_DISCRIMINANT_NON_ENUM]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemDiscriminant {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
if let ExprKind::Call(ref func, ref func_args) = expr.kind;
// is `mem::discriminant`
if let ExprKind::Path(ref func_qpath) = func.kind;
if let Some(def_id) = cx.tables.qpath_res(func_qpath, func.hir_id).opt_def_id();
if match_def_path(cx, def_id, &paths::MEM_DISCRIMINANT);
// type is non-enum
let ty_param = cx.tables.node_substs(func.hir_id).type_at(0);
if !ty_param.is_enum();
then {
span_lint_and_then(
cx,
MEM_DISCRIMINANT_NON_ENUM,
expr.span,
&format!("calling `mem::discriminant` on non-enum type `{}`", ty_param),
|db| {
// if this is a reference to an enum, suggest dereferencing
let (base_ty, ptr_depth) = walk_ptrs_ty_depth(ty_param);
if ptr_depth >= 1 && base_ty.is_enum() {
let param = &func_args[0];
// cancel out '&'s first
let mut derefs_needed = ptr_depth;
let mut cur_expr = param;
while derefs_needed > 0 {
if let ExprKind::AddrOf(BorrowKind::Ref, _, ref inner_expr) = cur_expr.kind {
derefs_needed -= 1;
cur_expr = inner_expr;
} else {
break;
}
}
let derefs: String = iter::repeat('*').take(derefs_needed).collect();
db.span_suggestion(
param.span,
"try dereferencing",
format!("{}{}", derefs, snippet(cx, cur_expr.span, "<param>")),
Applicability::MachineApplicable,
);
}
},
)
}
}
}
}
| true
|
ceda5e111548a76b1b5588d404a9262f6bd2e5c6
|
Rust
|
Luthaf/vecmap
|
/src/lib.rs
|
UTF-8
| 17,930
| 3.671875
| 4
|
[] |
no_license
|
use std::borrow::Borrow;
use std::ops::Index;
use std::fmt::Debug;
use std::mem;
use std::fmt;
use std::slice;
use std::vec;
#[derive(Clone)]
pub struct VecMap<K, V> {
values: Vec<V>,
keys: Vec<K>,
}
impl<K: Eq, V> VecMap<K, V> {
/// Create an empty `VecMap`
pub fn new() -> VecMap<K, V> {
VecMap {
values: Vec::new(),
keys: Vec::new(),
}
}
/// Create an empty `VecMap` with the given initial capacity
pub fn with_capacity(capacity: usize) -> VecMap<K, V> {
VecMap {
values: Vec::with_capacity(capacity),
keys: Vec::with_capacity(capacity),
}
}
/// Returns the number of elements the map can hold without reallocating.
///
/// # Examples
/// ```
/// use vecmap::VecMap;
/// let map: VecMap<isize, isize> = VecMap::with_capacity(100);
/// assert!(map.capacity() >= 100);
/// ```
pub fn capacity(&self) -> usize {
self.values.capacity()
}
/// Reserves capacity for at least additional more elements to be inserted
/// in the `VecMap`. The collection may reserve more space to avoid frequent
/// reallocations.
///
/// # Panics
///
/// Panics if the new allocation size overflows usize.
///
/// # Examples
/// ```
/// use vecmap::VecMap;
/// let mut map: VecMap<&str, isize> = VecMap::new();
/// map.reserve(10);
/// ```
pub fn reserve(&mut self, additional: usize) {
self.values.reserve(additional);
}
/// Shrinks the capacity of the map as much as possible.
///
/// # Examples
/// ```
/// use vecmap::VecMap;
/// let mut map: VecMap<isize, isize> = VecMap::with_capacity(100);
/// map.insert(1, 2);
/// map.insert(3, 4);
/// assert!(map.capacity() >= 100);
/// map.shrink_to_fit();
/// assert!(map.capacity() == 2);
/// ```
pub fn shrink_to_fit(&mut self) {
self.values.shrink_to_fit();
}
/// An iterator visiting all keys in insertion order.
/// Iterator element type is `&'a K`.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// map.insert("a", 1);
/// map.insert("b", 2);
/// map.insert("c", 3);
///
/// for key in map.keys() {
/// println!("{}", key);
/// }
/// ```
pub fn keys(&self) -> Keys<K> {
Keys{inner: self.keys.iter()}
}
/// An iterator visiting all values in insertion order.
/// Iterator element type is `&'a V`.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// map.insert("a", 1);
/// map.insert("b", 2);
/// map.insert("c", 3);
///
/// for val in map.values() {
/// println!("{}", val);
/// }
/// ```
pub fn values(&self) -> Values<V> {
Values{inner: self.values.iter()}
}
/// An iterator visiting all values mutably in insertion order.
/// Iterator element type is `&'a mut V`.
///
/// # Examples
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
///
/// map.insert("a", 1);
/// map.insert("b", 2);
/// map.insert("c", 3);
///
/// for val in map.values_mut() {
/// *val = *val + 10;
/// }
///
/// for val in map.values() {
/// print!("{}", val);
/// }
/// ```
pub fn values_mut(&mut self) -> ValuesMut<V> {
ValuesMut{inner: self.values.iter_mut()}
}
/// An iterator visiting all key-value pairs in insertion order.
/// Iterator element type is `(&'a K, &'a V)`.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// map.insert("a", 1);
/// map.insert("b", 2);
/// map.insert("c", 3);
///
/// for (key, val) in map.iter() {
/// println!("key: {} val: {}", key, val);
/// }
/// ```
pub fn iter(&self) -> Iter<K, V> {
Iter {
keys: self.keys.iter(),
values: self.values.iter()
}
}
/// An iterator visiting all key-value pairs in insertion order, with
/// mutable references to the values.
/// Iterator element type is `(&'a K, &'a mut V)`.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// map.insert("a", 1);
/// map.insert("b", 2);
/// map.insert("c", 3);
///
/// // Update all values
/// for (_, val) in map.iter_mut() {
/// *val *= 2;
/// }
///
/// for (key, val) in &map {
/// println!("key: {} val: {}", key, val);
/// }
/// ```
pub fn iter_mut(&mut self) -> IterMut<K, V> {
IterMut {
keys: self.keys.iter(),
values: self.values.iter_mut()
}
}
/// Gets the given key's corresponding entry in the map for in-place manipulation.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut letters = VecMap::new();
///
/// for ch in "a short treatise on fungi".chars() {
/// let counter = letters.entry(ch).or_insert(0);
/// *counter += 1;
/// }
///
/// assert_eq!(letters[&'s'], 2);
/// assert_eq!(letters[&'t'], 3);
/// assert_eq!(letters[&'u'], 1);
/// assert_eq!(letters.get(&'y'), None);
/// ```
pub fn entry(&mut self, key: K) -> Entry<K, V> {
match self.key_index(&key) {
Some(i) => Entry::Occupied(OccupiedEntry{
key: &self.keys[i],
value: &mut self.values[i]
}),
None => Entry::Vacant(VacantEntry{
key: key,
map: self
})
}
}
/// Returns the number of elements in the map.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut a = VecMap::new();
/// assert_eq!(a.len(), 0);
/// a.insert(1, "a");
/// assert_eq!(a.len(), 1);
/// ```
pub fn len(&self) -> usize {
debug_assert!(self.keys.len() == self.values.len());
self.values.len()
}
/// Returns true if the map contains no elements.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut a = VecMap::new();
/// assert!(a.is_empty());
/// a.insert(1, "a");
/// assert!(!a.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Clears the map, returning all key-value pairs as an iterator. Keeps the
/// allocated memory for reuse.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut a = VecMap::new();
/// a.insert(1, "a");
/// a.insert(2, "b");
///
/// for (k, v) in a.drain().take(1) {
/// assert!(k == 1 || k == 2);
/// assert!(v == "a" || v == "b");
/// }
///
/// assert!(a.is_empty());
/// ```
#[inline]
pub fn drain(&mut self) -> Drain<K, V> {
Drain {
keys: self.keys.drain(..),
values: self.values.drain(..),
}
}
/// Clears the map, removing all key-value pairs. Keeps the allocated memory
/// for reuse.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut a = VecMap::new();
/// a.insert(1, "a");
/// a.clear();
/// assert!(a.is_empty());
/// ```
#[inline]
pub fn clear(&mut self) {
self.values.clear();
self.keys.clear();
}
/// Returns a reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the map's key type, but `Eq` on the
/// borrowed form *must* match the one for the key type.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.get(&1), Some(&"a"));
/// assert_eq!(map.get(&2), None);
/// ```
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> where K: Borrow<Q>, Q: Eq {
self.key_index(key).map(|i| &self.values[i])
}
/// Returns a mutable reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the map's key type, but `Eq` on the
/// borrowed form *must* match the one for the key type.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// map.insert(1, "a");
/// if let Some(x) = map.get_mut(&1) {
/// *x = "b";
/// }
/// assert_eq!(map[&1], "b");
/// ```
pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V> where K: Borrow<Q>, Q: Eq {
match self.key_index(key) {
Some(i) => Some(&mut self.values[i]),
None => None
}
}
/// Returns true if the map contains a value for the specified key.
///
/// The key may be any borrowed form of the map's key type, but `Eq` on the
/// borrowed form *must* match the one for the key type.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.contains_key(&1), true);
/// assert_eq!(map.contains_key(&2), false);
/// ```
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where K: Borrow<Q>, Q: Eq {
self.key_index(key).is_some()
}
/// Inserts a key-value pair into the map.
///
/// If the map did not have this key present, `None` is returned.
///
/// If the map did have this key present, the value is updated, and the old
/// value is returned. The key is not updated, though; this matters for
/// types that can be `==` without being identical.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// assert_eq!(map.insert(37, "a"), None);
/// assert_eq!(map.is_empty(), false);
///
/// map.insert(37, "b");
/// assert_eq!(map.insert(37, "c"), Some("b"));
/// assert_eq!(map[&37], "c");
/// ```
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
match self.key_index(&key) {
Some(i) => {
let mut value = value;
mem::swap(&mut self.values[i], &mut value);
return Some(value);
}
None => {
self.values.push(value);
self.keys.push(key);
return None;
}
}
}
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
///
/// The key may be any borrowed form of the map's key type, but `Eq` on the
/// borrowed form *must* match the one for the key type.
///
/// # Examples
///
/// ```
/// use vecmap::VecMap;
///
/// let mut map = VecMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.remove(&1), Some("a"));
/// assert_eq!(map.remove(&1), None);
/// ```
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V> where K: Borrow<Q>, Q: Eq {
match self.key_index(key) {
Some(i) => {
self.keys.remove(i);
Some(self.values.remove(i))
}
None => None
}
}
/// Find the given key in the map, and return the corresponding index, or
/// `None`.
fn key_index<Q: ?Sized>(&self, key: &Q) -> Option<usize> where K: Borrow<Q>, Q: Eq {
for (i, entry) in self.keys.iter().enumerate() {
if entry.borrow() == key {
return Some(i);
}
}
return None;
}
}
impl<K: Eq, V> Default for VecMap<K, V> {
fn default() -> VecMap<K, V> {
VecMap::new()
}
}
impl<'a, K: Eq, Q: ?Sized, V> Index<&'a Q> for VecMap<K, V> where K: Borrow<Q>, Q: Eq {
type Output = V;
#[inline]
fn index(&self, index: &Q) -> &V {
self.get(index).expect("no entry found for key")
}
}
impl<K: Eq, V> Debug for VecMap<K, V> where K: Debug, V: Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(write!(f, "{{"));
for (k, v) in self {
try!(write!(f, "{:?}: {:?}", k, v));
}
try!(write!(f, "}}"));
Ok(())
}
}
impl<K: Eq, V> PartialEq for VecMap<K, V> where V: PartialEq {
fn eq(&self, other: &VecMap<K, V>) -> bool {
unimplemented!()
}
}
impl<K: Eq, V> Eq for VecMap<K, V> where V: Eq {}
impl<K: Eq, V> IntoIterator for VecMap<K, V> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> IntoIter<K, V> {
IntoIter {
keys: self.keys.into_iter(),
values: self.values.into_iter()
}
}
}
impl<'a, K: Eq, V> IntoIterator for &'a VecMap<K, V> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
impl<'a, K: Eq, V> IntoIterator for &'a mut VecMap<K, V> {
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
fn into_iter(self) -> IterMut<'a, K, V> {
self.iter_mut()
}
}
pub enum Entry<'a, K: 'a, V: 'a> where K: Eq {
Occupied(OccupiedEntry<'a, K, V>),
Vacant(VacantEntry<'a, K, V>),
}
pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
key: &'a K,
value: &'a mut V
}
pub struct VacantEntry<'a, K: 'a, V: 'a> {
key: K,
map: &'a mut VecMap<K, V>
}
impl<'a, K: Eq, V> Entry<'a, K, V> {
/// Ensures a value is in the entry by inserting the default if empty, and
/// returns a mutable reference to the value in the entry.
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.value,
Entry::Vacant(entry) => {
entry.map.insert(entry.key, default);
let i = entry.map.len() - 1;
&mut entry.map.values[i]
},
}
}
/// Ensures a value is in the entry by inserting the result of the default
/// function if empty, and returns a mutable reference to the value in the
/// entry.
pub fn or_insert_with<F>(self, default: F) -> &'a mut V where F: FnOnce() -> V {
match self {
Entry::Occupied(entry) => entry.value,
Entry::Vacant(entry) => {
entry.map.insert(entry.key, default());
let i = entry.map.len() - 1;
&mut entry.map.values[i]
},
}
}
/// Returns a reference to this entry's key
pub fn key(&self) -> &K {
match *self {
Entry::Occupied(ref entry) => entry.key,
Entry::Vacant(ref entry) => &entry.key,
}
}
}
pub struct Keys<'a, K: 'a> {
inner: slice::Iter<'a, K>
}
impl<'a, K> Iterator for Keys<'a, K> {
type Item = &'a K;
fn next(&mut self) -> Option<&'a K> {
self.inner.next()
}
}
pub struct Values<'a, V: 'a> {
inner: slice::Iter<'a, V>
}
impl<'a, V> Iterator for Values<'a, V> {
type Item = &'a V;
fn next(&mut self) -> Option<&'a V> {
self.inner.next()
}
}
pub struct ValuesMut<'a, V: 'a> {
inner: slice::IterMut<'a, V>
}
impl<'a, V> Iterator for ValuesMut<'a, V> {
type Item = &'a mut V;
fn next(&mut self) -> Option<&'a mut V> {
self.inner.next()
}
}
pub struct Iter<'a, K: 'a , V: 'a > {
keys: slice::Iter<'a, K>,
values: slice::Iter<'a, V>
}
impl<'a, K, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<(&'a K, &'a V)> {
match self.keys.next() {
Some(key) => {
let value = self.values.next().expect("Internal error: invalid size for values iterator");
Some((key, value))
}
None => {
debug_assert!(self.values.next().is_none());
None
}
}
}
}
pub struct IterMut<'a, K: 'a , V: 'a > {
keys: slice::Iter<'a, K>,
values: slice::IterMut<'a, V>
}
impl<'a, K, V> Iterator for IterMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
match self.keys.next() {
Some(key) => {
let value = self.values.next().expect("Internal error: invalid size for values iterator");
Some((key, value))
}
None => {
debug_assert!(self.values.next().is_none());
None
}
}
}
}
pub struct Drain<'a, K: 'a, V: 'a> {
keys: vec::Drain<'a, K>,
values: vec::Drain<'a, V>
}
impl<'a, K, V> Iterator for Drain<'a, K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
match self.keys.next() {
Some(key) => {
let value = self.values.next().expect("Internal error: invalid size for values iterator");
Some((key, value))
}
None => {
debug_assert!(self.values.next().is_none());
None
}
}
}
}
pub struct IntoIter<K, V> {
keys: vec::IntoIter< K>,
values: vec::IntoIter<V>
}
impl<K, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
match self.keys.next() {
Some(key) => {
let value = self.values.next().expect("Internal error: invalid size for values iterator");
Some((key, value))
}
None => {
debug_assert!(self.values.next().is_none());
None
}
}
}
}
// Traits: Extend, FromIterator
| true
|
a96271ca74d085769e6474b3b29865502551ca0f
|
Rust
|
rahulnakre/rust_channels
|
/src/lib.rs
|
UTF-8
| 6,148
| 3.296875
| 3
|
[] |
no_license
|
#![feature(test)]
use std::sync::{Arc, Condvar, Mutex};
// Vector with head and tail pointer
use std::collections::VecDeque;
use std::thread;
use std::sync::mpsc;
extern crate test;
pub struct Sender<T> {
shared: Arc<Shared<T>>,
}
/**
* Need to have Sender be cloneable, but #[derive(Clone)] doesn't work,
* as it desugars to:
* impl<T: Clone> Clone for Sender<T> {
* fn clone(&self) -> Self {
* // ....
* }
* }
* which adds the Clone bound to T as well.
* In our case, Arc implements Clone even if T doesn't implement Clone
*
*/
impl<T> Clone for Sender<T> {
fn clone(&self) -> Self {
// cus we're keeping track of # of senders,
// we need to update the count when cloning
let mut inner = self.shared.inner.lock().unwrap();
inner.senders += 1;
drop(inner);
Sender {
// dont do this
// shared: self.shared.clone(),
// we do this to say we want to clone the Arc,
// not the thing inside
shared: Arc::clone(&self.shared),
}
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
let mut inner = self.shared.inner.lock().unwrap();
inner.senders -= 1;
let was_last = inner.senders == 0;
drop(inner);
if was_last {
self.shared.available.notify_one();
}
}
}
impl<T> Sender<T> {
pub fn send(&mut self, t: T) {
// Note the thing about the poisoned lock
let mut inner = self.shared.inner.lock().unwrap();
inner.queue.push_back(t);
// drop the lock so that whoever we notify can wake up immediately,
// and we notify one thread
drop(inner);
self.shared.available.notify_one();
}
}
// Needs a mutex cus a send and recv can happen at the same time
pub struct Receiver<T> {
shared: Arc<Shared<T>>,
buffer: VecDeque<T>,
}
impl<T> Receiver<T> {
// We're implementing a blocking receive, where
// if there's nothing yet, it waits to receive something
// unlike a try_recv, which would return Option<T>
// Note: while trying to deal with the 0 senders case,
// we do end up needing an Option<T> cus it can be none
// if a Receiver is still blocking while senders r gone
pub fn recv(&mut self) -> Option<T> {
// for batch recv optimization: *
// if there's some leftover items from the last time we took the lock
if let Some(t) = self.buffer.pop_front() {
return Some(t)
}
let mut inner = self.shared.inner.lock().unwrap();
loop {
match inner.queue.pop_front() {
// return drops the mutex btw
Some(t) => {
// for batch recv optimization: *
// we only have 1 receiver, so anytime we do get the lock,
// might as well pick off everything from the queue at once
if !inner.queue.is_empty() {
// swap that vedeque w this new vecdeque
std::mem::swap(&mut self.buffer, &mut inner.queue)
}
return Some(t)
}
// None if dbg!(inner.senders) == 0 => return None,
None if inner.senders == 0 => return None,
None => {
// only if # of senders > 0 do we end up here
// have to give up mutex when waiting
inner = self.shared.available.wait(inner).unwrap();
}
}
}
}
}
impl<T> Iterator for Receiver<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.recv()
}
}
struct Inner<T> {
queue: VecDeque<T>,
senders: usize,
}
// common thing in rust when multiple handles
// that point to the same thing
// the shared (inner) type holds the data that is shared
// we use Mutex over a boolean semaphore bc
// - semaphore would have to spin on the condition,
// but Mutex's sleep/awake will be handled by the OS
struct Shared<T> {
// receiver deal with the oldest message on channel first
inner: Mutex<Inner<T>>,
// condvar has to be outside the mutex btw, so sleeping
// threads can wake
available: Condvar,
}
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let inner = Inner {
queue: VecDeque::default(),
senders: 1,
};
let shared = Shared {
inner: Mutex::new(inner),
available: Condvar::new()
};
// shared
let shared = Arc::new(shared);
// return a (sender, receiver) of that shared
(
Sender {
shared: shared.clone(),
},
Receiver {
shared: shared.clone(),
buffer: VecDeque::default(),
}
)
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn ping_pong() {
let (mut tx, mut rx) = channel();
tx.send(42);
assert_eq!(rx.recv(), Some(42))
}
// this hangs
// need a way to tell receivers that all
// senders are closed
#[test]
fn closed_tx() {
let (tx, mut rx) = channel::<()>();
// doesnt drop tx for some reason
// let _ = tx;
drop(tx);
assert_eq!(rx.recv(), None);
}
#[test]
fn closed_rx() {
let (_tx, rx) = channel::<()>();
drop(rx);
// tx.send(42);
}
fn my_channel_send_main() {
let (mut tx, mut rx) = channel();
tx.send(10);
// assert_eq!(rx.recv(), Some(10));
}
#[bench]
fn my_channel_send(b: &mut Bencher) {
b.iter(|| {
my_channel_send_main();
});
}
fn mpsc_channel_send_main() {
let (tx, rx) = mpsc::channel();
tx.send(10);
// assert_eq!(rx.recv(), Some(10));
}
#[bench]
fn mpsc_channel_send(b: &mut Bencher) {
b.iter(|| {
mpsc_channel_send_main();
});
}
fn play2_main() {
let (tx, mut rx): (Sender<i32>, Receiver<i32>) = channel();
let mut children = Vec::new();
static NTHREADS: i32 = 30;
for id in 0..NTHREADS {
let mut thread_tx = tx.clone();
let child = thread::spawn(move || {
thread_tx.send(id);
println!("Thread {} done", id);
});
children.push(child);
}
// messages collected
let mut ids = Vec::with_capacity(NTHREADS as usize);
for _ in 0..NTHREADS {
ids.push(rx.recv());
}
for child in children {
child.join().expect("child thread panicked");
}
println!("{:?}", ids);
}
#[bench]
fn play2(b: &mut Bencher) {
b.iter(|| {
play2_main();
})
}
}
| true
|
e3c7588ebe4866064c1a6172aaf2996b9316fe44
|
Rust
|
Razaekel/noise-rs
|
/examples/perlin.rs
|
UTF-8
| 1,067
| 2.625
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! An example of using perlin noise
extern crate noise;
use noise::{
core::perlin::{perlin_2d, perlin_3d, perlin_4d},
permutationtable::PermutationTable,
utils::*,
};
mod utils;
fn main() {
let hasher = PermutationTable::new(0);
utils::write_example_to_file(
&PlaneMapBuilder::new_fn(|point| perlin_2d(point.into(), &hasher))
.set_size(1024, 1024)
.set_x_bounds(-5.0, 5.0)
.set_y_bounds(-5.0, 5.0)
.build(),
"perlin_2d.png",
);
utils::write_example_to_file(
&PlaneMapBuilder::new_fn(|point| perlin_3d(point.into(), &hasher))
.set_size(1024, 1024)
.set_x_bounds(-5.0, 5.0)
.set_y_bounds(-5.0, 5.0)
.build(),
"perlin_3d.png",
);
utils::write_example_to_file(
&PlaneMapBuilder::new_fn(|point| perlin_4d(point.into(), &hasher))
.set_size(1024, 1024)
.set_x_bounds(-5.0, 5.0)
.set_y_bounds(-5.0, 5.0)
.build(),
"perlin_4d.png",
);
}
| true
|
345147513b607baa21473d2312d3013c06417f87
|
Rust
|
drhodes/regmach
|
/regmach/src/dsp/colors.rs
|
UTF-8
| 867
| 2.734375
| 3
|
[] |
no_license
|
use crate::dsp::types::*;
const fn c(r: u8, g: u8, b: u8) -> Color {
Color { r, g, b }
}
pub const BACKGROUND: Color = c(250, 250, 250);
pub const BLACK: Color = c(0, 0, 0);
pub const BLUE: Color = c(0, 0, 255);
pub const CURSOR_DARK: Color = c(23, 23, 23);
pub const CURSOR_LIGHT: Color = c(190, 190, 190);
pub const GRAY: Color = c(50, 50, 5);
pub const GREEN: Color = c(0, 255, 0);
pub const GREY: Color = c(50, 50, 5);
pub const GRID_GRAY: Color = c(0xEE, 0xEE, 0xEE);
pub const JADE_BLUE: Color = c(38, 139, 210);
pub const LIGHT_BLUE: Color = c(200, 200, 255);
pub const RED: Color = c(255, 0, 0);
pub const WHITE: Color = c(255, 255, 255);
impl Color {
pub fn as_gl(&self) -> (f32, f32, f32, f32) {
(
self.r as f32 / 255.0,
self.g as f32 / 255.0,
self.b as f32 / 255.0,
1.0,
)
}
}
| true
|
59392164af2e20f7755c263ade97fcfbd5c69819
|
Rust
|
triplef87/advent_of_code_2015
|
/day_23/src/main.rs
|
UTF-8
| 2,503
| 3
| 3
|
[] |
no_license
|
use std::{fs::File, io, path::Path};
use io::BufRead;
fn main() {
let mut instructions: Vec<String> = Vec::new();
if let Ok(lines) = read_lines("input") {
for line in lines {
if let Ok(row) = line {
instructions.push(row);
}
}
}
let mut index = 0;
let mut values = (1, 0);
while index < instructions.len() {
println!("{:?}", values);
let instruction: Vec<&str> = instructions.get(index).unwrap().split(" ").collect();
match instruction[0] {
"hlf" => {
values.0 = values.0 / 2;
index = index + 1;
},
"tpl" => {
values.0 = values.0 * 3;
index = index + 1;
},
"inc" => {
if instruction[1] == "a" {
values.0 = values.0 + 1;
} else {
values.1 = values.1 + 1;
}
index = index + 1;
},
"jmp" => {
let offset: i32 = instruction[1].parse().unwrap();
if offset.is_negative() {
index = index - offset.wrapping_abs() as usize;
} else {
index = index + offset as usize;
}
},
"jie" => {
if values.0 % 2 == 0 {
let offset: i32 = instruction[2].parse().unwrap();
if offset.is_negative() {
index = index - offset.wrapping_abs() as usize;
} else {
index = index + offset as usize;
}
} else {
index = index + 1;
}
},
"jio" => {
if values.0 == 1 {
let offset: i32 = instruction[2].parse().unwrap();
if offset.is_negative() {
index = index - offset.wrapping_abs() as usize;
} else {
index = index + offset as usize;
}
} else {
index = index + 1;
}
},
_ => {
}
}
}
println!("{:?}", values);
}
fn read_lines<P>(arg: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path> {
let file = File::open(arg)?;
Ok(io::BufReader::new(file).lines())
}
| true
|
40e59a241326685f4717bf354193dfa13caa5d3b
|
Rust
|
Batanick/mmmodel
|
/src/entities.rs
|
UTF-8
| 14,900
| 3.015625
| 3
|
[] |
no_license
|
use rand::{thread_rng, Rng};
use std::f32::consts::PI;
use std::cell::Cell;
use std::fmt::Debug;
pub type UserId = usize;
#[derive(Debug)]
pub struct UserData {
pub id: UserId,
pub real_skill: f32,
skill: Cell<f32>,
join_time: Cell<u32>,
use_real_skill: bool,
}
impl UserData {
fn new(id: UserId, initial_skill: f32, real_skill: f32, use_real_skill: bool) -> UserData {
UserData {
id: id,
skill: Cell::new(initial_skill),
real_skill: real_skill,
join_time: Cell::new(0),
use_real_skill: use_real_skill,
}
}
pub fn set_join_time(&self, join_time: u32) {
self.join_time.set(join_time);
}
pub fn get_join_time(&self) -> u32 {
self.join_time.get()
}
pub fn update_skill(&self, delta: f32) {
if self.use_real_skill {
return;
}
self.skill.set(self.skill.get() + delta);
}
pub fn get_skill(&self) -> f32 {
if self.use_real_skill { self.real_skill } else { self.skill.get() }
}
}
#[derive(Debug)]
pub struct UserPool {
users: Vec<UserData>,
pub use_real_skill: bool,
}
impl UserPool {
pub fn new(use_real_skill: bool) -> UserPool {
UserPool {
users: Vec::new(),
use_real_skill: use_real_skill,
}
}
pub fn generate(&mut self, initial_skill: f32, real_skill: f32) -> UserId {
let id = self.users.len();
self.users.push(UserData::new(id, initial_skill, real_skill, self.use_real_skill));
id
}
pub fn get_user(&self, id: &UserId) -> &UserData {
&self.users[*id]
}
pub fn get_avg_skill_error(&self) -> f32 {
let sum = self.users.iter().fold(0.0, |sum, data| sum + (data.real_skill - data.get_skill()).abs());
sum / (self.users.len() as f32)
}
}
#[derive(PartialEq)]
#[derive(Debug)]
pub struct Game {
pub team1: Vec<UserId>,
pub team2: Vec<UserId>,
}
impl Game {
pub fn new(team1: Vec<UserId>, team2: Vec<UserId>) -> Game {
Game {
team1: team1,
team2: team2,
}
}
pub fn process(&self, user_pool: &UserPool, win_team: u32) {
let (winners, losers) = match win_team {
1 => (&self.team1, &self.team2),
2 => (&self.team2, &self.team1),
_ => panic!()
};
let winners_avg = winners.iter().fold(0.0, |sum, id| sum + user_pool.get_user(id).get_skill()) / (winners.len() as f32);
let losers_avg = losers.iter().fold(0.0, |sum, id| sum + user_pool.get_user(id).get_skill()) / (losers.len() as f32);
let r_win = 10.0_f32.powf(winners_avg / 400.0);
let r_lose = 10.0_f32.powf(losers_avg / 400.0);
let e_win = r_win / (r_win + r_lose);
let e_lose = r_lose / (r_win + r_lose);
static K_FACTOR: f32 = 32.0;
let winner_delta = K_FACTOR * (1.0 - e_win);
let loser_delta = K_FACTOR * (-e_lose);
for id in winners {
user_pool.get_user(id).update_skill(winner_delta);
}
for id in losers {
user_pool.get_user(id).update_skill(loser_delta);
}
}
}
#[derive(PartialEq)]
#[derive(Debug)]
pub enum AlgorithmResult {
None,
Found(Game),
}
pub trait GameDecider: Debug {
fn decide(&self, game: &Game, pool: &UserPool) -> u32;
}
#[derive(Debug)]
pub struct RealSkillLevelDecider {}
impl GameDecider for RealSkillLevelDecider {
fn decide(&self, game: &Game, pool: &UserPool) -> u32 {
let skill1 = game.team1.iter().fold(0.0, |sum, id| sum + pool.get_user(id).real_skill);
let skill2 = game.team2.iter().fold(0.0, |sum, id| sum + pool.get_user(id).real_skill);
if skill1 == skill2 {
if thread_rng().gen() {
return 1;
} else {
return 2;
}
}
if skill1 > skill2 {
return 1;
} else {
return 2;
}
}
}
pub trait Algoritm: Debug {
fn search(&self, queue: &mut Vec<UserId>, pool: &UserPool) -> AlgorithmResult;
}
pub struct SimpleUserGenerator {
pub skill: f32,
}
pub fn peek_random<T>(vec: &mut Vec<T>) -> Option<T> {
if vec.len() == 0 {
return Option::None;
}
let index = thread_rng().gen_range(0, vec.len());
Option::Some(vec.remove(index))
}
#[derive(Debug)]
pub struct RandomPeekAlgorithm {
pub team_size: usize,
}
impl Algoritm for RandomPeekAlgorithm {
fn search(&self, queue: &mut Vec<UserId>, _: &UserPool) -> AlgorithmResult {
if queue.len() < (self.team_size * 2) {
return AlgorithmResult::None;
}
let mut team1 = Vec::new();
let mut team2 = Vec::new();
for _ in 0..self.team_size {
team1.push(peek_random(queue).unwrap());
team2.push(peek_random(queue).unwrap());
}
AlgorithmResult::Found(Game::new(team1, team2))
}
}
#[derive(Debug)]
pub struct SkillLevelAlgorithm {
pub team_size: usize,
pub size_factor: f32,
pub prefill_factor: f32,
}
impl Algoritm for SkillLevelAlgorithm {
fn search(&self, queue: &mut Vec<UserId>, pool: &UserPool) -> AlgorithmResult {
if (queue.len() as f32) < ((self.team_size as f32) * self.size_factor * 2.0) {
return AlgorithmResult::None;
}
let mut team1 = Vec::new();
let mut team2 = Vec::new();
let to_add = (self.prefill_factor * (self.team_size as f32) * 2.0) as u32;
if to_add > 0 {
for _ in 0..to_add {
let team_to_add = if team1.len() > team2.len() { &mut team2 } else { &mut team1 };
team_to_add.push(queue.remove(0));
}
}
let queue_avg = queue.iter().fold(0.0, |sum, id| sum + pool.get_user(id).get_skill()) / queue.len() as f32;
while team1.len() < self.team_size || team2.len() < self.team_size {
let team1_active = team1.len() < team2.len();
let (active_team, opp_team): (&mut Vec<UserId>, &mut Vec<UserId>) = if team1_active { (&mut team1, &mut team2) } else { (&mut team2, &mut team1) };
let active_team_skill = active_team.iter().fold(0.0, |sum, v| sum + pool.get_user(v).get_skill());
let opponent_team_skill = opp_team.iter().fold(0.0, |sum, v| sum + pool.get_user(v).get_skill());
let skil_delta = opponent_team_skill - active_team_skill;
let found = opp_team.len() + active_team.len();
let found_sum = active_team.iter().chain(opp_team.iter()).fold(0.0, |sum, id| sum + pool.get_user(id).get_skill());
let found_avg = if (found) == 0 { queue_avg } else { found_sum / found as f32 };
let desired_skill = if active_team.len() != opp_team.len() { skil_delta } else { skil_delta + found_avg };
let (index, _) = queue.iter().enumerate()
.map(|(index, id)| (index, (pool.get_user(id).get_skill() - desired_skill).abs()))
.fold((usize::max_value(), 1.0 / 0.0), |i, v| if v.1 > i.1 { i } else { (v.0, v.1) });
assert!(index != usize::max_value());
let candidate = queue.remove(index);
active_team.push(candidate)
}
AlgorithmResult::Found(Game::new(team1, team2))
}
}
#[derive(Debug)]
pub struct FIFOAlgorithm {
pub team_size: usize,
}
impl Algoritm for FIFOAlgorithm {
fn search(&self, queue: &mut Vec<UserId>, _: &UserPool) -> AlgorithmResult {
if queue.len() < (self.team_size * 2) {
return AlgorithmResult::None;
}
let mut team1 = Vec::new();
let mut team2 = Vec::new();
// queue is ordered by join time
for _ in 0..self.team_size {
team1.push(queue.remove(0));
team2.push(queue.remove(0));
}
AlgorithmResult::Found(Game::new(team1, team2))
}
}
#[derive(Debug)]
pub enum DistributionType {
Uniform,
Normal
}
#[derive(Debug)]
pub struct RandomRangeGen {
min: f32,
max: f32,
distribution: DistributionType,
}
impl RandomRangeGen {
pub fn new(min: f32, max: f32, distribution: DistributionType) -> RandomRangeGen {
RandomRangeGen {
min: min,
max: max,
distribution: distribution,
}
}
pub fn generate(&self) -> f32 {
let rand = match self.distribution {
DistributionType::Uniform => (thread_rng().next_f32()),
DistributionType::Normal => {
let u1 = thread_rng().next_f32();
let u2 = thread_rng().next_f32();
// https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
let mut result = (-2.0 * u1.ln()).sqrt() * ((2.0 * PI * u2).cos());
if result > 1.0 {
result = 1.0;
}
if result < -1.0 {
result = -1.0;
}
(result + 1.0) * 0.5
}
};
return ((self.max - self.min) * rand) + self.min;
}
}
// ============================ TESTS ============================
#[test]
fn test_skill_empty_queue() {
let algorithm = SkillLevelAlgorithm {
team_size: 5,
size_factor: 2.0,
prefill_factor: 0.0,
};
let pool = UserPool::new(false);
let mut queue = Vec::new();
assert!(algorithm.search(&mut queue, &pool) == AlgorithmResult::None);
}
#[test]
fn test_skill_small_queue() {
let algorithm = SkillLevelAlgorithm {
team_size: 5,
size_factor: 2.0,
prefill_factor: 0.0,
};
let mut pool = UserPool::new(false);
let mut queue = Vec::new();
for _ in 0..15 {
queue.push(pool.generate(500.0, 500.0))
}
assert!(algorithm.search(&mut queue, &pool) == AlgorithmResult::None);
}
#[test]
fn test_skill_small_prefill() {
let algorithm = SkillLevelAlgorithm {
team_size: 5,
size_factor: 2.0,
prefill_factor: 0.1,
};
let mut pool = UserPool::new(false);
let mut queue = Vec::new();
queue.push(pool.generate(10000.0, 10000.0));
for _ in 0..20 {
queue.push(pool.generate(500.0, 500.0))
}
let result = algorithm.search(&mut queue, &pool);
match result {
AlgorithmResult::Found(game) => {
assert!(game.team1.len() == 5);
assert!(game.team2.len() == 5);
assert_eq!(10000.0, pool.get_user(game.team1.get(0).unwrap()).get_skill());
}
_ => panic!("Incorrect result")
}
}
#[test]
fn test_skill_found() {
let algorithm = SkillLevelAlgorithm {
team_size: 5,
size_factor: 2.0,
prefill_factor: 0.0,
};
let mut pool = UserPool::new(false);
let mut queue = Vec::new();
for _ in 0..20 {
queue.push(pool.generate(500.0, 500.0))
}
let result = algorithm.search(&mut queue, &pool);
match result {
AlgorithmResult::Found(game) => {
assert!(game.team1.len() == 5);
assert!(game.team2.len() == 5);
}
_ => panic!("Incorrect result")
}
assert!(queue.len() == 10);
}
#[test]
fn test_clustered_queue() {
let algorithm = SkillLevelAlgorithm {
team_size: 5,
size_factor: 2.0,
prefill_factor: 0.0,
};
let mut pool = UserPool::new(false);
let mut queue = Vec::new();
for _ in 0..15 {
queue.push(pool.generate(500.0, 500.0))
}
for _ in 0..10 {
queue.push(pool.generate(10000.0, 10000.0))
}
thread_rng().shuffle(&mut queue);
let result = algorithm.search(&mut queue, &pool);
println!("{:?}", queue);
assert!(queue.len() == 15);
match result {
AlgorithmResult::Found(game) => {
println!("{:?}", game);
assert!(game.team1.len() == 5);
assert!(game.team2.len() == 5);
let team1_sum = game.team1.iter().fold(0.0, |sum, id| sum + pool.get_user(id).get_skill());
let team2_sum = game.team2.iter().fold(0.0, |sum, id| sum + pool.get_user(id).get_skill());
assert_eq!(team1_sum, team2_sum);
}
_ => panic!("Incorrect result")
}
}
#[test]
fn test_skill_level_sum() {
let algorithm = SkillLevelAlgorithm {
team_size: 5,
size_factor: 1.0,
prefill_factor: 0.0,
};
let mut pool = UserPool::new(false);
let mut queue = Vec::new();
for _ in 0..5 {
queue.push(pool.generate(450.0, 450.0))
}
for _ in 0..5 {
queue.push(pool.generate(550.0, 550.0))
}
for _ in 0..9 {
queue.push(pool.generate(10000.0, 10000.0))
}
thread_rng().shuffle(&mut queue);
let result = algorithm.search(&mut queue, &pool);
println!("Queue: {:?}", queue);
assert!(queue.len() == 9);
match result {
AlgorithmResult::Found(game) => {
println!("{:?}", game);
assert!(game.team1.len() == 5);
assert!(game.team2.len() == 5);
let team1_sum = game.team1.iter().fold(0.0, |sum, id| sum + pool.get_user(&id).get_skill());
let team2_sum = game.team2.iter().fold(0.0, |sum, id| sum + pool.get_user(&id).get_skill());
assert!((team1_sum - team2_sum).abs() <= 100.0);
}
_ => panic!("Incorrect result")
}
}
#[test]
fn rating_update() {
let mut pool = UserPool::new(false);
let user1 = pool.generate(2400.0, 0.0);
let user2 = pool.generate(2000.0, 0.0);
let game = Game::new(vec!(user1), vec!(user2));
game.process(&pool, 1);
assert!((pool.get_user(&user1).get_skill() - 2403.0).abs() < 0.1);
assert!((pool.get_user(&user2).get_skill() - 1997.0).abs() < 0.1);
}
#[test]
fn rating_update2() {
let mut pool = UserPool::new(false);
let user1 = pool.generate(2400.0, 0.0);
let user2 = pool.generate(2000.0, 0.0);
let game = Game::new(vec!(user1), vec!(user2));
game.process(&pool, 2);
assert!((pool.get_user(&user1).get_skill() - 2371.0).abs() < 0.1);
assert!((pool.get_user(&user2).get_skill() - 2029.0).abs() < 0.1);
}
#[test]
fn team_rating_update() {
let mut pool = UserPool::new(false);
let user1 = pool.generate(2800.0, 0.0);
let user2 = pool.generate(2000.0, 0.0);
let user3 = pool.generate(1000.0, 0.0);
let user4 = pool.generate(3000.0, 0.0);
println!("{:?}", pool);
let game = Game::new(vec!(user1, user2), vec!(user3, user4));
game.process(&pool, 2);
println!("{:?}", pool);
assert!((pool.get_user(&user1).get_skill() - 2771.0).abs() < 0.1);
assert!((pool.get_user(&user2).get_skill() - 1971.0).abs() < 0.1);
assert!((pool.get_user(&user3).get_skill() - 1029.0).abs() < 0.1);
assert!((pool.get_user(&user4).get_skill() - 3029.0).abs() < 0.1);
}
| true
|
41d33b348b0ca6ec238e2ff7fed48dda8a5b5bd3
|
Rust
|
fagossa/introrust_xebia
|
/workspace/src/test.rs
|
UTF-8
| 268
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
#[cfg(test)]
mod test {
describe!(
before_each {
let awesome = true;
}
it "is awesome" {
assert!(awesome);
}
it "injects before_each into all test cases" {
let still_awesome = awesome;
assert!(still_awesome);
}
)
}
| true
|
8c84e4312ac4aa738d6a4243b1080400ffbfc835
|
Rust
|
geofmureithi-zz/rethinkdb-rs
|
/tests/common/mod.rs
|
UTF-8
| 1,115
| 2.6875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
use std::process::Command;
// This should stop any current running database, and start a new one
// that has the database 'test', containing the table 'test'
// and also has a user named 'bob', with password 'secret'
pub fn setup() {
//setup code specific to your library's tests would go here
Command::new("sh")
.arg("-c")
.arg("rm -rf tests/rethinkdb_data")
.spawn()
.expect("failed to kill databases");
Command::new("sh")
.arg("-c")
.arg("cp -r tests/fresh_data tests/rethinkdb_data")
.spawn()
.expect("failed to kill databases");
Command::new("sh")
.arg("-c")
.arg("killall rethinkdb")
.spawn()
.expect("failed to kill databases");
std::thread::sleep(std::time::Duration::from_millis(500));
Command::new("rethinkdb")
.arg("--daemon")
.arg("--directory")
.arg("tests/rethinkdb_data")
.spawn()
.expect("failed to start database");
// takes time for the test to get tables ready
std::thread::sleep(std::time::Duration::from_secs(20));
}
| true
|
d7cdf71c9eb26071937618618783cdecb648918c
|
Rust
|
jessaimaya/MoonZoon
|
/crates/zoon/src/style/font.rs
|
UTF-8
| 3,799
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
use crate::*;
use std::borrow::Cow;
mod font_weight;
pub use font_weight::{FontWeight, NamedWeight};
mod font_family;
pub use font_family::FontFamily;
#[derive(Default)]
pub struct Font<'a> {
static_css_props: StaticCSSProps<'a>,
dynamic_css_props: DynamicCSSProps,
}
impl<'a> Font<'a> {
pub fn weight(mut self, weight: impl FontWeight<'a>) -> Self {
self.static_css_props
.insert("font-weight", weight.into_cow_str());
self
}
pub fn color(mut self, color: impl Into<Option<HSLuv>>) -> Self {
if let Some(color) = color.into() {
self.static_css_props.insert("color", color.into_cow_str());
}
self
}
pub fn color_signal(
mut self,
color: impl Signal<Item = impl Into<Option<HSLuv>>> + Unpin + 'static,
) -> Self {
let color = color.map(|color| color.into().map(|color| color.into_cow_str()));
self.dynamic_css_props
.insert("color".into(), box_css_signal(color));
self
}
pub fn size(mut self, size: u32) -> Self {
self.static_css_props.insert("font-size", px(size));
self
}
pub fn line_height(mut self, line_height: u32) -> Self {
self.static_css_props.insert("line-height", px(line_height));
self
}
pub fn italic(mut self) -> Self {
self.static_css_props.insert("font-style", "italic".into());
self
}
pub fn no_wrap(mut self) -> Self {
self.static_css_props.insert("white-space", "nowrap".into());
self
}
pub fn underline(mut self) -> Self {
self.static_css_props
.insert("text-decoration", "underline".into());
self
}
pub fn underline_signal(
mut self,
underline: impl Signal<Item = bool> + Unpin + 'static,
) -> Self {
let underline = underline.map_bool(|| "underline", || "none");
self.dynamic_css_props
.insert("text-decoration".into(), box_css_signal(underline));
self
}
pub fn strike(mut self) -> Self {
self.static_css_props
.insert("text-decoration", "line-through".into());
self
}
pub fn strike_signal(mut self, strike: impl Signal<Item = bool> + Unpin + 'static) -> Self {
let strike = strike.map_bool(|| "line-through", || "none");
self.dynamic_css_props
.insert("text-decoration".into(), box_css_signal(strike));
self
}
pub fn center(mut self) -> Self {
self.static_css_props.insert("text-align", "center".into());
self
}
pub fn family(mut self, family: impl IntoIterator<Item = FontFamily<'a>>) -> Self {
let font_family = family
.into_iter()
.map(|family| family.into_cow_str())
.collect::<Cow<_>>()
.join(", ");
self.static_css_props
.insert("font-family", font_family.into());
self
}
}
impl<'a> Style<'a> for Font<'a> {
fn apply_to_raw_el<E: RawEl>(
self,
mut raw_el: E,
style_group: Option<StyleGroup<'a>>,
) -> (E, Option<StyleGroup<'a>>) {
if let Some(mut style_group) = style_group {
for (name, value) in self.static_css_props {
style_group = style_group.style(name, value);
}
for (name, value) in self.dynamic_css_props {
style_group = style_group.style_signal(name, value);
}
return (raw_el, Some(style_group));
}
for (name, value) in self.static_css_props {
raw_el = raw_el.style(name, &value);
}
for (name, value) in self.dynamic_css_props {
raw_el = raw_el.style_signal(name, value);
}
(raw_el, None)
}
}
| true
|
78fc14f1f12dbe49260c40e560be10d75d3e8971
|
Rust
|
ferrous-systems/imxrt1052
|
/src/pxp/ctrl_tog/mod.rs
|
UTF-8
| 26,467
| 2.765625
| 3
|
[] |
no_license
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CTRL_TOG {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct ENABLER {
bits: bool,
}
impl ENABLER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct IRQ_ENABLER {
bits: bool,
}
impl IRQ_ENABLER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct NEXT_IRQ_ENABLER {
bits: bool,
}
impl NEXT_IRQ_ENABLER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct ENABLE_LCD_HANDSHAKER {
bits: bool,
}
impl ENABLE_LCD_HANDSHAKER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct RSVD0R {
bits: u8,
}
impl RSVD0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = "Possible values of the field `ROTATE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ROTATER {
#[doc = "ROT_0"]
ROT_0,
#[doc = "ROT_90"]
ROT_90,
#[doc = "ROT_180"]
ROT_180,
#[doc = "ROT_270"]
ROT_270,
}
impl ROTATER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
ROTATER::ROT_0 => 0,
ROTATER::ROT_90 => 1,
ROTATER::ROT_180 => 2,
ROTATER::ROT_270 => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> ROTATER {
match value {
0 => ROTATER::ROT_0,
1 => ROTATER::ROT_90,
2 => ROTATER::ROT_180,
3 => ROTATER::ROT_270,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `ROT_0`"]
#[inline]
pub fn is_rot_0(&self) -> bool {
*self == ROTATER::ROT_0
}
#[doc = "Checks if the value of the field is `ROT_90`"]
#[inline]
pub fn is_rot_90(&self) -> bool {
*self == ROTATER::ROT_90
}
#[doc = "Checks if the value of the field is `ROT_180`"]
#[inline]
pub fn is_rot_180(&self) -> bool {
*self == ROTATER::ROT_180
}
#[doc = "Checks if the value of the field is `ROT_270`"]
#[inline]
pub fn is_rot_270(&self) -> bool {
*self == ROTATER::ROT_270
}
}
#[doc = r" Value of the field"]
pub struct HFLIPR {
bits: bool,
}
impl HFLIPR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct VFLIPR {
bits: bool,
}
impl VFLIPR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct RSVD1R {
bits: u16,
}
impl RSVD1R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u16 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct ROT_POSR {
bits: bool,
}
impl ROT_POSR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `BLOCK_SIZE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BLOCK_SIZER {
#[doc = "Process 8x8 pixel blocks."]
_8X8,
#[doc = "Process 16x16 pixel blocks."]
_16X16,
}
impl BLOCK_SIZER {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
BLOCK_SIZER::_8X8 => false,
BLOCK_SIZER::_16X16 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> BLOCK_SIZER {
match value {
false => BLOCK_SIZER::_8X8,
true => BLOCK_SIZER::_16X16,
}
}
#[doc = "Checks if the value of the field is `_8X8`"]
#[inline]
pub fn is_8x8(&self) -> bool {
*self == BLOCK_SIZER::_8X8
}
#[doc = "Checks if the value of the field is `_16X16`"]
#[inline]
pub fn is_16x16(&self) -> bool {
*self == BLOCK_SIZER::_16X16
}
}
#[doc = r" Value of the field"]
pub struct RSVD3R {
bits: u8,
}
impl RSVD3R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct EN_REPEATR {
bits: bool,
}
impl EN_REPEATR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct RSVD4R {
bits: bool,
}
impl RSVD4R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CLKGATER {
bits: bool,
}
impl CLKGATER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct SFTRSTR {
bits: bool,
}
impl SFTRSTR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Proxy"]
pub struct _ENABLEW<'a> {
w: &'a mut W,
}
impl<'a> _ENABLEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _IRQ_ENABLEW<'a> {
w: &'a mut W,
}
impl<'a> _IRQ_ENABLEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _NEXT_IRQ_ENABLEW<'a> {
w: &'a mut W,
}
impl<'a> _NEXT_IRQ_ENABLEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ENABLE_LCD_HANDSHAKEW<'a> {
w: &'a mut W,
}
impl<'a> _ENABLE_LCD_HANDSHAKEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `ROTATE`"]
pub enum ROTATEW {
#[doc = "ROT_0"]
ROT_0,
#[doc = "ROT_90"]
ROT_90,
#[doc = "ROT_180"]
ROT_180,
#[doc = "ROT_270"]
ROT_270,
}
impl ROTATEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
ROTATEW::ROT_0 => 0,
ROTATEW::ROT_90 => 1,
ROTATEW::ROT_180 => 2,
ROTATEW::ROT_270 => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _ROTATEW<'a> {
w: &'a mut W,
}
impl<'a> _ROTATEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: ROTATEW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "ROT_0"]
#[inline]
pub fn rot_0(self) -> &'a mut W {
self.variant(ROTATEW::ROT_0)
}
#[doc = "ROT_90"]
#[inline]
pub fn rot_90(self) -> &'a mut W {
self.variant(ROTATEW::ROT_90)
}
#[doc = "ROT_180"]
#[inline]
pub fn rot_180(self) -> &'a mut W {
self.variant(ROTATEW::ROT_180)
}
#[doc = "ROT_270"]
#[inline]
pub fn rot_270(self) -> &'a mut W {
self.variant(ROTATEW::ROT_270)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _HFLIPW<'a> {
w: &'a mut W,
}
impl<'a> _HFLIPW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _VFLIPW<'a> {
w: &'a mut W,
}
impl<'a> _VFLIPW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ROT_POSW<'a> {
w: &'a mut W,
}
impl<'a> _ROT_POSW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 22;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `BLOCK_SIZE`"]
pub enum BLOCK_SIZEW {
#[doc = "Process 8x8 pixel blocks."]
_8X8,
#[doc = "Process 16x16 pixel blocks."]
_16X16,
}
impl BLOCK_SIZEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
BLOCK_SIZEW::_8X8 => false,
BLOCK_SIZEW::_16X16 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _BLOCK_SIZEW<'a> {
w: &'a mut W,
}
impl<'a> _BLOCK_SIZEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: BLOCK_SIZEW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Process 8x8 pixel blocks."]
#[inline]
pub fn _8x8(self) -> &'a mut W {
self.variant(BLOCK_SIZEW::_8X8)
}
#[doc = "Process 16x16 pixel blocks."]
#[inline]
pub fn _16x16(self) -> &'a mut W {
self.variant(BLOCK_SIZEW::_16X16)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 23;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _EN_REPEATW<'a> {
w: &'a mut W,
}
impl<'a> _EN_REPEATW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 28;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CLKGATEW<'a> {
w: &'a mut W,
}
impl<'a> _CLKGATEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 30;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SFTRSTW<'a> {
w: &'a mut W,
}
impl<'a> _SFTRSTW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 31;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Enables PXP operation with specified parameters"]
#[inline]
pub fn enable(&self) -> ENABLER {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ENABLER { bits }
}
#[doc = "Bit 1 - Interrupt enable"]
#[inline]
pub fn irq_enable(&self) -> IRQ_ENABLER {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
};
IRQ_ENABLER { bits }
}
#[doc = "Bit 2 - Next command interrupt enable"]
#[inline]
pub fn next_irq_enable(&self) -> NEXT_IRQ_ENABLER {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
};
NEXT_IRQ_ENABLER { bits }
}
#[doc = "Bit 4 - Enable handshake with LCD controller"]
#[inline]
pub fn enable_lcd_handshake(&self) -> ENABLE_LCD_HANDSHAKER {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ENABLE_LCD_HANDSHAKER { bits }
}
#[doc = "Bits 5:7 - Reserved, always set to zero."]
#[inline]
pub fn rsvd0(&self) -> RSVD0R {
let bits = {
const MASK: u8 = 7;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) as u8
};
RSVD0R { bits }
}
#[doc = "Bits 8:9 - Indicates the clockwise rotation to be applied at the output buffer"]
#[inline]
pub fn rotate(&self) -> ROTATER {
ROTATER::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 10 - Indicates that the output buffer should be flipped horizontally (effect applied before rotation)."]
#[inline]
pub fn hflip(&self) -> HFLIPR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) != 0
};
HFLIPR { bits }
}
#[doc = "Bit 11 - Indicates that the output buffer should be flipped vertically (effect applied before rotation)."]
#[inline]
pub fn vflip(&self) -> VFLIPR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
};
VFLIPR { bits }
}
#[doc = "Bits 12:21 - Reserved, always set to zero."]
#[inline]
pub fn rsvd1(&self) -> RSVD1R {
let bits = {
const MASK: u16 = 1023;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) as u16
};
RSVD1R { bits }
}
#[doc = "Bit 22 - This bit controls where rotation will occur in the PXP datapath"]
#[inline]
pub fn rot_pos(&self) -> ROT_POSR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 22;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ROT_POSR { bits }
}
#[doc = "Bit 23 - Select the block size to process."]
#[inline]
pub fn block_size(&self) -> BLOCK_SIZER {
BLOCK_SIZER::_from({
const MASK: bool = true;
const OFFSET: u8 = 23;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 24:27 - Reserved, always set to zero."]
#[inline]
pub fn rsvd3(&self) -> RSVD3R {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 24;
((self.bits >> OFFSET) & MASK as u32) as u8
};
RSVD3R { bits }
}
#[doc = "Bit 28 - Enable the PXP to run continuously"]
#[inline]
pub fn en_repeat(&self) -> EN_REPEATR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) != 0
};
EN_REPEATR { bits }
}
#[doc = "Bit 29 - Reserved, always set to zero."]
#[inline]
pub fn rsvd4(&self) -> RSVD4R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 29;
((self.bits >> OFFSET) & MASK as u32) != 0
};
RSVD4R { bits }
}
#[doc = "Bit 30 - This bit must be set to zero for normal operation"]
#[inline]
pub fn clkgate(&self) -> CLKGATER {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 30;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CLKGATER { bits }
}
#[doc = "Bit 31 - Set this bit to zero to enable normal PXP operation"]
#[inline]
pub fn sftrst(&self) -> SFTRSTR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 31;
((self.bits >> OFFSET) & MASK as u32) != 0
};
SFTRSTR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 3221225472 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Enables PXP operation with specified parameters"]
#[inline]
pub fn enable(&mut self) -> _ENABLEW {
_ENABLEW { w: self }
}
#[doc = "Bit 1 - Interrupt enable"]
#[inline]
pub fn irq_enable(&mut self) -> _IRQ_ENABLEW {
_IRQ_ENABLEW { w: self }
}
#[doc = "Bit 2 - Next command interrupt enable"]
#[inline]
pub fn next_irq_enable(&mut self) -> _NEXT_IRQ_ENABLEW {
_NEXT_IRQ_ENABLEW { w: self }
}
#[doc = "Bit 4 - Enable handshake with LCD controller"]
#[inline]
pub fn enable_lcd_handshake(&mut self) -> _ENABLE_LCD_HANDSHAKEW {
_ENABLE_LCD_HANDSHAKEW { w: self }
}
#[doc = "Bits 8:9 - Indicates the clockwise rotation to be applied at the output buffer"]
#[inline]
pub fn rotate(&mut self) -> _ROTATEW {
_ROTATEW { w: self }
}
#[doc = "Bit 10 - Indicates that the output buffer should be flipped horizontally (effect applied before rotation)."]
#[inline]
pub fn hflip(&mut self) -> _HFLIPW {
_HFLIPW { w: self }
}
#[doc = "Bit 11 - Indicates that the output buffer should be flipped vertically (effect applied before rotation)."]
#[inline]
pub fn vflip(&mut self) -> _VFLIPW {
_VFLIPW { w: self }
}
#[doc = "Bit 22 - This bit controls where rotation will occur in the PXP datapath"]
#[inline]
pub fn rot_pos(&mut self) -> _ROT_POSW {
_ROT_POSW { w: self }
}
#[doc = "Bit 23 - Select the block size to process."]
#[inline]
pub fn block_size(&mut self) -> _BLOCK_SIZEW {
_BLOCK_SIZEW { w: self }
}
#[doc = "Bit 28 - Enable the PXP to run continuously"]
#[inline]
pub fn en_repeat(&mut self) -> _EN_REPEATW {
_EN_REPEATW { w: self }
}
#[doc = "Bit 30 - This bit must be set to zero for normal operation"]
#[inline]
pub fn clkgate(&mut self) -> _CLKGATEW {
_CLKGATEW { w: self }
}
#[doc = "Bit 31 - Set this bit to zero to enable normal PXP operation"]
#[inline]
pub fn sftrst(&mut self) -> _SFTRSTW {
_SFTRSTW { w: self }
}
}
| true
|
4f8f91f6272df6244e22b2ebd623bbb9e282f89c
|
Rust
|
zTgx/rippled-rs
|
/src/crypto/key_type.rs
|
UTF-8
| 503
| 3.171875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use serde_json::{Value};
#[derive(Debug)]
pub enum KeyType {
Secp256k1 = 0,
Ed25519 = 1,
}
pub fn key_type_from_value (s: &Value) -> Option<KeyType> {
let mut ret = None;
if let Some(x) = s.as_str() {
match x {
"Secp256k1" => {
ret = Some( KeyType::Secp256k1 );
},
"Ed25519" => {
ret = Some( KeyType::Ed25519 );
},
&_ => {
}
}
}
ret
}
| true
|
730d7f75b45cf45542e1b465e7628f5c9776c802
|
Rust
|
danielschemmel/ralik
|
/ralik/src/value/display.rs
|
UTF-8
| 4,064
| 2.921875
| 3
|
[] |
no_license
|
use std::fmt;
use crate::types::{TypeKind, Variant};
use super::{Data, Value};
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.r#type.kind() {
TypeKind::Bool => match &self.data {
Data::Bool(value) => value.fmt(f),
_ => panic!("Invalid bool representation"),
},
TypeKind::Integer => match &self.data {
Data::Integer(value) => value.fmt(f),
_ => panic!("Invalid integer representation"),
},
TypeKind::Char => match &self.data {
Data::Char(value) => {
write!(f, "'")?;
value.escape_debug().fmt(f)?;
write!(f, "'")
}
_ => panic!("Invalid char representation"),
},
TypeKind::String => match &self.data {
Data::String(value) => {
write!(f, "'")?;
value.escape_debug().fmt(f)?;
write!(f, "'")
}
_ => panic!("Invalid char representation"),
},
TypeKind::Tuple => match &self.data {
Data::Empty => write!(f, "()"),
Data::Array(value) => {
assert!(value.len() > 0);
write!(f, "(")?;
for (i, element) in value.iter().enumerate() {
if i > 0 {
write!(f, ", {}", element)?;
} else {
write!(f, "{}", element)?;
}
}
if value.len() == 1 {
write!(f, ", )")
} else {
write!(f, ")")
}
}
_ => panic!("Invalid tuple representation"),
},
TypeKind::UnitStruct => match &self.data {
Data::Empty => write!(f, "{}", self.r#type.name()),
_ => panic!("Invalid unit struct representation"),
},
TypeKind::TupleStruct => {
write!(f, "{}", self.r#type.name())?;
match &self.data {
Data::Empty => write!(f, "()"),
Data::Array(value) => {
assert!(value.len() > 0);
write!(f, "(")?;
for (i, element) in value.iter().enumerate() {
if i > 0 {
write!(f, ", {}", element)?;
} else {
write!(f, "{}", element)?;
}
}
write!(f, ")")
}
_ => panic!("Invalid tuple struct representation"),
}
}
TypeKind::Struct => {
write!(f, "{} {{", self.r#type.name())?;
match &self.data {
Data::Empty => {}
Data::Array(value) => {
for (i, (name, id)) in self.r#type.fields().0.iter().enumerate() {
if i > 0 {
write!(f, ", {}: {}", name, value[*id])?;
} else {
write!(f, " {}: {}", name, value[*id])?;
}
}
}
_ => panic!("Invalid struct representation"),
}
write!(f, " }}")
}
TypeKind::Enum => {
write!(f, "{}::", self.r#type.name())?;
match &self.data {
Data::UnitVariant(id) => match &self.r#type.variants().1[*id] {
Variant::Unit(name) => write!(f, "{}", name),
Variant::Tuple(name, _field_types) => write!(f, "{}()", name),
Variant::Struct(name, _field_names, _field_types) => write!(f, "{} {{ }}", name),
},
Data::Variant(id, value) => match &self.r#type.variants().1[*id] {
Variant::Unit(name) => write!(f, "{}", name),
Variant::Tuple(name, _field_types) => {
write!(f, "{}(", name)?;
for (i, element) in value.iter().enumerate() {
if i > 0 {
write!(f, ", {}", element)?;
} else {
write!(f, "{}", element)?;
}
}
write!(f, ")")
}
Variant::Struct(name, field_names, _field_types) => {
write!(f, "{} {{ ", name)?;
for (i, (name, id)) in field_names.iter().enumerate() {
if i > 0 {
write!(f, ", {}: {}", name, value[*id])?;
} else {
write!(f, " {}: {}", name, value[*id])?;
}
}
write!(f, " }}")
}
},
_ => panic!("Invalid enum representation"),
}
}
TypeKind::Array => match &self.data {
Data::Empty => write!(f, "[]"),
Data::Array(value) => {
write!(f, "[")?;
for (i, element) in value.iter().enumerate() {
if i > 0 {
write!(f, ", {}", element)?;
} else {
write!(f, "{}", element)?;
}
}
write!(f, "]")
}
_ => panic!("Invalid array representation"),
},
}
}
}
| true
|
d0501904ce97352cb789fa2482332d7ed11cf340
|
Rust
|
feadoor/rustdoku
|
/src/strategies/hidden_single.rs
|
UTF-8
| 2,074
| 3.40625
| 3
|
[] |
no_license
|
//! A definition of the hidden single strategy.
use grid::{Grid, GridSize};
use strategies::{Deduction, Step};
use utils::GeneratorAdapter;
/// Find the hidden singles that appear in the grid.
///
/// A hidden single is when a given region has only one spot for a particular value. Then that
/// value can be placed in that location.
pub fn find<'a, T: GridSize>(grid: &'a Grid<T>) -> impl Iterator<Item = Step<T>> + 'a {
GeneratorAdapter::of(move || {
// Scan each region, and check if any value has only one position.
for region in grid.all_regions() {
for val in grid.values_missing_from_region(region).iter() {
let cells = grid.cells_with_candidate_in_region(val, region);
// There might be no place for this value, which is a contradiction. Check.
if cells.len() == 0 {
yield Step::NoPlaceForCandidateInRegion { region: region.clone(), value: val};
}
// Otherwise check for a hidden single deduction.
if cells.len() == 1 {
let cell_idx = cells.first().unwrap();
yield Step::HiddenSingle { region: region.clone(), cell: cell_idx, value: val };
}
}
}
})
}
/// Get the deductions arising from the hidden single on the given grid.
pub fn get_deductions<T: GridSize>(_grid: &Grid<T>, hidden_single: &Step<T>) -> Vec<Deduction> {
match hidden_single {
Step::HiddenSingle { cell, value, .. } => vec![ Deduction::Placement(*cell, *value) ],
_ => unreachable!(),
}
}
/// Get a concise description of this step, to be used in a description of a solution path.
pub fn get_description<T: GridSize>(grid: &Grid<T>, hidden_single: &Step<T>) -> String {
match hidden_single {
Step::HiddenSingle { region, cell, value } => format!(
"Hidden Single - {} is the only place for {} in {}",
grid.cell_name(*cell), value, grid.region_name(region),
),
_ => unreachable!(),
}
}
| true
|
7b14e3b9531ee7f8810ca5de2a3e443fb6078ed7
|
Rust
|
betabandido/rest-api-perf
|
/rust/rocket-rest-api/src/main.rs
|
UTF-8
| 916
| 2.578125
| 3
|
[] |
no_license
|
#![feature(proc_macro_hygiene, decl_macro)]
extern crate parking_lot;
#[macro_use]
extern crate rocket;
extern crate rest_api_common;
use parking_lot::RwLock;
use rocket::State;
use rocket_contrib::json::Json;
use rest_api_common::{make_value_repository, Value, ValueRepository};
#[get("/values/<key>")]
fn get_value(key: String, app: State<App>) -> Option<Json<Value>> {
let repo = &app.repo.read();
match repo.get(key) {
Ok(value) => Some(Json(value)),
Err(_) => None
}
}
#[put("/values", data = "<value>")]
fn put_value(value: Json<Value>, app: State<App>) {
let repo = &mut app.repo.write();
repo.put(value.0);
}
struct App {
repo: RwLock<Box<dyn ValueRepository>>
}
fn main() {
let repo = make_value_repository();
rocket::ignite()
.mount("/api", routes![get_value, put_value])
.manage(App { repo: RwLock::new(repo) })
.launch();
}
| true
|
74c19d4b27739a4e6696519a789be05d9ba61746
|
Rust
|
aatxe/dnd
|
/src/data/game.rs
|
UTF-8
| 2,408
| 3.171875
| 3
|
[] |
no_license
|
use std::collections::HashMap;
use std::io::Result;
use std::io::prelude::*;
use data::player::Player;
use data::{BotResult, as_io};
use data::BotError::PasswordIncorrect;
use openssl::crypto::hash::{Type, Hasher};
use rand::thread_rng;
use rand::distributions::{IndependentSample, Range};
use rustc_serialize::hex::ToHex;
pub struct Game {
pub name: String,
pub dm_nick: String,
pub users: HashMap<String, Player>,
}
impl Game {
pub fn new(name: &str, dm_nick: &str) -> Game {
Game {
name: name.to_string(),
dm_nick: dm_nick.to_string(),
users: HashMap::new(),
}
}
pub fn login(&mut self, account: Player, nickname: &str, password: &str) -> BotResult<&str> {
if account.password == try!(as_io(Game::password_hash(password))) {
self.users.insert(nickname.to_string(), account);
Ok("Login successful.")
} else {
Err(PasswordIncorrect)
}
}
pub fn password_hash(password: &str) -> Result<String> {
let mut hasher = Hasher::new(Type::SHA512);
try!(hasher.write_all(password.as_bytes()));
Ok(hasher.finish().to_hex())
}
pub fn roll() -> u8 {
let d20 = Range::new(1i8, 21i8);
let mut rng = thread_rng();
match d20.ind_sample(&mut rng) as u8 {
0 => 1,
n => n,
}
}
pub fn is_dm(&self, nickname: &str) -> bool {
&self.dm_nick == nickname
}
}
#[cfg(test)]
mod test {
use super::Game;
use data::player::Player;
#[test]
fn password_hash() {
let s = "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84\
f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff".to_string();
let h = Game::password_hash("test").unwrap();
assert_eq!(h, s);
}
#[test]
fn worldless_roll() {
for _ in 0..1000 {
let r = Game::roll();
assert!(r >= 1 && r <= 20);
}
}
#[test]
fn login() {
let p = Player::create("test", "test", 20, 30, 12, 12, 12, 12, 12, 12).unwrap();
p.save().unwrap();
let mut g = Game::new("test", "test");
g.login(p, "test", "test").unwrap();
}
#[test]
fn is_dm() {
let g = Game::new("Dungeons and Tests", "test");
assert!(g.is_dm("test"));
assert!(!g.is_dm("test2"));
}
}
| true
|
3554e8c2e499f22b19aebd16be806b77a0e9da42
|
Rust
|
pcein/trust-rust
|
/code/hello-led/a18.rs
|
UTF-8
| 172
| 2.84375
| 3
|
[] |
no_license
|
fn main() {
let v = vec![1,2,3,4,5,6];
v.iter().for_each(|x| { println!("{}", x); });
}
// Try running "rustfmt" on this file to format it in
// a better way!
| true
|
aeb86142a94a658a75844dd00b132d121a834a4c
|
Rust
|
davefollett/advent-of-code
|
/2021/src/day_02/mod.rs
|
UTF-8
| 2,534
| 3.796875
| 4
|
[] |
no_license
|
use std::fs::File;
use std::io::{BufRead, BufReader};
enum Direction {
Up(i32),
Down(i32),
Forward(i32)
}
struct Position {
depth: i32,
horizontal: i32,
aim: i32,
}
impl Position {
fn update(&mut self, delta: &Direction, part_01: bool) {
if part_01 {
match delta {
Direction::Up(value) => self.depth -= value,
Direction::Down(value) => self.depth += value,
Direction::Forward(value) => self.horizontal += value
}
} else {
match delta {
Direction::Up(value) => self.aim -= value,
Direction::Down(value) => self.aim += value,
Direction::Forward(value) => {
self.horizontal += value;
if self.aim != 0 { self.depth += self.aim * value; }
}
}
}
}
fn final_calculation(&self) -> i32 {
self.depth * self.horizontal
}
}
fn read_file(filename: &str) -> Vec<Direction> {
let mut directions: Vec<Direction> = Vec::new();
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line.unwrap();
let mut iter = line.split_whitespace();
let direction = iter.next().unwrap();
let amount = iter.next().unwrap().parse::<i32>().unwrap();
directions.push(
match direction {
"up" => Direction::Up(amount),
"down" => Direction::Down(amount),
"forward" => Direction::Forward(amount),
_ => unreachable!()
}
)
}
return directions;
}
pub fn run(filename: &str) {
let directions = read_file(filename);
part_01(&directions);
part_02(&directions);
}
fn part_01(directions: &Vec<Direction>) {
let mut sub_position = Position {
depth: 0,
horizontal: 0,
aim: 0,
};
for direction in directions.iter() {
sub_position.update(direction, true);
}
println!("day 02 part 01: {}", sub_position.final_calculation());
// day 02 part 01: 2027977
}
fn part_02(directions: &Vec<Direction>) {
let mut sub_position = Position {
depth: 0,
horizontal: 0,
aim: 0,
};
for direction in directions.iter() {
sub_position.update(direction, false);
}
println!("day 02 part 02: {}", sub_position.final_calculation());
// day 02 part 02: 1903644897
}
| true
|
b0c5824fe96fef350b1c36c13b4c15e7499d353f
|
Rust
|
handcraftsman/Genetic
|
/tests/lib_duplicate_string_tests.rs
|
UTF-8
| 1,379
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
extern crate genetic;
extern crate time;
#[cfg(test)]
mod tests {
use time::PreciseTime;
use genetic::*;
#[test]
fn test_duplicate_string() {
let start = PreciseTime::now();
let gene_set = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!.";
let target = "Not all those who wander are lost.";
let wrapped_display = |candidate: &genetic::Individual| {display_duplicate_string(&candidate, start);};
let wrapped_get_fitness = |candidate: &String| -> usize {get_duplicate_string_fitness(&candidate, target)};
let best = genetic::get_best(wrapped_get_fitness, wrapped_display, target.len(), target.len(), gene_set);
display_duplicate_string(&best, start);
println!("Total time: {}", start.to(PreciseTime::now()));
assert_eq!(best.genes, target);
}
fn display_duplicate_string(candidate: &genetic::Individual, start: PreciseTime) {
let now = PreciseTime::now();
let elapsed = start.to(now);
println!("{}\t{}\t{}", candidate.genes, candidate.fitness, elapsed);
}
fn get_duplicate_string_fitness(candidate: &String, target: &str) -> usize {
let different_count = target.chars()
.zip(candidate.chars())
.filter(|&(a, b)| a != b)
.count();
target.len() - different_count
}
}
| true
|
a2d1de0794a2aba130866f460e1c22fa6bb1172b
|
Rust
|
hdelva/preprocess_routable_tiles
|
/src/entities/segment.rs
|
UTF-8
| 471
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
#[derive(Debug)]
pub struct Segment<'a> {
pub from: &'a str,
pub to: &'a str,
}
#[derive(Debug)]
pub struct WeightedSegment<'a> {
pub segment: Segment<'a>,
pub weight: u64,
}
impl<'a> Segment<'a> {
pub fn new(from: &'a str, to: &'a str) -> Segment<'a> {
Segment { from, to }
}
}
impl<'a> WeightedSegment<'a> {
pub fn new(segment: Segment<'a>, weight: u64) -> WeightedSegment<'a> {
WeightedSegment { segment, weight }
}
}
| true
|
a3dbcf09b031227d712efb41a1e8bba6ba8e6544
|
Rust
|
marco-c/gecko-dev-wordified
|
/third_party/rust/ringbuf/src/ring_buffer.rs
|
UTF-8
| 4,819
| 2.78125
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use
crate
:
:
{
consumer
:
:
Consumer
producer
:
:
Producer
}
;
use
alloc
:
:
{
sync
:
:
Arc
vec
:
:
Vec
}
;
use
cache_padded
:
:
CachePadded
;
use
core
:
:
{
cell
:
:
UnsafeCell
cmp
:
:
min
mem
:
:
MaybeUninit
ptr
:
:
{
self
copy
}
sync
:
:
atomic
:
:
{
AtomicUsize
Ordering
}
}
;
pub
(
crate
)
struct
SharedVec
<
T
:
Sized
>
{
cell
:
UnsafeCell
<
Vec
<
T
>
>
len
:
usize
}
unsafe
impl
<
T
:
Sized
>
Sync
for
SharedVec
<
T
>
{
}
impl
<
T
:
Sized
>
SharedVec
<
T
>
{
pub
fn
new
(
data
:
Vec
<
T
>
)
-
>
Self
{
Self
{
len
:
data
.
len
(
)
cell
:
UnsafeCell
:
:
new
(
data
)
}
}
pub
fn
len
(
&
self
)
-
>
usize
{
self
.
len
}
pub
unsafe
fn
get_ref
(
&
self
)
-
>
&
Vec
<
T
>
{
&
*
self
.
cell
.
get
(
)
}
#
[
allow
(
clippy
:
:
mut_from_ref
)
]
pub
unsafe
fn
get_mut
(
&
self
)
-
>
&
mut
Vec
<
T
>
{
&
mut
*
self
.
cell
.
get
(
)
}
}
/
/
/
Ring
buffer
itself
.
pub
struct
RingBuffer
<
T
:
Sized
>
{
pub
(
crate
)
data
:
SharedVec
<
MaybeUninit
<
T
>
>
pub
(
crate
)
head
:
CachePadded
<
AtomicUsize
>
pub
(
crate
)
tail
:
CachePadded
<
AtomicUsize
>
}
impl
<
T
:
Sized
>
RingBuffer
<
T
>
{
/
/
/
Creates
a
new
instance
of
a
ring
buffer
.
pub
fn
new
(
capacity
:
usize
)
-
>
Self
{
let
mut
data
=
Vec
:
:
new
(
)
;
data
.
resize_with
(
capacity
+
1
MaybeUninit
:
:
uninit
)
;
Self
{
data
:
SharedVec
:
:
new
(
data
)
head
:
CachePadded
:
:
new
(
AtomicUsize
:
:
new
(
0
)
)
tail
:
CachePadded
:
:
new
(
AtomicUsize
:
:
new
(
0
)
)
}
}
/
/
/
Splits
ring
buffer
into
producer
and
consumer
.
pub
fn
split
(
self
)
-
>
(
Producer
<
T
>
Consumer
<
T
>
)
{
let
arc
=
Arc
:
:
new
(
self
)
;
(
Producer
{
rb
:
arc
.
clone
(
)
}
Consumer
{
rb
:
arc
}
)
}
/
/
/
Returns
capacity
of
the
ring
buffer
.
pub
fn
capacity
(
&
self
)
-
>
usize
{
self
.
data
.
len
(
)
-
1
}
/
/
/
Checks
if
the
ring
buffer
is
empty
.
pub
fn
is_empty
(
&
self
)
-
>
bool
{
let
head
=
self
.
head
.
load
(
Ordering
:
:
Acquire
)
;
let
tail
=
self
.
tail
.
load
(
Ordering
:
:
Acquire
)
;
head
=
=
tail
}
/
/
/
Checks
if
the
ring
buffer
is
full
.
pub
fn
is_full
(
&
self
)
-
>
bool
{
let
head
=
self
.
head
.
load
(
Ordering
:
:
Acquire
)
;
let
tail
=
self
.
tail
.
load
(
Ordering
:
:
Acquire
)
;
(
tail
+
1
)
%
self
.
data
.
len
(
)
=
=
head
}
/
/
/
The
length
of
the
data
in
the
buffer
.
pub
fn
len
(
&
self
)
-
>
usize
{
let
head
=
self
.
head
.
load
(
Ordering
:
:
Acquire
)
;
let
tail
=
self
.
tail
.
load
(
Ordering
:
:
Acquire
)
;
(
tail
+
self
.
data
.
len
(
)
-
head
)
%
self
.
data
.
len
(
)
}
/
/
/
The
remaining
space
in
the
buffer
.
pub
fn
remaining
(
&
self
)
-
>
usize
{
self
.
capacity
(
)
-
self
.
len
(
)
}
}
impl
<
T
:
Sized
>
Drop
for
RingBuffer
<
T
>
{
fn
drop
(
&
mut
self
)
{
let
data
=
unsafe
{
self
.
data
.
get_mut
(
)
}
;
let
head
=
self
.
head
.
load
(
Ordering
:
:
Acquire
)
;
let
tail
=
self
.
tail
.
load
(
Ordering
:
:
Acquire
)
;
let
len
=
data
.
len
(
)
;
let
slices
=
if
head
<
=
tail
{
(
head
.
.
tail
0
.
.
0
)
}
else
{
(
head
.
.
len
0
.
.
tail
)
}
;
let
drop
=
|
elem_ref
:
&
mut
MaybeUninit
<
T
>
|
unsafe
{
elem_ref
.
as_ptr
(
)
.
read
(
)
;
}
;
for
elem
in
data
[
slices
.
0
]
.
iter_mut
(
)
{
drop
(
elem
)
;
}
for
elem
in
data
[
slices
.
1
]
.
iter_mut
(
)
{
drop
(
elem
)
;
}
}
}
struct
SlicePtr
<
T
:
Sized
>
{
pub
ptr
:
*
mut
T
pub
len
:
usize
}
impl
<
T
>
SlicePtr
<
T
>
{
fn
null
(
)
-
>
Self
{
Self
{
ptr
:
ptr
:
:
null_mut
(
)
len
:
0
}
}
fn
new
(
slice
:
&
mut
[
T
]
)
-
>
Self
{
Self
{
ptr
:
slice
.
as_mut_ptr
(
)
len
:
slice
.
len
(
)
}
}
unsafe
fn
shift
(
&
mut
self
count
:
usize
)
{
self
.
ptr
=
self
.
ptr
.
add
(
count
)
;
self
.
len
-
=
count
;
}
}
/
/
/
Moves
at
most
count
items
from
the
src
consumer
to
the
dst
producer
.
/
/
/
Consumer
and
producer
may
be
of
different
buffers
as
well
as
of
the
same
one
.
/
/
/
/
/
/
count
is
the
number
of
items
being
moved
if
None
-
as
much
as
possible
items
will
be
moved
.
/
/
/
/
/
/
Returns
number
of
items
been
moved
.
pub
fn
move_items
<
T
>
(
src
:
&
mut
Consumer
<
T
>
dst
:
&
mut
Producer
<
T
>
count
:
Option
<
usize
>
)
-
>
usize
{
unsafe
{
src
.
pop_access
(
|
src_left
src_right
|
-
>
usize
{
dst
.
push_access
(
|
dst_left
dst_right
|
-
>
usize
{
let
n
=
count
.
unwrap_or_else
(
|
|
{
min
(
src_left
.
len
(
)
+
src_right
.
len
(
)
dst_left
.
len
(
)
+
dst_right
.
len
(
)
)
}
)
;
let
mut
m
=
0
;
let
mut
src
=
(
SlicePtr
:
:
new
(
src_left
)
SlicePtr
:
:
new
(
src_right
)
)
;
let
mut
dst
=
(
SlicePtr
:
:
new
(
dst_left
)
SlicePtr
:
:
new
(
dst_right
)
)
;
loop
{
let
k
=
min
(
n
-
m
min
(
src
.
0
.
len
dst
.
0
.
len
)
)
;
if
k
=
=
0
{
break
;
}
copy
(
src
.
0
.
ptr
dst
.
0
.
ptr
k
)
;
if
src
.
0
.
len
=
=
k
{
src
.
0
=
src
.
1
;
src
.
1
=
SlicePtr
:
:
null
(
)
;
}
else
{
src
.
0
.
shift
(
k
)
;
}
if
dst
.
0
.
len
=
=
k
{
dst
.
0
=
dst
.
1
;
dst
.
1
=
SlicePtr
:
:
null
(
)
;
}
else
{
dst
.
0
.
shift
(
k
)
;
}
m
+
=
k
}
m
}
)
}
)
}
}
| true
|
97002b87fa2f31dbbfa86b73ea1af41ec6d6ef56
|
Rust
|
veer66/linq-rust
|
/src/lib.rs
|
UTF-8
| 1,124
| 2.984375
| 3
|
[] |
no_license
|
macro_rules! query {
(select $select_expr:expr; from $data_source:ident;) => {
$data_source.map($select_expr)
};
(select $select_expr:expr; from $data_source:ident; where $where_expr:expr;) => {
$data_source.filter($where_expr).map($select_expr)
};
}
#[cfg(test)]
mod tests {
#[test]
fn select_query() {
let x = 1..100;
let y: Vec<_> = x.clone().map(|i| i * 2).collect();
let z: Vec<_> = query!(select |i| i * 2; from x;).collect();
assert_eq!(z, y);
}
#[test]
fn where_query() {
let x = 1..100;
let y: Vec<_> = x.clone().filter(|&i| i % 2 == 0).map(|i| i * 2).collect();
let z: Vec<_> = query!(select |i| i * 2; from x; where |i| i % 2 == 0;).collect();
assert_eq!(z, y);
}
#[test]
fn multiple_conditions_in_where_query() {
let x = 1..100;
let y: Vec<_> = x.clone().filter(|&i| i % 2 == 0 && i % 4 == 0).map(|i| i * 2).collect();
let z: Vec<_> = query!(select |i| i * 2; from x; where |i| i % 2 == 0 && i % 4 == 0;).collect();
assert_eq!(z, y);
}
}
| true
|
4f1ccebefdb5ab89464dd4b8ea882d4dd2420b50
|
Rust
|
AriYoung00/Rust-RSA
|
/rsa_vis/src/rsa.rs
|
UTF-8
| 7,875
| 3.1875
| 3
|
[] |
no_license
|
use num::{BigUint, BigInt, ToPrimitive, FromPrimitive};
use num::traits::{One, Zero};
use crate::rand;
use crate::primes;
use crate::num::bigint::ToBigInt;
const KEY_SIZE: usize = 1024;
const BLOCK_SIZE: usize = 4; // Block size in increments of 8 bytes
/// Return greatest common divisor of elements a and b as a BigUint
fn _gcd(a: BigUint, b: BigUint) -> BigUint {
return if b == Zero::zero() {
a.clone()
} else {
_gcd(b.clone(), a % b.clone())
}
}
/// Return modular multiplicative inverse of a and m as a BigUint
fn _modular_multiplicative_inverse(mut a: BigUint, mut m: BigUint) -> BigUint {
// This code adapted from GeeksForGeeks: https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
let mut a = a.to_bigint().unwrap();
let mut m = m.to_bigint().unwrap();
let mut m0 = m.clone();
let mut y: BigInt = BigInt::zero();
let mut x: BigInt = BigInt::one();
if m == x {
return y.to_biguint().unwrap();
}
while a > BigInt::one() {
let mut q: BigInt = a.clone() / m.clone();
let mut t: BigInt = m.clone();
// m is remainder now, process same as Euclid's algo
m = a % m;
a = t;
t = y.clone();
y = x - q * y.clone();
x = t;
}
// Make x positive if needed
if x < BigInt::zero() {
x = x + m0;
}
return x.to_biguint().unwrap();
}
fn _gen_key(num_prime_bits: usize) -> ((BigUint, BigUint), BigUint) {
// Algorithm adapted from https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Key_generation
let mut rng = rand::new();
let one: BigUint = One::one();
let mut prime_rng = rand::new();
// 1. Choose distinct prime numbers prime_one and prime_two
let prime_one = primes::gen_large_prime(num_prime_bits, &mut prime_rng);
let mut prime_two = primes::gen_large_prime(num_prime_bits, &mut prime_rng);
while prime_one == prime_two {
prime_two = primes::gen_large_prime(num_prime_bits, &mut prime_rng);
}
// 2. Compute n = prime_one * prime_two (only needed as return val, computed below)
// n is used as the modulus for both the public and private keys.
// 3. Compute lambda_n = lcm(p-1, q-1). Note that lcm(a, b) = abs(a*b} / gcd(a, b).
// Here, prime_one > 0 and prime_two > 0, so prime_one*prime_two = abs(prime_one*prime_two)
let prod: BigUint = (prime_one.clone() - one.clone()) * (prime_two.clone() - one.clone());
let lambda_n = prod / _gcd(prime_one.clone() - one.clone(),
prime_two.clone() - one.clone());
// 4. Choose an integer e s.t. 1 < e < lambda_n, and s.t. e and lambda_n are co-prime
let mut exponent = BigUint::from_i32(65_537).unwrap();
assert!(one.clone() < exponent.clone() && exponent.clone() < lambda_n.clone());
assert_eq!(_gcd(exponent.clone(), lambda_n.clone()), One::one());
// 5. Compute d s.t. d * e ≡ 1 mod lambda_n. d is modular multiplicative inverse of e, lambda_n
// d is the private key exponent
let d: BigUint = _modular_multiplicative_inverse(exponent.clone(), lambda_n.clone());
// Return tuple of (public_key, private_key)
((&prime_one * &prime_two, exponent), d)
}
pub fn gen_key() -> ((BigUint, BigUint), BigUint) {
_gen_key(KEY_SIZE / 2)
}
/// Helper function, encrypts bytes contained in blocks using the given publickey, returns cipher as
/// a vector of `BigUint`
///
/// # Arguments
/// * `blocks` - Packed vector of `u32`. The encryption algorith is run on each block, resulting in a
/// corresponding output block in the returned vector
/// * `key` - Public key to encrypt with, tuple of the form (modulus, exponent) where both are BigUints
fn _encrypt_bytes(blocks: Vec<u32>, key: (BigUint, BigUint)) -> Vec<BigUint> {
print!("Pre-Encrypt Blocks: [ ");
for b in &blocks { print!("{:#b}, ", b); }
println!("]");
let mut output: Vec<BigUint> = vec![BigUint::from_i32(0).unwrap();
blocks.len()];
for (i, block) in blocks.iter().enumerate() {
output[i] = BigUint::from_u32(block.clone()).unwrap()
.modpow(&key.1.clone(), &key.0.clone());
}
output
}
/// Helper function, decrypts cipher blocks using the given private key and exponent, returning the decrypted
/// blocks as a vector of `u32`
///
/// # Arguments
/// * `cipher` - The cipher to decrypt, as a reference to a vector of BigUint encrypted blocks
/// * `privkey` - The private key to use when decrypting the given cipher
/// * `modulus` - The "modulus" component of the public key, also used for decryption
fn _decrypt_bytes(cipher: &Vec<BigUint>, privkey: BigUint, modulus: BigUint) -> Vec<u32> {
let mut dec_blocks = vec![0_u32; cipher.len()];
for (i, enc_block) in cipher.iter().enumerate() {
match enc_block.modpow(&privkey.clone(), &modulus.clone())
.to_u32() {
Some(thing) => dec_blocks[i] = thing,
None => {
println!("> Error: Found garbage value when attempting to decrypt. Your key is probably incorrect.");
dec_blocks[i] = 0;
}
}
}
print!("Post-Decrypt Blocks: [ ");
for b in &dec_blocks { print!("{:#b}, ", b); }
println!("]");
dec_blocks
}
/// Helper function, packs a string into a vector of `u32` (which is the return value) to pass to encryption
/// function
///
/// # Arguments
/// * `msg` - The string to pack into `Vec<u32>`
fn _pack_string(msg: &str) -> Vec<u32> {
let offset: usize = if (msg.len() % BLOCK_SIZE) == 0 { 0 } else { 1 };
let mut blocks = vec![0_u32; (msg.len() / BLOCK_SIZE) + offset];
let mut block_index = 0;
let mut block_count = 0;
for c in msg.chars() {
blocks[block_index] ^= c as u32;
block_count += 1;
if block_count == BLOCK_SIZE {
block_index += 1;
block_count = 0;
} else {
blocks[block_index] <<= 8;
}
}
blocks
}
/// Helper function, unpacks and returns a string from a vector of `u32` returned by decryption function.
///
/// # Arguments
/// * `blocks` - `Vec<u32>` to unpack characters from
fn _unpack_string(mut blocks: Vec<u32>) -> String {
let mut res: String = String::new();
for mut c in blocks.iter_mut().rev() {
let mut c = *c;
while c > 0 {
let new_char = (c & 0b11111111) as u8;
res = char::from(new_char).to_string().to_owned() + &res;
// Mask to get rid of the bytes representing the character we just pulled out of this u32
c &= 0b11111111111111111111111100000000;
c = c.overflowing_shr(8).0;
}
}
res
}
/// Encrypts string `msg` using given public key
///
/// # Arguments
/// * `msg` - String to encrypt
/// * `pubkey` - Publickey to use to encrypt `msg`, in format (modulus: `BigUint`, exponent: `BigUint')
pub fn encrypt_str(msg: &str, pubkey: (BigUint, BigUint)) -> Vec<BigUint> {
let packed_string = _pack_string(msg);
_encrypt_bytes(packed_string, pubkey)
}
/// Returns cipher decrypted and unpacked as string
///
/// # Arguments
/// * `cipher` - Vector of `BigUint` representing encrypted string
/// * `privkey` - The private key to use for decryption
/// * `modulus` - The modulus component of the public key, also used in decryption
pub fn decrypt_str(cipher: &Vec<BigUint>, privkey: BigUint, modulus: BigUint) -> String {
let dec_blocks = _decrypt_bytes(cipher, privkey, modulus);
_unpack_string(dec_blocks)
}
pub fn test_thing() {
let (pubkey, privkey) = _gen_key(KEY_SIZE / 2);
let cipher = encrypt_str(&"Hello world, how are you today?".to_string(), pubkey.clone());
let dec_result = decrypt_str(&cipher, privkey, pubkey.0);
println!("Result: {}", dec_result);
}
| true
|
c00b88522453ec6aec72cd4468d49df63450e4c7
|
Rust
|
drademacher/advent_of_code_2020
|
/src/day_02.rs
|
UTF-8
| 1,728
| 3.46875
| 3
|
[] |
no_license
|
use regex::Regex;
pub fn solve() -> String {
return format!("First part: {}\nSecond part: {}", part_one(), part_two());
}
#[derive(Debug)]
struct SingleInput {
fst_number: usize,
snd_number: usize,
character: char,
password: &'static str,
}
fn read_input_file() -> Vec<SingleInput> {
let regex = Regex::new(r"(\d+)-(\d+) (\w+): (\w+)").unwrap();
let inputs: Vec<SingleInput> = include_str!("day_02.txt")
.lines()
.map(|s| regex.captures_iter(s).next().unwrap())
.map(|cap| SingleInput {
fst_number: cap[1].parse().unwrap(),
snd_number: cap[2].parse().unwrap(),
character: cap.get(3).unwrap().as_str().chars().next().unwrap(),
password: cap.get(4).unwrap().as_str(),
})
.collect();
return inputs;
}
fn part_one() -> usize {
let inputs = read_input_file();
let mut result = 0;
for input in inputs {
let count_character = input
.password
.chars()
.filter(|&c| c == input.character)
.count();
if input.fst_number <= count_character && count_character <= input.snd_number {
result += 1;
}
}
return result;
}
fn part_two() -> usize {
let inputs = read_input_file();
let mut result = 0;
for input in inputs {
let is_first_char_matching =
input.password.chars().nth(input.fst_number - 1).unwrap() == input.character;
let is_second_char_matching =
input.password.chars().nth(input.snd_number - 1).unwrap() == input.character;
if is_first_char_matching != is_second_char_matching {
result += 1;
}
}
return result;
}
| true
|
031cad4f1a486b37e51fae32391b73acca2b7da0
|
Rust
|
Enity/sudocu-brutforce-rs
|
/src/main.rs
|
UTF-8
| 1,600
| 2.71875
| 3
|
[] |
no_license
|
#![feature(test)]
mod random;
mod sudocu;
use random::Random;
use sudocu::Sudocu;
use std::env;
const INITIAL_BACKTRACK_STEP: usize = 2;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Cannot find sudoku in args");
} else {
let mut s = Sudocu::new();
let mut r = Random::new();
s.fill(&args[1]);
brut(&mut s, &mut r);
s.print();
}
}
fn brut(s: &mut Sudocu, r: &mut Random) {
let mut i = 0;
let mut backtrack_step = INITIAL_BACKTRACK_STEP;
let mut last_backtrack_index = 100;
while i < s.map.len() {
let mut v = r.get_new().unwrap();
while !s.try_set(i, v) {
v = match r.get_new() {
Some(v) => v,
None => {
if last_backtrack_index == i {
backtrack_step += 1;
}
last_backtrack_index = i;
if i <= backtrack_step {
i = 0;
backtrack_step = INITIAL_BACKTRACK_STEP;
} else {
i -= backtrack_step
}
s.clean(i);
r.reset();
r.get_new().unwrap()
}
};
}
r.reset();
i += 1;
}
}
extern crate test;
#[bench]
fn bench_brutforce(b: &mut test::Bencher) {
let mut r = Random::new();
let mut s = Sudocu::new();
b.iter(|| {
brut(&mut s, &mut r);
s.clean(0);
})
}
| true
|
1f322b3d0971df48bd379770271feb9161a389cb
|
Rust
|
trainman419/msp430fr2433
|
/src/port_1_2/p2out/mod.rs
|
UTF-8
| 18,934
| 2.734375
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::P2OUT {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `P2OUT0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum P2OUT0R {
#[doc = r" Reserved"]
_Reserved(bool),
}
impl P2OUT0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P2OUT0R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P2OUT0R {
match value {
i => P2OUT0R::_Reserved(i),
}
}
}
#[doc = "Possible values of the field `P2OUT1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum P2OUT1R {
#[doc = r" Reserved"]
_Reserved(bool),
}
impl P2OUT1R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P2OUT1R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P2OUT1R {
match value {
i => P2OUT1R::_Reserved(i),
}
}
}
#[doc = "Possible values of the field `P2OUT2`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum P2OUT2R {
#[doc = r" Reserved"]
_Reserved(bool),
}
impl P2OUT2R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P2OUT2R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P2OUT2R {
match value {
i => P2OUT2R::_Reserved(i),
}
}
}
#[doc = "Possible values of the field `P2OUT3`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum P2OUT3R {
#[doc = r" Reserved"]
_Reserved(bool),
}
impl P2OUT3R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P2OUT3R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P2OUT3R {
match value {
i => P2OUT3R::_Reserved(i),
}
}
}
#[doc = "Possible values of the field `P2OUT4`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum P2OUT4R {
#[doc = r" Reserved"]
_Reserved(bool),
}
impl P2OUT4R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P2OUT4R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P2OUT4R {
match value {
i => P2OUT4R::_Reserved(i),
}
}
}
#[doc = "Possible values of the field `P2OUT5`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum P2OUT5R {
#[doc = r" Reserved"]
_Reserved(bool),
}
impl P2OUT5R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P2OUT5R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P2OUT5R {
match value {
i => P2OUT5R::_Reserved(i),
}
}
}
#[doc = "Possible values of the field `P2OUT6`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum P2OUT6R {
#[doc = r" Reserved"]
_Reserved(bool),
}
impl P2OUT6R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P2OUT6R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P2OUT6R {
match value {
i => P2OUT6R::_Reserved(i),
}
}
}
#[doc = "Possible values of the field `P2OUT7`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum P2OUT7R {
#[doc = r" Reserved"]
_Reserved(bool),
}
impl P2OUT7R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P2OUT7R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P2OUT7R {
match value {
i => P2OUT7R::_Reserved(i),
}
}
}
#[doc = "Values that can be written to the field `P2OUT0`"]
pub enum P2OUT0W {}
impl P2OUT0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {}
}
}
#[doc = r" Proxy"]
pub struct _P2OUT0W<'a> {
w: &'a mut W,
}
impl<'a> _P2OUT0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: P2OUT0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `P2OUT1`"]
pub enum P2OUT1W {}
impl P2OUT1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {}
}
}
#[doc = r" Proxy"]
pub struct _P2OUT1W<'a> {
w: &'a mut W,
}
impl<'a> _P2OUT1W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: P2OUT1W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `P2OUT2`"]
pub enum P2OUT2W {}
impl P2OUT2W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {}
}
}
#[doc = r" Proxy"]
pub struct _P2OUT2W<'a> {
w: &'a mut W,
}
impl<'a> _P2OUT2W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: P2OUT2W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `P2OUT3`"]
pub enum P2OUT3W {}
impl P2OUT3W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {}
}
}
#[doc = r" Proxy"]
pub struct _P2OUT3W<'a> {
w: &'a mut W,
}
impl<'a> _P2OUT3W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: P2OUT3W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `P2OUT4`"]
pub enum P2OUT4W {}
impl P2OUT4W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {}
}
}
#[doc = r" Proxy"]
pub struct _P2OUT4W<'a> {
w: &'a mut W,
}
impl<'a> _P2OUT4W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: P2OUT4W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `P2OUT5`"]
pub enum P2OUT5W {}
impl P2OUT5W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {}
}
}
#[doc = r" Proxy"]
pub struct _P2OUT5W<'a> {
w: &'a mut W,
}
impl<'a> _P2OUT5W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: P2OUT5W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `P2OUT6`"]
pub enum P2OUT6W {}
impl P2OUT6W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {}
}
}
#[doc = r" Proxy"]
pub struct _P2OUT6W<'a> {
w: &'a mut W,
}
impl<'a> _P2OUT6W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: P2OUT6W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `P2OUT7`"]
pub enum P2OUT7W {}
impl P2OUT7W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {}
}
}
#[doc = r" Proxy"]
pub struct _P2OUT7W<'a> {
w: &'a mut W,
}
impl<'a> _P2OUT7W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: P2OUT7W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
#[doc = "Bit 0 - P2OUT0"]
#[inline]
pub fn p2out0(&self) -> P2OUT0R {
P2OUT0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 1 - P2OUT1"]
#[inline]
pub fn p2out1(&self) -> P2OUT1R {
P2OUT1R::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 2 - P2OUT2"]
#[inline]
pub fn p2out2(&self) -> P2OUT2R {
P2OUT2R::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 3 - P2OUT3"]
#[inline]
pub fn p2out3(&self) -> P2OUT3R {
P2OUT3R::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 4 - P2OUT4"]
#[inline]
pub fn p2out4(&self) -> P2OUT4R {
P2OUT4R::_from({
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 5 - P2OUT5"]
#[inline]
pub fn p2out5(&self) -> P2OUT5R {
P2OUT5R::_from({
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 6 - P2OUT6"]
#[inline]
pub fn p2out6(&self) -> P2OUT6R {
P2OUT6R::_from({
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 7 - P2OUT7"]
#[inline]
pub fn p2out7(&self) -> P2OUT7R {
P2OUT7R::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub fn bits(&mut self, bits: u8) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - P2OUT0"]
#[inline]
pub fn p2out0(&mut self) -> _P2OUT0W {
_P2OUT0W { w: self }
}
#[doc = "Bit 1 - P2OUT1"]
#[inline]
pub fn p2out1(&mut self) -> _P2OUT1W {
_P2OUT1W { w: self }
}
#[doc = "Bit 2 - P2OUT2"]
#[inline]
pub fn p2out2(&mut self) -> _P2OUT2W {
_P2OUT2W { w: self }
}
#[doc = "Bit 3 - P2OUT3"]
#[inline]
pub fn p2out3(&mut self) -> _P2OUT3W {
_P2OUT3W { w: self }
}
#[doc = "Bit 4 - P2OUT4"]
#[inline]
pub fn p2out4(&mut self) -> _P2OUT4W {
_P2OUT4W { w: self }
}
#[doc = "Bit 5 - P2OUT5"]
#[inline]
pub fn p2out5(&mut self) -> _P2OUT5W {
_P2OUT5W { w: self }
}
#[doc = "Bit 6 - P2OUT6"]
#[inline]
pub fn p2out6(&mut self) -> _P2OUT6W {
_P2OUT6W { w: self }
}
#[doc = "Bit 7 - P2OUT7"]
#[inline]
pub fn p2out7(&mut self) -> _P2OUT7W {
_P2OUT7W { w: self }
}
}
| true
|
aedb1f9d8bb6c9339a0da8ec55d37750a39bae8d
|
Rust
|
intendednull/yew
|
/examples/router/src/pages/author_list.rs
|
UTF-8
| 2,642
| 2.9375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use crate::components::{author_card::AuthorCard, progress_delay::ProgressDelay};
use rand::{distributions, Rng};
use yew::prelude::*;
/// Amount of milliseconds to wait before showing the next set of authors.
const CAROUSEL_DELAY_MS: u64 = 15000;
pub enum Msg {
NextAuthors,
}
pub struct AuthorList {
link: ComponentLink<Self>,
seeds: Vec<u64>,
}
impl Component for AuthorList {
type Message = Msg;
type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
seeds: random_author_seeds(),
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::NextAuthors => {
self.seeds = random_author_seeds();
true
}
}
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
let authors = self.seeds.iter().map(|&seed| {
html! {
<div class="tile is-parent">
<div class="tile is-child">
<AuthorCard seed=seed />
</div>
</div>
}
});
html! {
<div class="container">
<section class="hero">
<div class="hero-body">
<div class="container">
<h1 class="title">{ "Authors" }</h1>
<h2 class="subtitle">
{ "Meet the definitely real people behind your favourite Yew content" }
</h2>
</div>
</div>
</section>
<p class="section py-0">
{ "It wouldn't be fair " }
<i>{ "(or possible :P)" }</i>
{" to list each and every author in alphabetical order."}
<br />
{ "So instead we chose to put more focus on the individuals by introducing you to two people at a time" }
</p>
<div class="section">
<div class="tile is-ancestor">
{ for authors }
</div>
<ProgressDelay duration_ms=CAROUSEL_DELAY_MS on_complete=self.link.callback(|_| Msg::NextAuthors) />
</div>
</div>
}
}
}
fn random_author_seeds() -> Vec<u64> {
rand::thread_rng()
.sample_iter(distributions::Standard)
.take(2)
.collect()
}
| true
|
4b9415ba34def5035a0e5877df1825c8cbcd9cde
|
Rust
|
0xflotus/grapl
|
/src/rust/graph-descriptions/src/graph.rs
|
UTF-8
| 1,961
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
use std::collections::HashMap;
use crate::graph_description::{Edge, EdgeList, GeneratedSubgraphs, Graph, Node};
use crate::node::NodeT;
impl Graph {
pub fn new(timestamp: u64) -> Self {
Graph {
nodes: HashMap::new(),
edges: HashMap::new(),
timestamp,
}
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.edges.is_empty()
}
pub fn merge(&mut self, other: &Graph) {
self.edges.extend(other.edges.clone());
for (node_key, other_node) in other.nodes.iter() {
self.nodes
.entry(node_key.clone())
.and_modify(|node| {
node.merge(other_node);
})
.or_insert_with(|| other_node.clone());
}
}
pub fn add_node<N>(&mut self, node: N)
where
N: Into<Node>,
{
let node = node.into();
let key = node.clone_node_key();
self.nodes.insert(key.to_string(), node);
self.edges
.entry(key)
.or_insert_with(|| EdgeList { edges: vec![] });
}
pub fn with_node<N>(mut self, node: N) -> Graph
where
N: Into<Node>,
{
self.add_node(node);
self
}
pub fn add_edge(
&mut self,
edge_name: impl Into<String>,
from: impl Into<String>,
to: impl Into<String>,
) {
let from = from.into();
let to = to.into();
let edge_name = edge_name.into();
let edge = Edge {
from: from.clone(),
to,
edge_name,
};
self.edges
.entry(from)
.or_insert_with(|| EdgeList {
edges: Vec::with_capacity(1),
})
.edges
.push(edge);
}
}
impl GeneratedSubgraphs {
pub fn new(subgraphs: Vec<Graph>) -> GeneratedSubgraphs {
GeneratedSubgraphs { subgraphs }
}
}
| true
|
04323cb7aeffd2e84435fc99e08753f6ef9f38b7
|
Rust
|
benblank/aoc2019-rust
|
/src/day14.rs
|
UTF-8
| 10,259
| 2.90625
| 3
|
[] |
no_license
|
use std::collections::HashMap;
use std::fs;
use std::io::BufRead;
const INPUT_PATH: &str = "day14.input.txt";
const ORE: &str = "ORE";
#[derive(Debug, PartialEq)]
struct Ingredient {
name: String,
count: u64,
}
impl Ingredient {
fn from_string(string: &str) -> Ingredient {
let parts = string.split(' ').collect::<Vec<_>>();
let count = parts[0]
.parse::<u64>()
.unwrap_or_else(|_| panic!("invalid ingredient count '{}'", parts[0]));
let name = parts[1].to_string();
Ingredient { name, count }
}
}
#[derive(Debug, PartialEq)]
struct Recipe {
result: Ingredient,
ingredients: Vec<Ingredient>,
}
impl Recipe {
fn from_line(line: &str) -> Recipe {
let parts = line.split(" => ").collect::<Vec<_>>();
let result = Ingredient::from_string(parts[1]);
let ingredients = parts[0]
.split(", ")
.map(|ingredient| Ingredient::from_string(ingredient))
.collect::<Vec<_>>();
Recipe {
result,
ingredients,
}
}
}
fn count_fuel_made(ore_limit: u64, recipes: &HashMap<String, Recipe>) -> u64 {
let single_fuel_cost = get_ore_cost(&recipes, 1);
let mut min = ore_limit / single_fuel_cost;
let mut max = 2 * min;
loop {
let target = (min + max) / 2;
let cost = get_ore_cost(&recipes, target);
let cost_of_plus_one = get_ore_cost(&recipes, target + 1);
if cost <= ore_limit && cost_of_plus_one > ore_limit {
break target;
}
if cost < ore_limit {
min = target;
} else {
max = target;
}
}
}
fn get_ore_cost(recipes: &HashMap<String, Recipe>, fuel_count: u64) -> u64 {
let mut elements = HashMap::new();
elements.insert("FUEL".to_string(), fuel_count);
elements = reduce_to_ore(&recipes, elements);
*elements.get(ORE).expect("ore entry not found")
}
fn only_need_ore(need: &HashMap<String, u64>) -> bool {
let elements = need.keys().collect::<Vec<_>>();
elements.len() == 1 && elements[0] == ORE
}
fn parse_input(input: &[u8]) -> HashMap<String, Recipe> {
let mut recipes = HashMap::new();
for line in input.lines() {
let recipe = Recipe::from_line(&line.expect("input line not valid UTF-8"));
recipes.insert(recipe.result.name.clone(), recipe);
}
recipes
}
fn reduce_to_ore(
recipes: &HashMap<String, Recipe>,
elements: HashMap<String, u64>,
) -> HashMap<String, u64> {
let mut elements = elements;
let mut extras = HashMap::new();
while !only_need_ore(&elements) {
elements = elements
.iter()
.flat_map(|(element, count)| {
if element == ORE {
vec![(element.clone(), *count)]
} else {
let recipe = recipes
.get(element)
.unwrap_or_else(|| panic!("no recipe for '{}'", element));
let needed = {
let extra = extras.entry(element.clone()).or_default();
if *extra >= *count {
*extra -= count;
0
} else {
let remaining = *count - *extra;
*extra = 0;
remaining
}
};
if needed == 0 {
Vec::new()
} else {
let batches = (needed + recipe.result.count - 1) / recipe.result.count;
extras
.entry(element.clone())
.and_modify(|c| *c += recipe.result.count * batches - needed)
.or_insert(recipe.result.count * batches - needed);
recipe
.ingredients
.iter()
.map(move |ingredient| {
(ingredient.name.clone(), ingredient.count * batches)
})
.collect::<Vec<_>>()
}
}
})
.fold(HashMap::new(), |mut elements, (element, count)| {
elements
.entry(element)
.and_modify(|value| *value += count)
.or_insert(count);
elements
});
}
elements
}
pub fn part1() {
let input = fs::read(INPUT_PATH).expect("count not read input file");
let recipes = parse_input(&input);
let fuel_cost = get_ore_cost(&recipes, 1);
println!("Ore needed: {}", fuel_cost);
}
pub fn part2() {
let input = fs::read(INPUT_PATH).expect("count not read input file");
let recipes = parse_input(&input);
let fuel_created = count_fuel_made(1_000_000_000_000, &recipes);
println!("Fuel created: {}", fuel_created);
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::hashmap;
#[test]
fn count_fuel_made_works() {
let input = b"157 ORE => 5 NZVS\n165 ORE => 6 DCFZ\n44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL\n12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ\n179 ORE => 7 PSHF\n177 ORE => 5 HKGWZ\n7 DCFZ, 7 PSHF => 2 XJWVT\n165 ORE => 2 GPVTF\n3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT";
let recipes = parse_input(input);
let fuel_created = count_fuel_made(1_000_000_000_000, &recipes);
assert_eq!(82_892_753, fuel_created);
}
#[test]
fn parse_input_works() {
let input = b"10 ORE => 10 A\n1 ORE => 1 B\n7 A, 1 B => 1 C\n7 A, 1 C => 1 D\n7 A, 1 D => 1 E\n7 A, 1 E => 1 FUEL";
let recipes = hashmap! {
"A".to_string() => Recipe {
result: Ingredient {
name: "A".to_string(),
count: 10,
},
ingredients: vec![
Ingredient {
name: "ORE".to_string(),
count: 10,
}
],
},
"B".to_string() => Recipe {
result: Ingredient {
name: "B".to_string(),
count: 1,
},
ingredients: vec![
Ingredient {
name: "ORE".to_string(),
count: 1,
}
],
},
"C".to_string() => Recipe {
result: Ingredient {
name: "C".to_string(),
count: 1,
},
ingredients: vec![
Ingredient {
name: "A".to_string(),
count: 7,
},
Ingredient {
name: "B".to_string(),
count: 1,
}
],
},
"D".to_string() => Recipe {
result: Ingredient {
name: "D".to_string(),
count: 1,
},
ingredients: vec![
Ingredient {
name: "A".to_string(),
count: 7,
},
Ingredient {
name: "C".to_string(),
count: 1,
}
],
},
"E".to_string() => Recipe {
result: Ingredient {
name: "E".to_string(),
count: 1,
},
ingredients: vec![
Ingredient {
name: "A".to_string(),
count: 7,
},
Ingredient {
name: "D".to_string(),
count: 1,
}
],
},
"FUEL".to_string() => Recipe {
result: Ingredient {
name: "FUEL".to_string(),
count: 1,
},
ingredients: vec![
Ingredient {
name: "A".to_string(),
count: 7,
},
Ingredient {
name: "E".to_string(),
count: 1,
}
],
},
};
assert_eq!(recipes, parse_input(input));
}
#[test]
fn reduce_to_ore_works_1() {
let input = b"10 ORE => 10 A\n1 ORE => 1 B\n7 A, 1 B => 1 C\n7 A, 1 C => 1 D\n7 A, 1 D => 1 E\n7 A, 1 E => 1 FUEL";
let recipes = parse_input(input);
let mut elements = HashMap::new();
elements.insert("FUEL".to_string(), 1);
elements = reduce_to_ore(&recipes, elements);
assert_eq!(31, *elements.get(ORE).expect("ore entry not found"));
}
#[test]
fn reduce_to_ore_works_2() {
let input = b"9 ORE => 2 A\n8 ORE => 3 B\n7 ORE => 5 C\n3 A, 4 B => 1 AB\n5 B, 7 C => 1 BC\n4 C, 1 A => 1 CA\n2 AB, 3 BC, 4 CA => 1 FUEL";
let recipes = parse_input(input);
let mut elements = HashMap::new();
elements.insert("FUEL".to_string(), 1);
elements = reduce_to_ore(&recipes, elements);
assert_eq!(165, *elements.get(ORE).expect("ore entry not found"));
}
#[test]
fn reduce_to_ore_works_3() {
let input = b"157 ORE => 5 NZVS\n165 ORE => 6 DCFZ\n44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL\n12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ\n179 ORE => 7 PSHF\n177 ORE => 5 HKGWZ\n7 DCFZ, 7 PSHF => 2 XJWVT\n165 ORE => 2 GPVTF\n3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT";
let recipes = parse_input(input);
let mut elements = HashMap::new();
elements.insert("FUEL".to_string(), 1);
elements = reduce_to_ore(&recipes, elements);
assert_eq!(13312, *elements.get(ORE).expect("ore entry not found"));
}
}
| true
|
dfbc8652b020b227cd14ae74f069620dd20259ab
|
Rust
|
seanwallawalla-forks/nushell
|
/crates/nu-command/src/commands/viewers/autoview/options.rs
|
UTF-8
| 1,168
| 3
| 3
|
[
"MIT"
] |
permissive
|
pub use nu_data::config::NuConfig;
use std::fmt::Debug;
#[derive(PartialEq, Debug)]
pub enum AutoPivotMode {
Auto,
Always,
Never,
}
impl AutoPivotMode {
pub fn is_auto(&self) -> bool {
matches!(self, AutoPivotMode::Auto)
}
pub fn is_always(&self) -> bool {
matches!(self, AutoPivotMode::Always)
}
#[allow(unused)]
pub fn is_never(&self) -> bool {
matches!(self, AutoPivotMode::Never)
}
}
pub trait ConfigExtensions: Debug + Send {
fn pivot_mode(&self) -> AutoPivotMode;
}
pub fn pivot_mode(config: &NuConfig) -> AutoPivotMode {
let vars = &config.vars;
if let Some(mode) = vars.get("pivot_mode") {
let mode = match mode.as_string() {
Ok(m) if m.to_lowercase() == "auto" => AutoPivotMode::Auto,
Ok(m) if m.to_lowercase() == "always" => AutoPivotMode::Always,
Ok(m) if m.to_lowercase() == "never" => AutoPivotMode::Never,
_ => AutoPivotMode::Never,
};
return mode;
}
AutoPivotMode::Never
}
impl ConfigExtensions for NuConfig {
fn pivot_mode(&self) -> AutoPivotMode {
pivot_mode(self)
}
}
| true
|
c43b1cdb611278a2d5a0ff5f9ecf57c64004cad2
|
Rust
|
wooddeep/lee
|
/src/executor/mod.rs
|
UTF-8
| 9,631
| 3
| 3
|
[] |
no_license
|
use crate::parser::*;
use crate::lexer::*;
use crate::tree::*;
use std::ops::Deref;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub struct Executor<'a> {
parser: &'a mut Parser<'a>,
para_map: Rc<HashMap<String, HashMap<String, i32>>>, // 记录个函数的参数列表
}
impl<'a> Executor<'a> {
pub fn new(parser: &'a mut Parser<'a>) -> Self {
Executor { parser, para_map: Rc::new(Default::default()) }
}
pub fn parser(&'a mut self) -> &'a mut Parser<'a> {
self.parser
}
pub fn eval_program(&mut self) {
let etl = self.parser.parse_program();
self.eval_etree_list(&etl.0, &etl.1, None, None);
//self.eval_func_map(&etl.1);
}
pub fn eval_func_call(&mut self, ft: &FuncTree, alist: &Vec<Etree>, fm: &HashMap<String, Etree>) {
let body = ft.fbody.as_ref().unwrap(); // 函数体
let plist = ft.plist.as_ref().unwrap();
self.eval_etree_list(body, fm, Some(plist), Some(alist));
}
pub fn eval_etree(&mut self, et: &Etree, fm: &HashMap<String, Etree>,
plist: Option<&HashMap<String, i32>>, alist: Option<&Vec<Etree>>) {
match et {
Etree::FuncCallTree(fctree) => {
println!("## function name: {}", fctree.func_name);
let ftree = fm.get(&fctree.func_name).unwrap().func_tree().unwrap();
self.eval_func_call(ftree, fctree.alist.as_ref().unwrap(), fm);
}
Etree::Tree(tree) => {
match tree.semantics_type {
SemanticsType::Calculate | SemanticsType::Compare | SemanticsType::Direct => {
let value = self.eval_num_calc(&tree, plist, alist);
println!("## result = {:?}", value);
}
_ => {}
}
}
Etree::IfTree(itree) => {
let value = self.eval_num_calc(
&itree.condition.as_ref().unwrap().tree().unwrap(), plist, alist);
match value {
Value::Bool(bv) => {
if bv {
println!("## in if branch!");
self.eval_etree_list(itree.if_branch.as_ref().unwrap(), fm, None, None);
} else {
println!("## in else branch!");
self.eval_etree_list(itree.else_branch.as_ref().unwrap(), fm, None, None);
}
}
Value::Float(fv) => {
if fv > 0f32 {
println!("## in if branch!");
self.eval_etree_list(itree.if_branch.as_ref().unwrap(), fm, None, None);
} else {
println!("## in else branch!");
self.eval_etree_list(itree.else_branch.as_ref().unwrap(), fm, None, None);
}
}
_ => {}
}
}
_ => {}
}
}
pub fn eval_etree_list(&mut self, etl: &Vec<Etree>, fm: &HashMap<String, Etree>,
plist: Option<&HashMap<String, i32>>, alist: Option<&Vec<Etree>>) {
for et in etl.iter() {
self.eval_etree(et, fm, plist, alist);
}
}
pub fn eval_func_map(&mut self, fmap: &HashMap<String, Etree>) {
for (_, tree) in fmap {
self.eval_etree(tree, fmap, None, None);
}
}
pub fn eval(&mut self) {
let ot = self.parser.parse_expr();
match ot {
None => {}
Some(tree) => {
match tree.tree().unwrap().token_type {
TokenType::MULTIP | TokenType::DIVIDER | TokenType::PLUS | TokenType::SUBSTRACT => {
let value = self.eval_num_calc(&tree.tree().unwrap(), None, None);
println!("## result = {:?}", value)
}
_ => {}
}
()
}
}
}
pub fn eval_compare(&mut self, tree: &Tree) -> Value {
let left_val = self.eval_num_calc(tree.left.as_ref().unwrap().tree().unwrap(), None, None);
let right_val = self.eval_num_calc(tree.right.as_ref().unwrap().tree().unwrap(), None, None);
match tree.token_type {
TokenType::EQ => {
return Value::Bool(left_val == right_val);
}
TokenType::UE => {
return Value::Bool(left_val != right_val);
}
TokenType::GT => {
return Value::Bool(left_val > right_val);
}
TokenType::GE => {
return Value::Bool(left_val >= right_val);
}
TokenType::LT => {
return Value::Bool(left_val < right_val);
}
TokenType::LE => {
return Value::Bool(left_val <= right_val);
}
_ => {}
}
return Value::Bool(true);
}
pub fn eval_num_calc(&mut self, tree: &Tree, plist: Option<&HashMap<String, i32>>,
alist: Option<&Vec<Etree>>) -> Value {
match tree.semantics_type {
SemanticsType::Direct => {
return tree.value.clone();
}
SemanticsType::Variable => { // 变量
let para_name = tree.value.get_str().unwrap();
let para_index = plist.unwrap().get(para_name).unwrap();
println!("# var name: {:?}, index: {:?}", para_name, para_index);
let arg = alist.unwrap().get( *para_index as usize).unwrap();
match arg {
Etree::Tree(tree) => {
return self.eval_num_calc(tree, plist, alist);
},
_ => {return Value::Float(0f32)},
}
}
SemanticsType::Compare => {
println!("it compare type");
return self.eval_compare(tree);
}
_ => {
let left_val = self.eval_num_calc(&tree.left.as_ref().unwrap().tree().unwrap(), plist, alist);
let right_val = self.eval_num_calc(&tree.right.as_ref().unwrap().tree().unwrap(), plist, alist);
match tree.token_type {
TokenType::MULTIP => {
let lv = match left_val {
Value::Float(v) => v,
_ => panic!("undefine value type"),
};
let rv = match right_val {
Value::Float(v) => v,
_ => panic!("undefine value type"),
};
return Value::Float(lv * rv);
}
TokenType::DIVIDER => {
let lv = match left_val {
Value::Float(v) => v,
_ => panic!("undefine value type"),
};
let rv = match right_val {
Value::Float(v) => v,
_ => panic!("undefine value type"),
};
return Value::Float(lv / rv);
}
TokenType::PLUS => {
let lv = match left_val {
Value::Float(v) => (v, None),
Value::Charset(s) => (0f32, Some(s)),
_ => panic!("undefine value type"),
};
let rv = match right_val {
Value::Float(v) => (v, None),
Value::Charset(s) => (0f32, Some(s)),
_ => panic!("undefine value type"),
};
if lv.1 == None && rv.1 == None { // 1. 0 + 2.0 = 3.0
return Value::Float(lv.0 + rv.0);
}
if lv.1 == None && rv.1 != None { // 1 + "abc" = "1abc"
return Value::Charset(lv.0.to_string() + &rv.1.unwrap());
}
if lv.1 != None && rv.1 == None { // 1 + "abc" = "1abc"
return Value::Charset(lv.1.unwrap() + rv.0.to_string().as_str());
}
return Value::Charset(lv.1.unwrap() + &rv.1.unwrap());
}
TokenType::SUBSTRACT => {
let lv = match left_val {
Value::Float(v) => v,
_ => panic!("undefine value type"),
};
let rv = match right_val {
Value::Float(v) => v,
_ => panic!("undefine value type"),
};
return Value::Float(lv - rv);
}
_ => { return Value::Float(0f32); }
}
}
}
}
}
| true
|
5988110d9948cadb19e5b2413147fd3ecf742328
|
Rust
|
mordet/yabook
|
/telegram/src/user_message.rs
|
UTF-8
| 1,086
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
use telegram_bot::{MessageEntityKind, MessageEntity};
pub struct UserMessage {
pub command: Option<String>,
pub mentions: Vec<String>
}
fn substring(data: &String, offset: i64, length: i64) -> String {
data.chars()
.skip(offset as usize)
.take(length as usize)
.collect()
}
impl UserMessage {
pub fn new(data: &String, entities: &Vec<MessageEntity>) -> UserMessage {
let mut command: Option<String> = None;
let mut mentions: Vec<String> = vec![];
for entity in entities {
let value = substring(&data, entity.offset, entity.length);
match entity.kind {
MessageEntityKind::Mention => {
mentions.push(value);
},
MessageEntityKind::BotCommand => match command {
None => command = Some(value),
Some(_) => println!("Secondary command found, rejecting"),
},
_ => {},
}
}
UserMessage { command: command, mentions: mentions }
}
}
| true
|
d687a247358f2d7d266a6ef14ede696d47eee27b
|
Rust
|
freddyDappDev/lazycli
|
/src/template.rs
|
UTF-8
| 1,244
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
use regex::{Captures, Regex};
use crate::{config::Command, parse::Row};
pub fn resolve_command(command: &dyn Command, row: &Row) -> String {
// if keybinding has a regex we need to use that, otherwise we generate the regex ourselves
let matches = match &command.regex() {
Some(regex) => {
let regex = Regex::new(regex).unwrap(); // TODO: handle malformed regex
match regex.captures(&row.original_line) {
None => vec![],
Some(captures) => captures
.iter()
.map(|capture| match capture {
Some(capture) => capture.as_str(),
None => "",
})
.collect::<Vec<&str>>(),
}
}
None => row.cells_as_strs(),
};
template_replace(&command.command(), &matches)
}
// adapted from https://stackoverflow.com/questions/53974404/replacing-numbered-placeholders-with-elements-of-a-vector-in-rust
pub fn template_replace(template: &str, values: &[&str]) -> String {
let regex = Regex::new(r#"\$(\d+)"#).unwrap();
regex
.replace_all(template, |captures: &Captures| {
values.get(index(captures)).unwrap_or(&"")
})
.to_string()
}
fn index(captures: &Captures) -> usize {
captures.get(1).unwrap().as_str().parse().unwrap()
}
| true
|
2ff3cbc4697fe868c9e48136ea18a09ecc2a3f7a
|
Rust
|
geom3trik/swash
|
/src/scale/outline.rs
|
UTF-8
| 11,252
| 3.25
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
/*!
Glyph outline.
*/
use zeno::{Bounds, PathData, Point, Transform, Verb};
/// Scaled glyph outline represented as a collection of layers and a sequence
/// of points and verbs.
#[derive(Clone, Default)]
pub struct Outline {
layers: Vec<LayerData>,
points: Vec<Point>,
verbs: Vec<Verb>,
is_color: bool,
}
impl Outline {
/// Creates a new empty outline.
pub fn new() -> Self {
Self::default()
}
/// Returns true if the outline has color layers.
pub fn is_color(&self) -> bool {
self.is_color
}
/// Returns the number of layers in the outline.
pub fn len(&self) -> usize {
self.layers.len()
}
/// Returns true if there are no layers in the outline.
pub fn is_empty(&self) -> bool {
self.layers.is_empty()
}
/// Returns a reference to the layer at the specified index.
pub fn get<'a>(&'a self, index: usize) -> Option<Layer<'a>> {
let data = self.layers.get(index)?;
let points = self.points.get(data.points.0..data.points.1)?;
let verbs = self.verbs.get(data.verbs.0..data.verbs.1)?;
let color_index = data.color_index;
Some(Layer {
points,
verbs,
color_index,
})
}
/// Returns a mutable reference to the layer at the specified index.
pub fn get_mut<'a>(&'a mut self, index: usize) -> Option<LayerMut<'a>> {
let data = self.layers.get(index)?;
let points = self.points.get_mut(data.points.0..data.points.1)?;
let verbs = self.verbs.get(data.verbs.0..data.verbs.1)?;
let color_index = data.color_index;
Some(LayerMut {
points,
verbs,
color_index,
})
}
/// Returns a reference to the sequence of points in the outline.
pub fn points(&self) -> &[Point] {
&self.points
}
/// Returns a mutable reference to the sequence of points in the outline.
pub fn points_mut(&mut self) -> &mut [Point] {
&mut self.points
}
/// Returns a reference to the sequence of verbs in the outline.
pub fn verbs(&self) -> &[Verb] {
&self.verbs
}
/// Returns path data for the outline.
pub fn path(&self) -> impl PathData + '_ {
(&self.points[..], &self.verbs[..])
}
/// Computes the bounding box of the outline.
pub fn bounds(&self) -> Bounds {
Bounds::from_points(&self.points)
}
/// Transforms the outline by the specified matrix.
pub fn transform(&mut self, transform: &Transform) {
for p in &mut self.points {
*p = transform.transform_point(*p);
}
}
/// Applies a faux bold to the outline with the specified strengths in the
/// x and y directions.
pub fn embolden(&mut self, x_strength: f32, y_strength: f32) {
for i in 0..self.len() {
if let Some(mut layer) = self.get_mut(i) {
layer.embolden(x_strength, y_strength);
}
}
}
/// Clears the outline.
pub fn clear(&mut self) {
self.points.clear();
self.verbs.clear();
self.layers.clear();
self.is_color = false;
}
}
/// Reference to a layer in a scaled outline.
#[derive(Copy, Clone)]
pub struct Layer<'a> {
points: &'a [Point],
verbs: &'a [Verb],
color_index: Option<u16>,
}
impl<'a> Layer<'a> {
/// Returns the sequence of points for the layer.
pub fn points(&self) -> &'a [Point] {
self.points
}
/// Returns the sequence of verbs for the layer.
pub fn verbs(&self) -> &'a [Verb] {
self.verbs
}
/// Returns path data for the layer.
pub fn path(&self) -> impl PathData + 'a {
(self.points(), self.verbs())
}
/// Computes the bounding box of the layer.
pub fn bounds(&self) -> Bounds {
Bounds::from_points(self.points())
}
/// Returns the color index for the layer.
pub fn color_index(&self) -> Option<u16> {
self.color_index
}
}
/// Mutable reference to a layer in a scaled outline.
pub struct LayerMut<'a> {
points: &'a mut [Point],
verbs: &'a [Verb],
color_index: Option<u16>,
}
impl<'a> LayerMut<'a> {
/// Returns the sequence of points for the layer.
pub fn points(&'a self) -> &'a [Point] {
&self.points[..]
}
/// Returns a mutable reference the sequence of points for the layer.
pub fn points_mut(&'a mut self) -> &'a mut [Point] {
&mut *self.points
}
/// Returns the sequence of verbs for the layer.
pub fn verbs(&self) -> &'a [Verb] {
self.verbs
}
/// Returns path data for the layer.
pub fn path(&'a self) -> impl PathData + 'a {
(self.points(), self.verbs())
}
/// Computes the bounding box of the layer.
pub fn bounds(&self) -> Bounds {
Bounds::from_points(self.points())
}
/// Returns the color index for the layer.
pub fn color_index(&self) -> Option<u16> {
self.color_index
}
/// Transforms this layer by the specified matrix.
pub fn transform(&'a mut self, transform: &Transform) {
for p in self.points.iter_mut() {
*p = transform.transform_point(*p);
}
}
/// Applies a faux bold to this layer with the specified strengths in the
/// x and y directions.
pub fn embolden(&mut self, x_strength: f32, y_strength: f32) {
let mut point_start = 0;
let mut pos = 0;
let winding = compute_winding(self.points);
for verb in self.verbs {
match verb {
Verb::MoveTo | Verb::Close => {
if let Some(points) = self.points.get_mut(point_start..pos) {
if !points.is_empty() {
embolden(points, winding, x_strength, y_strength);
}
point_start = pos;
if *verb == Verb::MoveTo {
pos += 1;
}
} else {
return;
}
}
Verb::LineTo => pos += 1,
Verb::QuadTo => pos += 2,
Verb::CurveTo => pos += 3,
}
}
if pos > point_start {
if let Some(points) = self.points.get_mut(point_start..pos) {
embolden(points, winding, x_strength, y_strength);
}
}
}
}
#[derive(Copy, Clone, Default)]
struct LayerData {
points: (usize, usize),
verbs: (usize, usize),
color_index: Option<u16>,
}
impl Outline {
pub(super) fn set_color(&mut self, color: bool) {
self.is_color = color;
}
pub(super) fn move_to(&mut self, p: Point) {
self.maybe_close();
self.points.push(p);
self.verbs.push(Verb::MoveTo);
}
pub(super) fn line_to(&mut self, p: Point) {
self.points.push(p);
self.verbs.push(Verb::LineTo);
}
pub(super) fn quad_to(&mut self, p0: Point, p1: Point) {
self.points.push(p0);
self.points.push(p1);
self.verbs.push(Verb::QuadTo);
}
pub(super) fn curve_to(&mut self, p0: Point, p1: Point, p2: Point) {
self.points.push(p0);
self.points.push(p1);
self.points.push(p2);
self.verbs.push(Verb::CurveTo);
}
pub(super) fn close(&mut self) {
self.verbs.push(Verb::Close);
}
pub(super) fn maybe_close(&mut self) {
if !self.verbs.is_empty() && self.verbs.last() != Some(&Verb::Close) {
self.close();
}
}
pub(super) fn begin_layer(&mut self, color_index: Option<u16>) {
let points_end = self.points.len();
let verbs_end = self.verbs.len();
if let Some(last) = self.layers.last_mut() {
last.points.1 = points_end;
last.verbs.1 = verbs_end;
}
self.layers.push(LayerData {
points: (points_end, points_end),
verbs: (verbs_end, verbs_end),
color_index,
});
}
pub(super) fn finish(&mut self) {
let points_end = self.points.len();
let verbs_end = self.verbs.len();
if let Some(last) = self.layers.last_mut() {
last.points.1 = points_end;
last.verbs.1 = verbs_end;
} else {
self.layers.push(LayerData {
points: (0, points_end),
verbs: (0, verbs_end),
color_index: None,
})
}
}
}
fn embolden(points: &mut [Point], winding: u8, x_strength: f32, y_strength: f32) {
if points.is_empty() {
return;
}
let last = points.len() - 1;
let mut i = last;
let mut j = 0;
let mut k = !0;
let mut out_len;
let mut in_len = 0.;
let mut anchor_len = 0.;
let mut anchor = Point::ZERO;
let mut out;
let mut in_ = Point::ZERO;
while j != i && i != k {
if j != k {
out = points[j] - points[i];
out_len = out.length();
if out_len == 0. {
j = if j < last { j + 1 } else { 0 };
continue;
} else {
let s = 1. / out_len;
out.x *= s;
out.y *= s;
}
} else {
out = anchor;
out_len = anchor_len;
}
if in_len != 0. {
if k == !0 {
k = i;
anchor = in_;
anchor_len = in_len;
}
let mut d = (in_.x * out.x) + (in_.y * out.y);
let shift = if d > -0.9396 {
d += 1.;
let mut sx = in_.y + out.y;
let mut sy = in_.x + out.x;
if winding == 0 {
sx = -sx;
} else {
sy = -sy;
}
let mut q = (out.x * in_.y) - (out.y * in_.x);
if winding == 0 {
q = -q;
}
let l = in_len.min(out_len);
if x_strength * q <= l * d {
sx = sx * x_strength / d;
} else {
sx = sx * l / q;
}
if y_strength * q <= l * d {
sy = sy * y_strength / d;
} else {
sy = sy * l / q;
}
Point::new(sx, sy)
} else {
Point::ZERO
};
while i != j {
points[i].x += x_strength + shift.x;
points[i].y += y_strength + shift.y;
i = if i < last { i + 1 } else { 0 };
}
} else {
i = j;
}
in_ = out;
in_len = out_len;
j = if j < last { j + 1 } else { 0 };
}
}
fn compute_winding(points: &[Point]) -> u8 {
if points.is_empty() {
return 0;
}
let mut area = 0.;
let last = points.len() - 1;
let mut prev = points[last];
for cur in points[0..=last].iter() {
area += (cur.y - prev.y) * (cur.x + prev.x);
prev = *cur;
}
if area > 0. {
1
} else {
0
}
}
| true
|
7366dbdc68f6e29c83dfa2d044dc47068fd47e2c
|
Rust
|
nilsso/challenge-solutions
|
/leetcode/problems/redundant-connection/src/main.rs
|
UTF-8
| 1,875
| 3.375
| 3
|
[] |
no_license
|
use std::collections::HashMap;
#[derive(Debug)]
struct DSU {
parents: HashMap<usize, usize>,
ranks: HashMap<usize, usize>,
}
impl DSU {
fn new() -> Self {
DSU {
parents: HashMap::new(),
ranks: HashMap::new(),
}
}
fn parent(&mut self, x: usize) -> &mut usize {
self.parents.entry(x).or_insert(x)
}
fn rank(&mut self, x: usize) -> &mut usize {
self.ranks.entry(x).or_insert(0)
}
fn find(&mut self, x: usize) -> usize {
if self.parent(x) != &x {
let p = *self.parent(x);
*self.parent(x) = self.find(p);
}
*self.parent(x)
}
fn union(&mut self, edge: &Vec<i32>) -> bool {
let (x, y) = (edge[0] as usize, edge[1] as usize);
let (x_rank, y_rank) = (self.find(x), self.find(y));
if x_rank == y_rank {
false
} else {
use std::cmp::Ordering::*;
let (x_parent, y_parent) = (*self.parent(x_rank), *self.parent(y_rank));
match x_parent.cmp(&y_parent) {
Less => *self.parent(x_rank) = y_rank,
Greater => *self.parent(y_rank) = x_rank,
Equal => {
*self.parent(y_rank) = x_rank;
*self.rank(x_rank) += 1;
},
}
true
}
}
}
fn redundant_edge(edges: Vec<Vec<i32>>) -> Vec<i32> {
let mut dsu = DSU::new();
edges.into_iter().find(|edge| !dsu.union(edge)).unwrap()
}
fn to_edges(edges: &[(i32, i32)]) -> Vec<Vec<i32>> {
edges.iter().map(|t| vec![t.0, t.1]).collect()
}
fn main() {
println!("{:?}", DSU::new());
}
fn test(edges: &[(i32, i32)], expected: Vec<i32>) {
assert_eq!(redundant_edge(to_edges(edges)), expected);
}
#[test]
fn test_1() {
test(&[(1, 2), (1, 3), (2, 3)], vec![2, 3]);
}
| true
|
81de8f4ffde9aa8996697076b8661a57e9f4d603
|
Rust
|
kumabook/pink-spider
|
/src/get_env.rs
|
UTF-8
| 739
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
use std::env;
use toml::Value;
use std::fs::File;
use std::io::Read;
pub fn var(key: &str) -> Option<String> {
match env::var(key) {
Ok(value) => Some(value),
Err(_) => {
let file = File::open("config/env.toml");
if file.is_err() {
return None;
}
let mut f = file.unwrap();
let mut s = String::new();
let _ = f.read_to_string(&mut s);
if let Ok(value) = s.parse::<Value>() {
value.as_table()
.and_then(|t| t.get(key))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
} else {
None
}
}
}
}
| true
|
25dad3fc77f9e9149e33b469019432a8ffd7e1a8
|
Rust
|
faustfu/hello_rust
|
/src/types/option1.rs
|
UTF-8
| 1,434
| 4.125
| 4
|
[] |
no_license
|
// 1. Option is generic enum of Some and None. Therefore it could be some value or none.
// enum Option<T> {
// Some(T),
// None,
// }
// 2. Use method:unwrap to parse a Some result or panic the system.
// 3. Use question mark operator to parse a Some result or return None.
// 4. Choosing between match and if let depends on what you’re doing in your particular situation and
// whether gaining conciseness is an appropriate trade-off for losing exhaustive checking.
/* map signature
impl Option<T>{
fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U { ... }
}
*/
pub fn run() {
// case 1(match)
let x = 3.0;
let y = 2.0;
let result: Option<f64> = if y != 0.0 { Some(x / y) } else { None };
println!("result = {:?}", result);
match result {
Some(z) => println!("{} / {} = {}", x, y, z),
None => println!("{} / {} has errors", x, y),
}
// case 2(if let)
// parsing is ok, then "if" block will be executed.
if let Some(z) = result {
println!("z = {}", z)
};
// case 3(map with functions)
let i = Some(5);
if let Some(z) = maybe_add_4(i) {
println!("z = {}", z)
};
// case 4(map with closures)
let i = Some(5);
if let Some(z) = maybe_add_5(i) {
println!("z = {}", z)
};
}
fn maybe_add_4(i: Option<i32>) -> Option<i32> {
i.map(add_4)
}
fn add_4(i: i32) -> i32 {
i + 4
}
fn maybe_add_5(i: Option<i32>) -> Option<i32> {
i.map(|x| x + 5)
}
| true
|
86ae412c7e7705585a4b85ba08cda78d44326cbf
|
Rust
|
reitermarkus/vcontrol-rs
|
/src/types/error.rs
|
UTF-8
| 2,599
| 3.21875
| 3
|
[] |
no_license
|
use core::fmt;
use arrayref::array_ref;
#[cfg(feature = "impl_json_schema")]
use schemars::JsonSchema;
use serde::{Serialize, Deserialize};
use crate::Device;
use super::DateTime;
#[cfg_attr(feature = "impl_json_schema", derive(JsonSchema))]
#[derive(Clone, PartialEq, Deserialize, Serialize)]
pub struct Error {
index: u8,
time: DateTime,
}
impl Error {
pub fn new(index: u8, time: DateTime) -> Self {
Self { index, time }
}
pub fn index(&self) -> u8 {
self.index
}
pub fn to_str(&self, device: &Device) -> Option<&'static str> {
device.errors().get(&(self.index as i32)).cloned()
}
pub fn time(&self) -> &DateTime {
&self.time
}
pub fn from_bytes(bytes: &[u8; 9]) -> Self {
let index = bytes[0];
let time = DateTime::from_bytes(array_ref![bytes, 1, 8]);
Self { index, time }
}
pub fn to_bytes(&self) -> [u8; 9] {
let mut bytes = [0; 9];
let time_bytes = self.time.to_bytes();
bytes[0] = self.index;
bytes[1..].copy_from_slice(&time_bytes);
bytes
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: Error {:02X}", self.time, self.index)
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error({}, ", self.index)?;
self.time.fmt(f)?;
write!(f, ")")
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Timelike;
use chrono::Datelike;
#[test]
fn new() {
let time = DateTime::new(2018, 12, 23, 17, 49, 31);
let error = Error::new(0xAC, time.clone());
assert_eq!(error.index, 0xAC);
assert_eq!(time.0.year(), 2018);
assert_eq!(time.0.month(), 12);
assert_eq!(time.0.day(), 23);
assert_eq!(time.0.weekday().number_from_monday(), 7);
assert_eq!(time.0.hour(), 17);
assert_eq!(time.0.minute(), 49);
assert_eq!(time.0.second(), 31);
}
#[test]
fn from_bytes() {
let error = Error::from_bytes(&[0xAC, 0x20, 0x18, 0x12, 0x23, 0x07, 0x17, 0x49, 0x31]);
assert_eq!(error.index, 0xAC);
assert_eq!(error.time.0.year(), 2018);
assert_eq!(error.time.0.month(), 12);
assert_eq!(error.time.0.day(), 23);
assert_eq!(error.time.0.weekday().number_from_monday(), 7);
assert_eq!(error.time.0.hour(), 17);
assert_eq!(error.time.0.minute(), 49);
assert_eq!(error.time.0.second(), 31);
}
#[test]
fn to_bytes() {
let time = DateTime::new(2018, 12, 23, 17, 49, 31);
let error = Error::new(0xAC, time);
assert_eq!(error.to_bytes(), [0xAC, 0x20, 0x18, 0x12, 0x23, 0x07, 0x17, 0x49, 0x31]);
}
}
| true
|
e59e8b8ab4aebc1b775eab83e87f768f02115ba8
|
Rust
|
pchickey/cap-std
|
/cap-primitives/src/winx/fs/is_same_file.rs
|
UTF-8
| 1,875
| 2.984375
| 3
|
[
"MIT",
"LLVM-exception",
"Apache-2.0"
] |
permissive
|
use crate::fs::Metadata;
use std::{fs, io};
/// Determine if `a` and `b` refer to the same inode on the same device.
#[cfg(windows_by_handle)]
#[allow(dead_code)]
pub(crate) fn is_same_file(a: &fs::File, b: &fs::File) -> io::Result<bool> {
let a_metadata = Metadata::from_std(a.metadata()?);
let b_metadata = Metadata::from_std(b.metadata()?);
is_same_file_metadata(&a_metadata, &b_metadata)
}
/// Determine if `a` and `b` are metadata for the same inode on the same device.
#[cfg(windows_by_handle)]
#[allow(dead_code)]
pub(crate) fn is_same_file_metadata(a: &Metadata, b: &Metadata) -> io::Result<bool> {
use std::os::windows::fs::MetadataExt;
Ok(a.volume_serial_number() == b.volume_serial_number() && a.file_index() == b.file_index())
}
/// Determine if `a` and `b` definitely refer to different inodes.
///
/// This is similar to `is_same_file`, but is conservative, and doesn't depend
/// on nightly-only features.
pub(crate) fn is_different_file(a: &fs::File, b: &fs::File) -> io::Result<bool> {
#[cfg(windows_by_handle)]
{
is_same_file(a, b).map(|same| !same)
}
#[cfg(not(windows_by_handle))]
{
let a_metadata = Metadata::from_std(a.metadata()?);
let b_metadata = Metadata::from_std(b.metadata()?);
is_different_file_metadata(&a_metadata, &b_metadata)
}
}
/// Determine if `a` and `b` are metadata for definitely different inodes.
///
/// This is similar to `is_same_file_metadata`, but is conservative, and doesn't depend
/// on nightly-only features.
pub(crate) fn is_different_file_metadata(a: &Metadata, b: &Metadata) -> io::Result<bool> {
#[cfg(windows_by_handle)]
{
is_same_file_metadata(a, b).map(|same| !same)
}
#[cfg(not(windows_by_handle))]
{
// Conservatively just compare creation times.
Ok(a.created()? != b.created()?)
}
}
| true
|
6b84f0e8065e100f19de4949508bc39f5e5c8bda
|
Rust
|
input-output-hk/jormungandr
|
/jcli/src/jcli_lib/transaction/new.rs
|
UTF-8
| 947
| 2.578125
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::jcli_lib::transaction::{common, staging::Staging, Error};
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(rename_all = "kebab-case")]
pub struct New {
#[structopt(flatten)]
pub common: common::CommonTransaction,
}
impl New {
pub fn exec(self) -> Result<(), Error> {
let staging = Staging::new();
self.common.store(&staging)
}
}
#[cfg(test)]
mod tests {
use self::common::CommonTransaction;
use super::*;
use assert_fs::{prelude::*, NamedTempFile};
use predicates::prelude::*;
#[test]
pub fn test_staging_file_is_created() {
let tempfile = NamedTempFile::new("staging").unwrap();
let new = New {
common: CommonTransaction {
staging_file: Some(tempfile.path().into()),
},
};
new.exec().expect(" error while executing New action");
tempfile.assert(predicate::path::is_file());
}
}
| true
|
3f1c9c2e8093da05d9f283ca56fedc5dff181ef1
|
Rust
|
norse-rs/runic
|
/src/rasterizer/hati.rs
|
UTF-8
| 3,785
| 2.578125
| 3
|
[] |
no_license
|
use crate::{
math::*, rasterize_each_with_bias, Curve, Framebuffer, Rasterizer, Rect,
Segment, Filter,
};
pub struct HatiRasterizer<F: Filter> {
pub filter: F,
}
impl<F: Filter> Rasterizer for HatiRasterizer<F> {
fn name(&self) -> String {
format!("HatiRasterizer :: {}", self.filter.name())
}
fn create_path(&mut self, segments: &[Segment]) -> Vec<Curve> {
let mut curves = Vec::new();
for segment in segments {
for curve in segment {
curves.push(*curve);
}
}
curves
}
fn cmd_draw(
&mut self,
framebuffer: &mut Framebuffer,
rect: Rect,
path: &[Curve],
) {
rasterize_each_with_bias(
(1.0, 1.0),
framebuffer,
rect,
|pos_curve, dxdy| {
let mut coverage = 0.0;
let mut distance = 100000.0f32;
for curve in path {
match curve {
Curve::Line { p0, p1 } => {
let p0 = *p0 - pos_curve;
let p1 = *p1 - pos_curve;
let sign_y = (p1.y() > 0.0) as i32 - (p0.y() > 0.0) as i32;
let dir = p1 - p0;
let dp = -p0;
let t = dir.dot(dp) / dir.dot(dir);
let n = (dp - dir * t) / dxdy;
let sign = n.x().signum();
let nd = (dp - dir * clamp(t, 0.0, 1.0)) / dxdy;
let d = nd.length();
coverage += sign_y as f32 * sign.min(0.0);
distance = distance.min(d);
}
Curve::Quad { p0, p1, p2 } => {
let p0 = *p0 - pos_curve;
let p1 = *p1 - pos_curve;
let p2 = *p2 - pos_curve;
let sign_y = (p2.y() > 0.0) as i32 - (p0.y() > 0.0) as i32;
let t = quad_raycast(p0.y(), p1.y(), p2.y(), 0.0);
let dx = quad_eval(p0.x(), p1.x(), p2.x(), t) / dxdy.x();
let yy0 = clamp(- 0.5 * dxdy.y(), p0.y(), p2.y());
let yy1 = clamp(0.5 * dxdy.y(), p0.y(), p2.y());
let ty0 = quad_raycast(p0.y(), p1.y(), p2.y(), yy0); // raycast y direction
let ty1 = quad_raycast(p0.y(), p1.y(), p2.y(), yy1); // raycast y direction
// xx = (p2.x() > 0.0) as i32 - (p0.x() > 0.0) as i32;
// yy = (p2.y() > 0.0) as i32 - (p0.y() > 0.0) as i32;
// if yy != 0 {
// let t = quad_raycast(p0.y(), p1.y(), p2.y(), 0.0);
// let d = quad_eval(p0.x(), p1.x(), p2.x(), t) / dxdy.x();
// coverage -= yy as f32 * d.signum().min(0.0);
// a = d;
// }
// let d = match (xx == 0, yy == 0) {
// (true, true) => quack,
// (true, false) => a.abs(),
// (false, true) => b.abs(),
// (false, false) => (a * b).abs() / (2.0 * (a*a + b * b).sqrt()),
// };
// quack = quack.min(d);
}
}
}
self.filter.cdf((2.0 * coverage - 1.0) * distance)
},
);
}
}
| true
|
7d901168167e384ac20d676e665a83427fd14fa6
|
Rust
|
tomdewildt/rust-basics
|
/src/loops.rs
|
UTF-8
| 481
| 4.15625
| 4
|
[
"MIT"
] |
permissive
|
// Loops are used to iterate until a condition is met
pub fn main() {
let mut integer = 0;
// Infinite loop
loop {
integer += 1;
println!("Infinite loop: {}", integer);
if integer >= 5 {
break;
}
}
// While loop
while integer <= 10 {
println!("While loop: {}", integer);
integer += 1;
}
// For range loop
for value in 0..5 {
println!("For range loop: {}", value);
}
}
| true
|
a2128f96a24ecab9d6b2aab5284394639b21bb33
|
Rust
|
tessi/rpiet
|
/src/cmd_options.rs
|
UTF-8
| 3,552
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
use clap::{App, Arg, ArgMatches};
pub struct CmdOptions<'a> {
pub verbose: bool,
pub codel_size: u32,
pub max_steps: u128,
pub unlimited_steps: bool,
pub unknown_white: bool,
pub file_path: &'a str,
}
fn is_valid_file_name(val: String) -> Result<(), String> {
if val.ends_with(".png") {
return Ok(());
}
if val.ends_with(".gif") {
return Ok(());
}
Err(String::from("the file format must one of {png, gif}."))
}
pub fn clap_options() -> ArgMatches<'static> {
App::new("myapp")
.version(clap::crate_version!())
.author("Philipp Tessenow <philipp@tessenow.org>")
.about("An interpreter for the piet programming language")
.arg(
Arg::with_name("file")
.help("The image to execute. Supports png and gif files only")
.default_value("input.png")
.index(1)
.required(true)
.validator(is_valid_file_name),
)
.arg(
Arg::with_name("codel_size")
.help("The length of a codel in pixels")
.default_value("1")
.short("c")
.long("codel-size")
.long_help(
"Piet works by going through the pixels of an image.\n\
However, this makes piet images visually small when viewing them.\n\
Thus, piet allows interpreting images in codels which consist of larger pixels blocks.\n\
Setting codel-size to 2 would mean a codel is the size of 2x2 pixels.",
)
.takes_value(true)
.required(false)
.validator(|s| {
s.parse::<u32>()
.map(|_| ())
.map_err(|_| String::from("Must be a positive number!"))
}),
)
.arg(
Arg::with_name("max_steps")
.help("The max number of allowed execution steps")
.short("e")
.long("max-steps")
.long_help(
"This stops the piet interpreter after the given number of steps and\n\
solves the halting problem once and for all :)\n\
Very useful to debug endless loops",
)
.takes_value(true)
.required(false)
.validator(|s| {
s.parse::<u32>()
.map(|_| ())
.map_err(|_| String::from("Must be a positive number!"))
}),
)
.arg(
Arg::with_name("verbose")
.help("Logs debug information to stderr")
.short("v")
.long("verbose")
)
.get_matches()
}
pub fn cmd_options<'a>(options: &'a ArgMatches) -> CmdOptions<'a> {
let verbose = options.is_present("verbose");
let codel_size = options
.value_of("codel_size")
.map_or(1, |s| s.parse::<u32>().unwrap_or(1));
let max_steps = options
.value_of("max_steps")
.map_or(-1, |s| s.parse::<i128>().unwrap_or(-1));
let file_path = options.value_of("file").unwrap();
CmdOptions {
verbose: verbose,
codel_size: codel_size,
max_steps: if max_steps < 0 { 0 } else { max_steps as u128 },
unlimited_steps: max_steps < 0,
file_path: file_path,
unknown_white: true, // TODO: add a command line option so the user can configure this
}
}
| true
|
f7724c2189b7c7166729cb9c845c219aa38fe8a3
|
Rust
|
jxnu-liguobin/graphql-ws-client
|
/src/websockets.rs
|
UTF-8
| 1,691
| 3.0625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//! Contains traits to provide support for various underlying websocket clients.
/// An abstraction around WebsocketMessages
///
/// graphql-ws-client doesn't implement the websocket protocol itself.
/// This trait provides part of the integration with websocket client libraries.
pub trait WebsocketMessage: std::fmt::Debug {
/// The `Error` type for this websocket client.
type Error: std::error::Error + Send + 'static;
/// Constructs a new message with the given text
fn new(text: String) -> Self;
/// Returns the text (if there is any) contained in this message
fn text(&self) -> Option<&str>;
/// Returns true if this message is a websocket ping.
fn is_ping(&self) -> bool;
/// Returns true if this message is a websocket pong.
fn is_pong(&self) -> bool;
/// Returns true if this message is a websocket close.
fn is_close(&self) -> bool;
}
#[cfg(feature = "async-tungstenite")]
impl WebsocketMessage for async_tungstenite::tungstenite::Message {
type Error = async_tungstenite::tungstenite::Error;
fn new(text: String) -> Self {
async_tungstenite::tungstenite::Message::Text(text)
}
fn text(&self) -> Option<&str> {
match self {
async_tungstenite::tungstenite::Message::Text(text) => Some(text.as_ref()),
_ => None,
}
}
fn is_ping(&self) -> bool {
matches!(self, async_tungstenite::tungstenite::Message::Ping(_))
}
fn is_pong(&self) -> bool {
matches!(self, async_tungstenite::tungstenite::Message::Pong(_))
}
fn is_close(&self) -> bool {
matches!(self, async_tungstenite::tungstenite::Message::Close(_))
}
}
| true
|
736b79b216a9f316e642ed693c07157177c3ee2a
|
Rust
|
HewlettPackard/dockerfile-parser-rs
|
/src/instructions/misc.rs
|
UTF-8
| 1,967
| 2.71875
| 3
|
[
"MIT",
"LicenseRef-scancode-dco-1.1"
] |
permissive
|
// (C) Copyright 2019-2020 Hewlett Packard Enterprise Development LP
use std::convert::TryFrom;
use crate::Span;
use crate::dockerfile_parser::Instruction;
use crate::error::*;
use crate::util::*;
use crate::parser::*;
/// A miscellaneous (unsupported) Dockerfile instruction.
///
/// These are instructions that aren't explicitly parsed. They may be invalid,
/// deprecated, or otherwise unsupported by this library.
///
/// Unsupported but valid commands include: `MAINTAINER`, `EXPOSE`, `VOLUME`,
/// `USER`, `WORKDIR`, `ONBUILD`, `STOPSIGNAL`, `HEALTHCHECK`, `SHELL`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct MiscInstruction {
pub span: Span,
pub instruction: SpannedString,
pub arguments: BreakableString
}
impl MiscInstruction {
pub(crate) fn from_record(record: Pair) -> Result<MiscInstruction> {
let span = Span::from_pair(&record);
let mut instruction = None;
let mut arguments = None;
for field in record.into_inner() {
match field.as_rule() {
Rule::misc_instruction => instruction = Some(parse_string(&field)?),
Rule::misc_arguments => arguments = Some(parse_any_breakable(field)?),
_ => return Err(unexpected_token(field))
}
}
let instruction = instruction.ok_or_else(|| Error::GenericParseError {
message: "generic instructions require a name".into()
})?;
let arguments = arguments.ok_or_else(|| Error::GenericParseError {
message: "generic instructions require arguments".into()
})?;
Ok(MiscInstruction {
span,
instruction, arguments
})
}
}
impl<'a> TryFrom<&'a Instruction> for &'a MiscInstruction {
type Error = Error;
fn try_from(instruction: &'a Instruction) -> std::result::Result<Self, Self::Error> {
if let Instruction::Misc(m) = instruction {
Ok(m)
} else {
Err(Error::ConversionError {
from: format!("{:?}", instruction),
to: "MiscInstruction".into()
})
}
}
}
| true
|
95b429dee9123775503e1672b69631c277c2825b
|
Rust
|
MacTuitui/nannou
|
/examples/wgpu/wgpu_triangle_raw_frame/wgpu_triangle_raw_frame.rs
|
UTF-8
| 2,883
| 3.078125
| 3
|
[] |
permissive
|
//! The same as the `wgpu_triangle` example, but demonstrates how to draw directly to the swap
//! chain texture (`RawFrame`) rather than to nannou's intermediary `Frame`.
use nannou::prelude::*;
struct Model {
bind_group: wgpu::BindGroup,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct Vertex {
position: [f32; 2],
}
const VERTICES: [Vertex; 3] = [
Vertex {
position: [-0.5, -0.25],
},
Vertex {
position: [0.0, 0.5],
},
Vertex {
position: [0.25, -0.1],
},
];
fn main() {
nannou::app(model).run();
}
fn model(app: &App) -> Model {
let w_id = app
.new_window()
.size(512, 512)
.raw_view(view)
.build()
.unwrap();
let window = app.window(w_id).unwrap();
let device = window.swap_chain_device();
// NOTE: We are drawing to the swap chain format, rather than the `Frame::TEXTURE_FORMAT`.
let format = window.swap_chain_descriptor().format;
let vs_mod = wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/vert.spv"));
let fs_mod = wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/frag.spv"));
let vertices_bytes = vertices_as_bytes(&VERTICES[..]);
let usage = wgpu::BufferUsage::VERTEX;
let vertex_buffer = device.create_buffer_with_data(vertices_bytes, usage);
let bind_group_layout = wgpu::BindGroupLayoutBuilder::new().build(device);
let bind_group = wgpu::BindGroupBuilder::new().build(device, &bind_group_layout);
let pipeline_layout = wgpu::create_pipeline_layout(device, &[&bind_group_layout]);
let render_pipeline = wgpu::RenderPipelineBuilder::from_layout(&pipeline_layout, &vs_mod)
.fragment_shader(&fs_mod)
.color_format(format)
.add_vertex_buffer::<Vertex>(&wgpu::vertex_attr_array![0 => Float2])
.build(device);
Model {
bind_group,
vertex_buffer,
render_pipeline,
}
}
fn view(_app: &App, model: &Model, frame: RawFrame) {
let mut encoder = frame.command_encoder();
let mut render_pass = wgpu::RenderPassBuilder::new()
// NOTE: We are drawing to the swap chain texture directly rather than the intermediary
// texture as in `wgpu_triangle`.
.color_attachment(frame.swap_chain_texture(), |color| color)
.begin(&mut encoder);
render_pass.set_pipeline(&model.render_pipeline);
render_pass.set_bind_group(0, &model.bind_group, &[]);
render_pass.set_vertex_buffer(0, &model.vertex_buffer, 0, 0);
let vertex_range = 0..VERTICES.len() as u32;
let instance_range = 0..1;
render_pass.draw(vertex_range, instance_range);
}
// See the `nannou::wgpu::bytes` documentation for why this is necessary.
fn vertices_as_bytes(data: &[Vertex]) -> &[u8] {
unsafe { wgpu::bytes::from_slice(data) }
}
| true
|
6c2c9f996468a0eb78e871c81c818aafa08ebede
|
Rust
|
minhtriet/rustlings
|
/exercises/variables/variables2.rs
|
UTF-8
| 260
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
// variables2.rs
// Make me compile! Execute the command `rustlings hint variables2` if you want a hint :)
fn main() {
let x = 0.15 + 0.15 + 0.15;
if x == 0.1 + 0.25 + 0.1 {
println!("Ten!");
} else {
println!("Not ten!");
}
}
| true
|
972349dfd09ad02d3fe538a363cda82500217993
|
Rust
|
astral-sh/ruff
|
/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs
|
UTF-8
| 3,925
| 3.109375
| 3
|
[
"BSD-3-Clause",
"0BSD",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] |
permissive
|
use itertools::Either::{Left, Right};
use itertools::Itertools;
use ruff_python_ast::{self as ast, Expr, Ranged};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_semantic::analyze::typing::Pep604Operator;
use ruff_source_file::Locator;
use crate::checkers::ast::Checker;
use crate::registry::AsRule;
/// ## What it does
/// Check for type annotations that can be rewritten based on [PEP 604] syntax.
///
/// ## Why is this bad?
/// [PEP 604] introduced a new syntax for union type annotations based on the
/// `|` operator. This syntax is more concise and readable than the previous
/// `typing.Union` and `typing.Optional` syntaxes.
///
/// ## Example
/// ```python
/// from typing import Union
///
/// foo: Union[int, str] = 1
/// ```
///
/// Use instead:
/// ```python
/// foo: int | str = 1
/// ```
///
/// ## Options
/// - `target-version`
/// - `pyupgrade.keep-runtime-typing`
///
/// [PEP 604]: https://peps.python.org/pep-0604/
#[violation]
pub struct NonPEP604Annotation;
impl Violation for NonPEP604Annotation {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!("Use `X | Y` for type annotations")
}
fn autofix_title(&self) -> Option<String> {
Some("Convert to `X | Y`".to_string())
}
}
/// UP007
pub(crate) fn use_pep604_annotation(
checker: &mut Checker,
expr: &Expr,
slice: &Expr,
operator: Pep604Operator,
) {
// Avoid fixing forward references, or types not in an annotation.
let fixable = checker.semantic().in_type_definition()
&& !checker.semantic().in_complex_string_type_definition();
match operator {
Pep604Operator::Optional => {
let mut diagnostic = Diagnostic::new(NonPEP604Annotation, expr.range());
if fixable && checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(Fix::suggested(Edit::range_replacement(
optional(slice, checker.locator()),
expr.range(),
)));
}
checker.diagnostics.push(diagnostic);
}
Pep604Operator::Union => {
let mut diagnostic = Diagnostic::new(NonPEP604Annotation, expr.range());
if fixable && checker.patch(diagnostic.kind.rule()) {
match slice {
Expr::Slice(_) => {
// Invalid type annotation.
}
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
diagnostic.set_fix(Fix::suggested(Edit::range_replacement(
union(elts, checker.locator()),
expr.range(),
)));
}
_ => {
// Single argument.
diagnostic.set_fix(Fix::suggested(Edit::range_replacement(
checker.locator().slice(slice.range()).to_string(),
expr.range(),
)));
}
}
}
checker.diagnostics.push(diagnostic);
}
}
}
/// Format the expression as a PEP 604-style optional.
fn optional(expr: &Expr, locator: &Locator) -> String {
format!("{} | None", locator.slice(expr.range()))
}
/// Format the expressions as a PEP 604-style union.
fn union(elts: &[Expr], locator: &Locator) -> String {
let mut elts = elts
.iter()
.flat_map(|expr| match expr {
Expr::Tuple(ast::ExprTuple { elts, .. }) => Left(elts.iter()),
_ => Right(std::iter::once(expr)),
})
.peekable();
if elts.peek().is_none() {
"()".to_string()
} else {
elts.map(|expr| locator.slice(expr.range())).join(" | ")
}
}
| true
|
8a5c7a6ab675e107b0bf9a69af92a9333c2afd24
|
Rust
|
PacktPublishing/Rust-High-Performance
|
/Chapter10/example1.rs
|
UTF-8
| 213
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
use std::cell::Cell;
fn main() {
let my_cell = Cell::new(0);
println!("Initial cell value: {}", my_cell.get());
my_cell.set(my_cell.get() + 1);
println!("Final cell value: {}", my_cell.get());
}
| true
|
af8d8fc0ee1781e9b1d498e4908553765f90b45f
|
Rust
|
vrobweis/genius-rs
|
/src/album.rs
|
UTF-8
| 2,494
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
use serde::Deserialize;
use crate::annotation::Referent;
use crate::song::{Artist, SongPerformance};
use crate::user::UserMetadata;
#[derive(Deserialize, Debug)]
pub struct Album {
/// Path of the API.
pub api_path: String,
/// Number of comments.
/// > Only in `get_album`
pub comment_count: Option<u32>,
/// Cover art of the album.
pub cover_art_url: String,
/// Custom header image.
/// > Only in `get_album`
pub custom_header_image_url: Option<String>,
/// Full album title is: "`name` by `author`".
pub full_title: String,
/// Header image.
/// > Only in `get_album`
pub header_image_url: Option<String>,
/// Id of the album.
pub id: u32,
/// > Only in `get_album`
pub lock_state: Option<String>,
/// Name of the album.
pub name: String,
/// Number of pyongs in this album.
/// > Only in `get_album`
pub pyongs_count: Option<u32>,
/// Release date of the album in ISO 8601 date format.
/// > Only in `get_album`
pub release_date: Option<String>,
/// Release date of the album in struct format [`Date`].
/// > Only in `get_album`
pub release_date_components: Option<Date>,
/// Url of the album page.
pub url: String,
/// Current user metadata have all the permissions of the user to vote, edit etc. and some others stuffs.
/// > Only in `get_album`
pub current_user_metadata: Option<UserMetadata>,
/// Number of views in the album page.
/// > Only in `get_album`
#[serde(rename = "song_pageviews")]
pub album_pageviews: Option<u32>,
/// Album artist.
pub artist: Artist,
/// All cover arts of the album.
/// > Only in `get_album`
pub cover_arts: Option<Vec<CoverArt>>,
/// Annotations in this album.
/// > Only in `get_album`
pub description_annotation: Option<Referent>,
/// All the people who worked on this album.
/// > Only in `get_album`
pub song_performances: Option<Vec<SongPerformance>>,
}
#[derive(Deserialize, Debug)]
pub struct CoverArt {
/// If this art have annotations.
pub annotated: bool,
/// Path of the API
pub api_path: String,
/// Id of cover art.
pub id: u32,
/// Image of the art.
pub image_url: String,
/// Thumbnail image of the art.
pub thumbnail_image_url: String,
/// Page of the art.
pub url: String,
}
#[derive(Deserialize, Debug)]
pub struct Date {
pub year: u32,
pub month: u32,
pub day: u32,
}
| true
|
0d9b453ccf99da29a3241ba9cb7ff1dd1a1b5a6d
|
Rust
|
J0sh0nat0r/rust-aip-filtering
|
/src/ast.rs
|
UTF-8
| 12,523
| 3.109375
| 3
|
[] |
no_license
|
use std::fmt::{self, Display, Formatter};
use std::time::Duration;
use chrono::{DateTime, FixedOffset};
use itertools::Itertools;
use pest::error::Error;
use pest::iterators::{Pair, Pairs};
use pest::Parser;
use pest_derive::Parser;
#[derive(Parser)]
#[grammar = "grammar.pest"]
pub struct FilterParser;
impl FilterParser {
pub fn parse_str(input: &str) -> Result<Filter, Error<Rule>> {
let mut pairs: Pairs<Rule> = Self::parse(Rule::filter, input)?;
match pairs.next() {
None => Ok(Filter::None),
Some(pair) => Ok(Filter::Some(Expression::parse(pair).unwrap())),
}
}
}
pub type Filter<'a> = Option<Expression<'a>>;
#[derive(Debug)]
pub enum Value<'a> {
Bool(bool),
Duration(Duration),
Float(f64),
Int(i64),
String(&'a str),
Text(&'a str),
Timestamp(DateTime<FixedOffset>),
}
impl<'a> Value<'a> {
pub fn parse(pair: Pair<'a, Rule>) -> Result<Self, ()> {
debug_assert_eq!(pair.as_rule(), Rule::value);
let inner_pair = pair.into_inner().next().unwrap();
match inner_pair.as_rule() {
Rule::string => {
let str = inner_pair.into_inner().as_str();
if let Ok(value) = DateTime::parse_from_rfc3339(str) {
return Ok(Value::Timestamp(value));
}
return Ok(Value::String(str))
}
Rule::text => {
let str = inner_pair.as_str();
if let Ok(value) = str.parse() {
return Ok(Value::Bool(value));
}
if str.ends_with("s") {
if let Ok(secs) = str[..str.len() - 1].parse() {
return Ok(Value::Duration(Duration::from_secs_f64(secs)))
}
}
if let Ok(value) = str.parse() {
return Ok(Value::Int(value));
}
if let Ok(value) = str.parse() {
return Ok(Value::Float(value));
}
if let Ok(value) = DateTime::parse_from_rfc3339(str) {
return Ok(Value::Timestamp(value));
}
Ok(Value::Text(str))
}
_ => unreachable!()
}
}
pub fn string_repr(&self) -> String {
match self {
Self::Bool(value) => value.to_string(),
Self::Duration(value) => format!("{}s", value.as_secs_f64()),
Self::Float(value) => value.to_string(),
Self::Int(value) => value.to_string(),
Self::String(value) => value.to_string(),
Self::Text(value) => value.to_string(),
Self::Timestamp(value) => value.to_rfc3339(),
}
}
}
impl Display for Value<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Bool(value) => write!(f, "{}", value),
Self::Duration(value) => write!(f, "{}s", value.as_secs_f64()),
Self::Float(value) => write!(f, "{}", value),
Self::Int(value) => write!(f, "{}", value),
Self::String(value) => write!(f, "\"{}\"", value),
Self::Text(value) => write!(f, "{}", value),
Self::Timestamp(value) => write!(f, "\"{}\"", value.to_rfc3339()),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Comparator {
Eq,
Gt,
GtEq,
Has,
Lt,
LtEq,
Ne,
}
impl Comparator {
pub fn parse(pair: Pair<Rule>) -> Result<Self, ()> {
debug_assert_eq!(pair.as_rule(), Rule::comparator);
let inner_pair = pair.into_inner().next().unwrap();
Ok(match inner_pair.as_rule() {
Rule::eq => Self::Eq,
Rule::gt => Self::Gt,
Rule::gt_eq => Self::GtEq,
Rule::has => Self::Has,
Rule::lt => Self::Lt,
Rule::lt_eq => Self::LtEq,
Rule::ne => Self::Ne,
_ => return Err(()),
})
}
}
impl Display for Comparator {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Eq => " = ",
Self::Gt => " > ",
Self::GtEq => " >= ",
Self::Has => ":",
Self::Lt => " < ",
Self::LtEq => " <= ",
Self::Ne => " != ",
}
)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BinOp {
And,
Or,
}
impl Display for BinOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::And => " AND ",
Self::Or => " OR ",
}
)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UnOp {
Neg,
Not,
}
impl Display for UnOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Neg => "-",
Self::Not => "NOT ",
}
)
}
}
#[derive(Debug)]
pub enum Expression<'a> {
Binary {
lhs: Box<Expression<'a>>,
op: BinOp,
rhs: Box<Expression<'a>>,
},
FCall {
name: &'a str,
args: Vec<Expression<'a>>,
},
Member {
value: Value<'a>,
path: Vec<Value<'a>>,
},
Restriction {
lhs: Box<Expression<'a>>,
op: Comparator,
rhs: Box<Expression<'a>>,
},
Sequence(Vec<Expression<'a>>),
Unary {
op: UnOp,
rhs: Box<Expression<'a>>,
},
Value(Value<'a>),
}
impl<'a> Expression<'a> {
pub fn parse(pair: Pair<'a, Rule>) -> Result<Self, ()> {
debug_assert_eq!(pair.as_rule(), Rule::expression);
let mut inner = pair.into_inner();
let mut expr = Expression::parse_impl(inner.next().unwrap())?;
while let Some(rhs_pair) = inner.next() {
let rhs = Expression::parse_impl(rhs_pair)?;
expr = Expression::Binary {
lhs: Box::new(expr),
op: BinOp::And,
rhs: Box::new(rhs),
}
}
Ok(expr)
}
fn parse_impl(pair: Pair<'a, Rule>) -> Result<Self, ()> {
match pair.as_rule() {
Rule::expression => Self::parse(pair),
Rule::factor => {
let mut inner = pair.into_inner();
let mut expr = Expression::parse_impl(inner.next().unwrap())?;
while let Some(rhs_pair) = inner.next() {
let rhs = Expression::parse_impl(rhs_pair)?;
expr = Expression::Binary {
lhs: Box::new(expr),
op: BinOp::Or,
rhs: Box::new(rhs),
};
}
Ok(expr)
}
Rule::sequence => {
let mut inner = pair.into_inner();
match inner.clone().count() {
0 => Err(()),
1 => Expression::parse_impl(inner.next().unwrap()),
_ => {
let exprs = inner
.map(|pair| Expression::parse_impl(pair))
.try_collect()?;
Ok(Expression::Sequence(exprs))
}
}
}
Rule::term => {
let mut inner = pair.into_inner();
match inner.next().unwrap() {
inner_pair if inner_pair.as_rule() == Rule::negation => {
let op = match inner_pair.as_str() {
"-" => UnOp::Neg,
"NOT" => UnOp::Not,
_ => unreachable!(),
};
let term_pair = inner.next().unwrap();
let rhs = Expression::parse_impl(term_pair)?;
Ok(Expression::Unary {
op,
rhs: Box::new(rhs),
})
}
term_pair => Ok(Expression::parse_impl(term_pair)?),
}
}
Rule::restriction => {
let mut inner = pair.into_inner();
let lhs = Expression::parse_impl(inner.next().unwrap())?;
match inner.next() {
None => Ok(lhs),
Some(comparator_pair) => {
let op = Comparator::parse(comparator_pair)?;
let rhs = Expression::parse_impl(inner.next().unwrap())?;
Ok(Expression::Restriction {
lhs: Box::new(lhs),
op,
rhs: Box::new(rhs),
})
}
}
}
Rule::member => {
let mut inner = pair.into_inner();
let value = Value::parse(inner.next().unwrap())?;
match inner.peek() {
None => Ok(Expression::Value(value)),
Some(_) => {
let mut path = Vec::new();
for field_pair in inner {
// Should always be equal when coming from Pest
debug_assert_eq!(field_pair.as_rule(), Rule::field);
let inner_pair = field_pair.into_inner().next().unwrap();
path.push(parse_field(inner_pair)?);
}
Ok(Expression::Member { value, path })
}
}
}
Rule::function => {
let mut inner = pair.into_inner();
let name = {
let name_pair = inner.next().unwrap();
debug_assert_eq!(name_pair.as_rule(), Rule::function_name);
name_pair.as_str()
};
let args = inner
.next()
.map(|arg_list_pair| {
debug_assert_eq!(arg_list_pair.as_rule(), Rule::arg_list);
arg_list_pair
.into_inner()
.map(|pair| Expression::parse_impl(pair))
.try_collect()
})
.unwrap_or_else(|| Ok(Vec::new()))?;
Ok(Expression::FCall { name, args })
}
Rule::value => {
let inner_pair = pair.into_inner().next().unwrap();
Ok(Expression::Value(Value::parse(inner_pair)?))
}
_ => unimplemented!("{:?}", pair),
}
}
}
impl Display for Expression<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Binary { lhs, op, rhs } => write!(f, "({}{}{})", lhs, op, rhs),
Self::FCall { name, args } => {
let args_str = args
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(", ");
write!(f, "({}({}))", name, args_str)
}
Self::Member { value, path } => {
let path_str = path
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(".");
write!(f, "({}.{})", value, path_str)
}
Self::Restriction { lhs, op, rhs } => write!(f, "({}{}{})", lhs, op, rhs),
Self::Sequence(expressions) => {
let joined_str = expressions
.iter()
.map(|expr| format!("{}", expr))
.collect::<Vec<String>>()
.join(" ");
write!(f, "({})", joined_str)
}
Self::Unary { op, rhs } => write!(f, "({}{})", op, rhs),
Self::Value(value) => value.fmt(f),
}
}
}
fn parse_field(pair: Pair<Rule>) -> Result<Value, ()> {
match pair.as_rule() {
Rule::value => Value::parse(pair),
Rule::keyword => Ok(Value::Text(pair.as_str())),
_ => Err(()),
}
}
| true
|
0ab9c7449413e929cdeccd1452a8d5c14bd6887f
|
Rust
|
quininer/aes
|
/src/mode/ecb.rs
|
UTF-8
| 1,219
| 2.890625
| 3
|
[] |
no_license
|
use ::AES;
use ::utils::padding::Padding;
use ::cipher::{
DecryptFail,
SingleBlockEncrypt, SingleBlockDecrypt,
BlockEncrypt, BlockDecrypt
};
#[derive(Clone, Debug)]
pub struct Ecb<C> {
cipher: C
}
impl Ecb<AES> {
pub fn new(key: &[u8]) -> Ecb<AES> {
Ecb { cipher: AES::new(key) }
}
}
impl<C> BlockEncrypt for Ecb<C> where C: SingleBlockEncrypt {
fn bs(&self) -> usize { C::bs() }
fn encrypt<P: Padding>(&mut self, data: &[u8]) -> Vec<u8> {
P::padding(data, self.bs()).chunks(self.bs())
.map(|b| self.cipher.encrypt(b))
.fold(Vec::new(), |mut sum, mut next| {
sum.append(&mut next);
sum
})
}
}
impl<C> BlockDecrypt for Ecb<C> where C: SingleBlockDecrypt {
fn bs(&self) -> usize { C::bs() }
fn decrypt<P: Padding>(&mut self, data: &[u8]) -> Result<Vec<u8>, DecryptFail> {
P::unpadding(
&data.chunks(self.bs())
.map(|b| self.cipher.decrypt(b))
.fold(Vec::new(), |mut sum, mut next| {
sum.append(&mut next);
sum
}),
self.bs()
).map_err(|err| err.into())
}
}
| true
|
93ee4d09a663b58577314f57bf319770d0c0de9f
|
Rust
|
chikuchikugonzalez/varsun
|
/src/mswin.rs
|
UTF-8
| 3,753
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
// -*- coding: utf-8 -*-
// vi: set sts=4 ts=4 sw=4 et ft=rust:
//! Provides MS-Windows style substition.
//!
//! MS-Winodws style substition is `%var%` format strings.
//! You can see on COMMAND PROMPT (not PowerShell).
/// Parse src and substitute found variables with result of `mapfn`.
///
/// # Examples
///
/// ```
/// use varsun::mswin::substitute;
///
/// let src = "foo is %foo%.";
/// let res = substitute(src, |name: &str| -> Option<String> {
/// match name {
/// "foo" => Some("FOO!!".to_string()),
/// _ => None, // If None returns, variable replaces with "" (empty string).
/// }
/// });
/// ```
pub fn substitute<F>(src: &str, mapfn: F) -> String where F: Fn(&str) -> Option<String> {
let mut dst = String::new();
let mut chs = src.chars();
// Temporary variables.
let mut varname = String::new();
let mut started = false;
// Check each characters.
while let Some(ch) = chs.next() {
if ch == '%' {
if started {
// Reach end of varname section.
// Call mapping-function.
if let Some(val) = mapfn(varname.as_str()) {
// Push raw value.
dst.push_str(val.as_str());
// Leave varname section.
started = false;
} else {
// Push Back Variable.
dst.push('%');
dst.push_str(varname.as_str());
}
// Reset varname.
varname.clear();
} else {
// Enter varname section.
started = true;
// Continue to Next.
continue;
}
} else {
if started {
// Part of varname.
varname.push(ch);
} else {
// Part of text.
dst.push(ch);
}
}
}
// Push Back vaname if cursor placed in varname section yet.
if started {
dst.push('%');
dst.push_str(varname.as_str());
// Reset
varname.clear();
}
return dst;
}
/// Substitute environment variable by Windows format.
pub fn substenvar(src: &str) -> String {
return self::substitute(src, super::envar);
}
#[cfg(test)]
mod tests {
fn mapfn(name: &str) -> Option<String> {
match name {
"foo" => Some("foo!!".to_string()),
"bar" => Some("!bar!".to_string()),
"baz" => Some("%baz%".to_string()),
_ => Some("( ・ω・)?".to_string()),
}
}
#[test]
fn substitute_basic() {
assert_eq!("foo!!", super::substitute("%foo%", mapfn));
assert_eq!("!bar!", super::substitute("%bar%", mapfn));
assert_eq!("%baz%", super::substitute("%baz%", mapfn));
assert_eq!("foo is foo!!", super::substitute("foo is %foo%", mapfn));
assert_eq!("!bar! not ( ・ω・)?", super::substitute("%bar% not %foobar%", mapfn));
assert_eq!("foo!!!bar!%baz%", super::substitute("%foo%%bar%%baz%", mapfn));
}
//#[bench]
//fn substitute_bench(b: &mut Bencher) {
// b.iter(|| super::substitute("%foo%%bar%%baz%", mapfn));
//}
#[test]
fn substenvar_basic() {
::std::env::set_var("FOO", "foo, foo!");
::std::env::set_var("BAR", "foobar");
assert_eq!("foo, foo!", super::substenvar("%FOO%"));
assert_eq!("foobar says 'foo, foo!'", super::substenvar("%BAR% says '%FOO%'"));
assert_eq!("%BAZ%", super::substenvar("%BAZ%"));
}
}
| true
|
0d6e7fa95ae4b163993a546dc830349e529ecf0d
|
Rust
|
kaikalii/smore
|
/src/lib.rs
|
UTF-8
| 7,820
| 2.953125
| 3
|
[] |
no_license
|
use std::f32::EPSILON;
pub trait Vectorize<const N: usize> {
fn vectorize(&self) -> [f32; N];
}
pub trait Devectorize<const N: usize>: Vectorize<N> {
fn devectorize(vector: [f32; N]) -> Self;
}
impl Vectorize<1> for f32 {
fn vectorize(&self) -> [f32; 1] {
[*self]
}
}
impl Devectorize<1> for f32 {
fn devectorize(vector: [f32; 1]) -> Self {
vector[0]
}
}
impl Vectorize<1> for f64 {
fn vectorize(&self) -> [f32; 1] {
[*self as f32]
}
}
impl Devectorize<1> for f64 {
fn devectorize(vector: [f32; 1]) -> Self {
vector[0] as f64
}
}
impl<const N: usize> Vectorize<N> for [f32; N] {
fn vectorize(&self) -> [f32; N] {
*self
}
}
impl<const N: usize> Devectorize<N> for [f32; N] {
fn devectorize(vector: [f32; N]) -> Self {
vector
}
}
impl<const N: usize> Vectorize<N> for [f64; N] {
fn vectorize(&self) -> [f32; N] {
let mut vectorized = [0.0; N];
for (a, b) in vectorized.iter_mut().zip(self) {
*a = *b as f32;
}
vectorized
}
}
impl<const N: usize> Devectorize<N> for [f64; N] {
fn devectorize(vector: [f32; N]) -> Self {
let mut devectorized = [0.0; N];
for (a, b) in devectorized.iter_mut().zip(&vector) {
*a = *b as f64;
}
devectorized
}
}
pub struct Smore<const A: usize, const B: usize> {
mappings: Vec<([f32; A], [f32; B])>,
}
impl<const A: usize, const B: usize> Default for Smore<A, B> {
fn default() -> Self {
Smore::new()
}
}
impl<const A: usize, const B: usize> Smore<A, B> {
pub fn new() -> Self {
Smore {
mappings: Vec::new(),
}
}
pub fn map<AT, BT>(&mut self, input: &AT, output: &BT)
where
AT: Vectorize<A>,
BT: Devectorize<B>,
{
self.mappings.push((input.vectorize(), output.vectorize()));
}
pub fn eval<W>(&self, weight: W) -> Evaluator<W, A, B> {
Evaluator {
weight,
smore: self,
}
}
}
pub struct Evaluator<'a, W, const A: usize, const B: usize> {
weight: W,
smore: &'a Smore<A, B>,
}
impl<'a, W, const A: usize, const B: usize> Evaluator<'a, W, A, B> {
pub fn get<AT, BT>(&self, input: &AT) -> BT
where
W: WeightFn<A>,
AT: Vectorize<A>,
BT: Devectorize<B>,
{
let mut val_sum = [0.0; B];
let mut weight_sum = 0.0;
let input = input.vectorize();
for (a, b) in &self.smore.mappings {
let weight = if let Some(weight) = self.weight.weight(&input, a) {
weight
} else {
return BT::devectorize(*b);
};
weight_sum += weight;
let mut val = *b;
mul_assign(&mut val, weight);
add_assign(&mut val_sum, &val);
}
div_assign(&mut val_sum, weight_sum);
BT::devectorize(val_sum)
}
}
pub trait WeightFn<const N: usize> {
fn weight(&self, target: &[f32; N], other: &[f32; N]) -> Option<f32>;
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Exponential(pub f32);
impl<const N: usize> WeightFn<N> for Exponential {
fn weight(&self, target: &[f32; N], other: &[f32; N]) -> Option<f32> {
let mut sum = 0.0;
for (a, b) in target.iter().zip(other) {
sum += (a - b).abs().powf(self.0);
}
if sum < EPSILON {
return None;
}
Some(1.0 / sum)
}
}
impl Exponential {
pub fn find_best<const A: usize, const B: usize>(
training: &Smore<A, B>,
target: &Smore<A, B>,
min: f32,
max: f32,
step: f32,
) -> Exponential {
let mut exp = Exponential(min);
let mut best = exp;
let mut best_error = f32::MAX;
while exp.0 <= max {
let eval = training.eval(exp);
let avg_error = target
.mappings
.iter()
.filter_map(|(input, output)| Exponential(2.0).weight(output, &eval.get(input)))
.map(|weight| 1.0 / weight)
.sum::<f32>()
/ target.mappings.len() as f32;
if avg_error < best_error {
best = exp;
best_error = avg_error;
}
exp.0 += step;
}
best
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Threshold<T, const N: usize> {
inner: T,
threshold: f32,
}
impl<T, const N: usize> Threshold<T, N>
where
T: WeightFn<N>,
{
pub fn new<I>(inner: T, a: &I, b: &I) -> Self
where
I: Vectorize<N>,
{
let threshold = inner.weight(&a.vectorize(), &b.vectorize()).unwrap_or(0.0);
Threshold { inner, threshold }
}
}
impl<T, const N: usize> WeightFn<N> for Threshold<T, N>
where
T: WeightFn<N>,
{
fn weight(&self, target: &[f32; N], other: &[f32; N]) -> Option<f32> {
let weight = self.inner.weight(target, other)?;
Some(if weight < self.threshold { 0.0 } else { weight })
}
}
fn add_assign<const N: usize>(a: &mut [f32; N], b: &[f32; N]) {
for (a, b) in a.iter_mut().zip(b) {
*a += *b;
}
}
fn mul_assign<const N: usize>(v: &mut [f32; N], d: f32) {
for i in v {
*i *= d;
}
}
fn div_assign<const N: usize>(v: &mut [f32; N], d: f32) {
for i in v {
*i /= d;
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn xor() {
let solutions = [
([0f32, 0.0], 0f32),
([0.0, 1.0], 1.0),
([1.0, 0.0], 1.0),
([1.0, 1.0], 0.0),
];
let mut smore = Smore::new();
for (input, output) in &solutions {
smore.map(input, output);
}
const ERROR: f32 = 0.01;
let eval = smore.eval(Exponential(2.0));
for (input, output) in &solutions {
let errored_input = [input[0] + ERROR, input[1] - ERROR];
let errored_output: f32 = eval.get(&errored_input);
println!("{:?} -> {}", errored_input, errored_output);
assert!((output - errored_output).abs() < ERROR);
}
}
#[test]
fn add() {
const RESOLUTION: i32 = 8;
const MIN: i32 = -1000;
const MAX: i32 = 1000;
let training = (MIN / RESOLUTION..MAX / RESOLUTION)
.map(|i| (i * RESOLUTION) as f32)
.flat_map(|i| {
(MIN / RESOLUTION..MAX / RESOLUTION)
.map(|j| (j * RESOLUTION) as f32)
.map(move |j| ([i, j], (i + j)))
});
let mut smore = Smore::new();
for (input, output) in training {
smore.map(&input, &output);
}
let test_data = [
([0.5f32, 0.5], 1f32),
([23.0, 7.0], 30.0),
([91.0, 123.0], 214.0),
([111.0, 222.0], 333.0),
([-123.0, -456.0], -579.0),
([-123.0, 456.0], 333.0),
([107.0, -2.0], 105.0),
];
let mut test = Smore::new();
for (input, output) in &test_data {
test.map(input, output);
}
let weight = Exponential::find_best(&smore, &test, 1.0, 5.0, 0.1);
println!("{:?}", weight);
let eval = smore.eval(weight);
for (input, output) in &test_data {
let evaled: f32 = eval.get(input);
let error = (*output - evaled).abs();
println!(
"{} + {} = {} | error: {}",
input[0], input[1], evaled, error
);
assert!(error < RESOLUTION as f32);
}
let mut i = 0.0;
while i < 100.0 {
println!("{}", i);
i = eval.get(&[i, 6.0]);
}
}
}
| true
|
1232d9c02f168950e5e9ed338fc694223f02dfaf
|
Rust
|
sepiggy/imooc-517
|
/ch04/demo09function/src/main.rs
|
UTF-8
| 203
| 3.453125
| 3
|
[] |
no_license
|
fn fib(n:u64) -> u64 {
match n {
0 => 0,
1 => 1,
_ => fib(n-1) + fib(n-2),
}
}
fn main() {
println!("fib(5) = {}", fib(5));
println!("fib(10) = {}", fib(10));
}
| true
|
2a685aa3263d3491a1746b5f13e15b87c183707e
|
Rust
|
lordy1992/REMulator
|
/src/cpu.rs
|
UTF-8
| 46,049
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
use crate::address_space::AddressSpace;
#[derive(Debug)]
pub struct StatusRegister {
carry_flag: bool,
zero_flag: bool,
interrupt_disable_flag: bool,
decimal_flag: bool,
break_flag_1: bool,
break_flag_2: bool,
overflow_flag: bool,
negative_flag: bool
}
impl StatusRegister {
pub fn new() -> StatusRegister {
// Initialize to 0xFD, the value of the status register when reset.
// 0xFD == 1111 1101 ==> All 1 except zero_flag
StatusRegister { carry_flag: false, zero_flag: false, interrupt_disable_flag: true,
decimal_flag: false, break_flag_1: false, break_flag_2: true,
overflow_flag: false, negative_flag: false}
}
pub fn as_bytes(&self) -> u8 {
(self.carry_flag as u8) | ((self.zero_flag as u8) << 1) |
((self.interrupt_disable_flag as u8) << 2) | ((self.decimal_flag as u8) << 3) |
((self.break_flag_1 as u8) << 4) | ((self.break_flag_2 as u8) << 5) |
((self.overflow_flag as u8) << 6) | ((self.negative_flag as u8) << 7)
}
pub fn from_bytes(&self, bytes: u8) -> StatusRegister {
let carry_flag = (bytes & 0x01) != 0;
let zero_flag = ((bytes >> 1) & 0x01) != 0;
let interrupt_disable_flag = ((bytes >> 2) & 0x01) != 0;
let decimal_flag = ((bytes >> 3) & 0x01) != 0;
let break_flag_1 = ((bytes >> 4) & 0x01) != 0;
let break_flag_2 = ((bytes >> 5) & 0x01) != 0;
let overflow_flag = ((bytes >> 6) & 0x01) != 0;
let negative_flag = ((bytes >> 7) & 0x01) != 0;
StatusRegister { carry_flag, zero_flag, interrupt_disable_flag, decimal_flag, break_flag_1,
break_flag_2, overflow_flag, negative_flag }
}
}
type Cycles = usize;
type Opcode = u8;
type OpcodeToInstrInfo<'a> = HashMap<Opcode, (&'a str, Opcode, Cycles, AddressingMode)>;
pub struct CPU<'a> {
pc: u16,
acc: u8,
x: u8,
y: u8,
status: StatusRegister,
sp: u8,
opcode_map: OpcodeToInstrInfo<'a>,
address_space: &'a mut AddressSpace<'a>,
total_cycles: usize
}
impl<'a> std::fmt::Debug for CPU<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("PC:{:04X?} A:{:02X?} X:{:02X?} Y:{:02X?} P:{:02X?} SP:{:02X?}",
self.pc, self.acc, self.x, self.y, self.status.as_bytes(), self.sp))
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum AddressingMode {
Immediate,
Relative,
Accumulator,
Absolute, AbsoluteX, AbsoluteY,
ZeroPage, ZeroPageX, ZeroPageY,
Indirect, IndirectX, IndirectY,
Implicit
}
use AddressingMode::*;
use std::fmt::Formatter;
const OPCODES : [(&str, Opcode, Cycles, AddressingMode); 240] = [
("BRK", 0x00, 7, Implicit), ("ORA", 0x01, 6, IndirectX), ("ORA", 0x05, 3, ZeroPage),
("ASL", 0x06, 5, ZeroPage), ("PHP", 0x08, 3, Implicit), ("ORA", 0x09, 2, Immediate),
("ASL", 0x0A, 2, Accumulator), ("ORA", 0x0D, 4, Absolute), ("ASL", 0x0E, 6, Absolute),
("BPL", 0x10, 2, Relative), ("ORA", 0x11, 5, IndirectY), ("ORA", 0x15, 4, ZeroPageX),
("ASL", 0x16, 6, ZeroPageX), ("CLC", 0x18, 2, Implicit), ("ORA", 0x19, 4, AbsoluteY),
("ORA", 0x1D, 4, AbsoluteX), ("ASL", 0x1E, 7, AbsoluteX), ("JSR", 0x20, 6, Absolute),
("AND", 0x21, 6, IndirectX), ("BIT", 0x24, 3, ZeroPage), ("AND", 0x25, 3, ZeroPage),
("ROL", 0x26, 5, ZeroPage), ("PLP", 0x28, 4, Implicit), ("AND", 0x29, 2, Immediate),
("ROL", 0x2A, 2, Accumulator), ("BIT", 0x2C, 4, Absolute), ("AND", 0x2D, 4, Absolute),
("ROL", 0x2E, 6, Absolute), ("BMI", 0x30, 2, Relative), ("AND", 0x31, 5, IndirectY),
("AND", 0x35, 4, ZeroPageX), ("ROL", 0x36, 6, ZeroPageX), ("SEC", 0x38, 2, Implicit),
("AND", 0x39, 4, AbsoluteY), ("AND", 0x3D, 4, AbsoluteX), ("ROL", 0x3E, 7, AbsoluteX),
("RTI", 0x40, 6, Implicit), ("EOR", 0x41, 6, IndirectX), ("EOR", 0x45, 3, ZeroPage),
("LSR", 0x46, 5, ZeroPage), ("PHA", 0x48, 3, Implicit), ("EOR", 0x49, 2, Immediate),
("LSR", 0x4A, 2, Accumulator), ("JMP", 0x4C, 3, Absolute), ("EOR", 0x4D, 4, Absolute),
("LSR", 0x4E, 6, Absolute), ("BVC", 0x50, 2, Relative), ("EOR", 0x51, 5, IndirectY),
("EOR", 0x55, 4, ZeroPageX), ("LSR", 0x56, 6, ZeroPageX), ("CLI", 0x58, 2, Implicit),
("EOR", 0x59, 4, AbsoluteY), ("EOR", 0x5D, 4, AbsoluteX), ("LSR", 0x5E, 7, AbsoluteX),
("RTS", 0x60, 6, Implicit), ("ADC", 0x61, 6, IndirectX), ("ADC", 0x65, 3, ZeroPage),
("ROR", 0x66, 5, ZeroPage), ("PLA", 0x68, 4, Implicit), ("ADC", 0x69, 2, Immediate),
("ROR", 0x6A, 2, Accumulator), ("JMP", 0x6C, 5, Indirect), ("ADC", 0x6D, 4, Absolute),
("ROR", 0x6E, 6, Absolute), ("BVS", 0x70, 2, Relative), ("ADC", 0x71, 5, IndirectY),
("ADC", 0x75, 4, ZeroPageX), ("ROR", 0x76, 6, ZeroPageX), ("SEI", 0x78, 2, Implicit),
("ADC", 0x79, 4, AbsoluteY), ("ADC", 0x7D, 4, AbsoluteX), ("ROR", 0x7E, 7, AbsoluteX),
("STA", 0x81, 6, IndirectX), ("STY", 0x84, 3, ZeroPage), ("STA", 0x85, 3, ZeroPage),
("STX", 0x86, 3, ZeroPage), ("DEY", 0x88, 2, Implicit), ("TXA", 0x8A, 2, Implicit),
("STY", 0x8C, 4, Absolute), ("STA", 0x8D, 4, Absolute), ("STX", 0x8E, 4, Absolute),
("BCC", 0x90, 2, Relative), ("STA", 0x91, 6, IndirectY), ("STY", 0x94, 4, ZeroPageX),
("STA", 0x95, 4, ZeroPageX), ("STX", 0x96, 4, ZeroPageY), ("TYA", 0x98, 2, Implicit),
("STA", 0x99, 5, AbsoluteY), ("TXS", 0x9A, 2, Implicit), ("STA", 0x9D, 5, AbsoluteX),
("LDY", 0xA0, 2, Immediate), ("LDA", 0xA1, 6, IndirectX), ("LDX", 0xA2, 2, Immediate),
("LDY", 0xA4, 3, ZeroPage), ("LDA", 0xA5, 3, ZeroPage), ("LDX", 0xA6, 3, ZeroPage),
("TAY", 0xA8, 2, Implicit), ("LDA", 0xA9, 2, Immediate), ("TAX", 0xAA, 2, Implicit),
("LDY", 0xAC, 4, Absolute), ("LDA", 0xAD, 4, Absolute), ("LDX", 0xAE, 4, Absolute),
("BCS", 0xB0, 2, Relative), ("LDA", 0xB1, 5, IndirectY), ("LDY", 0xB4, 4, ZeroPageX),
("LDA", 0xB5, 4, ZeroPageX), ("LDX", 0xB6, 4, ZeroPageY), ("CLV", 0xB8, 2, Implicit),
("LDA", 0xB9, 4, AbsoluteY), ("TSX", 0xBA, 2, Implicit), ("LDY", 0xBC, 4, AbsoluteX),
("LDA", 0xBD, 4, AbsoluteX), ("LDX", 0xBE, 4, AbsoluteY), ("CPY", 0xC0, 2, Immediate),
("CMP", 0xC1, 6, IndirectX), ("CPY", 0xC4, 3, ZeroPage), ("CMP", 0xC5, 3, ZeroPage),
("DEC", 0xC6, 5, ZeroPage), ("INY", 0xC8, 2, Implicit), ("CMP", 0xC9, 2, Immediate),
("DEX", 0xCA, 2, Implicit), ("CPY", 0xCC, 4, Absolute), ("CMP", 0xCD, 4, Absolute),
("DEC", 0xCE, 6, Absolute), ("BNE", 0xD0, 2, Relative), ("CMP", 0xD1, 5, IndirectY),
("CMP", 0xD5, 4, ZeroPageX), ("DEC", 0xD6, 6, ZeroPageX), ("CLD", 0xD8, 2, Implicit),
("CMP", 0xD9, 4, AbsoluteY), ("CMP", 0xDD, 4, AbsoluteX), ("DEC", 0xDE, 7, AbsoluteX),
("CPX", 0xE0, 2, Immediate), ("SBC", 0xE1, 6, IndirectX), ("CPX", 0xE4, 3, ZeroPage),
("SBC", 0xE5, 3, ZeroPage), ("INC", 0xE6, 5, ZeroPage), ("INX", 0xE8, 2, Implicit),
("SBC", 0xE9, 2, Immediate), ("NOP", 0xEA, 2, Implicit), ("CPX", 0xEC, 4, Absolute),
("SBC", 0xED, 4, Absolute), ("INC", 0xEE, 6, Absolute), ("BEQ", 0xF0, 2, Relative),
("SBC", 0xF1, 5, IndirectY), ("SBC", 0xF5, 4, ZeroPageX), ("INC", 0xF6, 6, ZeroPageX),
("SED", 0xF8, 2, Implicit), ("SBC", 0xF9, 4, AbsoluteY), ("SBC", 0xFD, 4, AbsoluteX),
("INC", 0xFE, 7, AbsoluteX),
// Unofficial opcodes
("ASO", 0x0F, 6, Absolute), ("ASO", 0x1F, 7, AbsoluteX), ("ASO", 0x1B, 7, AbsoluteY),
("ASO", 0x07, 5, ZeroPage), ("ASO", 0x17, 6, ZeroPageX), ("ASO", 0x03, 8, IndirectX),
("ASO", 0x13, 8, IndirectY),
("NOP", 0x04, 3, Immediate), ("NOP", 0x44, 3, Immediate), ("NOP", 0x64, 3, Immediate),
("SKW", 0x0C, 4, Absolute), ("NOP", 0x14, 4, Immediate), ("NOP", 0x34, 4, Immediate),
("NOP", 0x54, 4, Immediate), ("NOP", 0x74, 4, Immediate), ("NOP", 0xD4, 4, Immediate),
("NOP", 0xF4, 4, Immediate), ("NOP", 0x1A, 2, Implicit), ("NOP", 0x3A, 2, Implicit),
("NOP", 0x5A, 2, Implicit), ("NOP", 0x7A, 2, Implicit), ("NOP", 0xDA, 2, Implicit),
("NOP", 0xFA, 2, Implicit), ("NOP", 0x80, 2, Immediate), ("SKW", 0x1C, 4, AbsoluteX),
("SKW", 0x3C, 4, AbsoluteX), ("SKW", 0x5C, 4, AbsoluteX), ("SKW", 0x7C, 4, AbsoluteX),
("SKW", 0xDC, 4, AbsoluteX), ("SKW", 0xFC, 4, AbsoluteX),
("RLA", 0x2F, 6, Absolute), ("RLA", 0x3F, 7, AbsoluteX), ("RLA", 0x3B, 7, AbsoluteY),
("RLA", 0x27, 5, ZeroPage), ("RLA", 0x37, 6, ZeroPageX), ("RLA", 0x23, 8, IndirectX),
("RLA", 0x33, 8, IndirectY),
("LSE", 0x4F, 6, Absolute), ("LSE", 0x5F, 7, AbsoluteX), ("LSE", 0x5B, 7, AbsoluteY),
("LSE", 0x47, 5, ZeroPage), ("LSE", 0x57, 6, ZeroPageX), ("LSE", 0x43, 8, IndirectX),
("LSE", 0x53, 8, IndirectY),
("RRA", 0x6F, 6, Absolute), ("RRA", 0x7F, 7, AbsoluteX), ("RRA", 0x7B, 7, AbsoluteY),
("RRA", 0x67, 5, ZeroPage), ("RRA", 0x77, 6, ZeroPageX), ("RRA", 0x63, 8, IndirectX),
("RRA", 0x73, 8, IndirectY),
("AXS", 0x8F, 4, Absolute), ("AXS", 0x87, 3, ZeroPage), ("AXS", 0x97, 4, ZeroPageY),
("AXS", 0x83, 6, IndirectX),
("LAX", 0xAF, 4, Absolute), ("LAX", 0xBF, 4, AbsoluteY), ("LAX", 0xA7, 3, ZeroPage),
("LAX", 0xB7, 4, ZeroPageY), ("LAX", 0xA3, 6, IndirectX), ("LAX", 0xB3, 5, IndirectY),
("DCM", 0xCF, 6, Absolute), ("DCM", 0xDF, 7, AbsoluteX), ("DCM", 0xDB, 7, AbsoluteY),
("DCM", 0xC7, 5, ZeroPage), ("DCM", 0xD7, 6, ZeroPageX), ("DCM", 0xC3, 8, IndirectX),
("DCM", 0xD3, 8, IndirectY),
("INS", 0xEF, 6, Absolute), ("INS", 0xFF, 7, AbsoluteX), ("INS", 0xFB, 7, AbsoluteY),
("INS", 0xE7, 5, ZeroPage), ("INS", 0xF7, 6, ZeroPageX), ("INS", 0xE3, 8, IndirectX),
("INS", 0xF3, 8, IndirectY),
("ALR", 0x4B, 2, Immediate), ("ARR", 0x6B, 2, Immediate), ("XAA", 0x8B, 2, Immediate),
("OAL", 0xAB, 2, Immediate), ("SAX", 0xCB, 2, Immediate), ("TAS", 0x9B, 5, AbsoluteY),
("SAY", 0x9C, 5, AbsoluteX), ("XAS", 0x9E, 5, AbsoluteY), ("AXA", 0x9F, 5, AbsoluteY),
("AXA", 0x93, 6, IndirectY), ("ANC", 0x2B, 2, Immediate), ("ANC", 0x0B, 2, Immediate),
("LAS", 0xBB, 4, AbsoluteY), ("SBC", 0xEB, 2, Immediate)
];
const OPCODES_EXTRA_CYCLES_ON_PAGE: [u8; 32] = [
0x3D, 0x39, 0x31, 0x7D, 0x79, 0x71, 0xDD, 0xD9, 0xD1, 0x5D, 0x59, 0x51, 0xBD, 0xB9, 0xB1, 0xBE,
0xBC, 0x1D, 0x19, 0x11, 0xFD, 0xF9, 0xF1, 0xBF, 0xB3, 0xBB, 0x1C, 0x3C, 0x5C, 0x7C, 0xDC, 0xFC
];
const BRANCH_EXTRA_CYCLES_ON_PAGE: [u8; 8] = [
0x90, 0xB0, 0xF0, 0x30, 0xD0, 0x10, 0x50, 0x70
];
impl<'a> CPU<'a> {
pub fn new(address_space: &'a mut AddressSpace<'a>) -> CPU<'a> {
// TODO: Support other memory mappers...
// Abstract away the following into another component...
// The reset vector is at 0xFFFC and 0xFFFD in the CPU memory.
let pc = address_space.read_data_u16(0xFFFC);
let opcode_map: HashMap<Opcode, (&str, Opcode, Cycles, AddressingMode)> =
OPCODES.iter().map(|t| (t.1, *t)).collect();
CPU { pc, acc: 0, x: 0, y: 0, status: StatusRegister::new(), sp: 0xFF,
opcode_map, address_space, total_cycles: 7 }
}
fn address_mode_to_register(&self, address_mode: AddressingMode) -> u8 {
match address_mode {
AbsoluteX | ZeroPageX => self.x,
AbsoluteY | ZeroPageY => self.y,
ZeroPage => 0,
_ => panic!("No other address modes match to a register")
}
}
fn check_page_boundary_crossed(&self, address_mode: AddressingMode) -> usize {
match address_mode {
AbsoluteX | AbsoluteY => {
let reg = self.address_mode_to_register(address_mode);
let addr = self.address_space.read_data_u16(self.pc.wrapping_add(1));
let addr_low = addr as u8;
let addr_added = ((addr_low as u16) + (reg as u16)) & 0xFF;
if addr_added < reg as u16 {
// Wrapped around (have to carry to the high byte). This will result in an
// extra cycle.
1
} else {
0
}
}
IndirectY => {
let zero_page_addr =
self.address_space.read_data_u8(self.pc.wrapping_add(1));
let addr = self.address_space.read_data_u16(zero_page_addr as u16);
let addr_low = addr as u8;
let addr_added = ((addr_low as u16) + (self.y as u16)) & 0xFF;
if addr_added < self.y as u16 {
// Wrapped around (have to carry to the high byte). This will result in an
// extra cycle.
1
} else {
0
}
}
Relative => {
let src = self.address_space.read_data_u8(self.pc.wrapping_add(1));
let inc_pc = self.pc.wrapping_add(self.num_bytes_from_mode(address_mode));
if (inc_pc & 0xFF00) != (self.rel_address(src)
.wrapping_add(self.num_bytes_from_mode(address_mode)) & 0xFF00) {
1
} else {
0
}
}
_ => 0
}
}
fn get_addr_by_address_mode(&self, address_mode: AddressingMode) -> u16 {
match address_mode {
Absolute => {
self.address_space.read_data_u16(self.pc.wrapping_add(1))
}
AbsoluteX | AbsoluteY => {
let reg = self.address_mode_to_register(address_mode);
let addr = self.address_space.read_data_u16(self.pc.wrapping_add(1));
let val = addr.wrapping_add(reg as u16);
val
}
ZeroPage | ZeroPageX | ZeroPageY => {
let addr =
self.address_space.read_data_u8(self.pc.wrapping_add(1)) as u16;
// self.address_mode_to_register returns 0 if ZeroPage
let added = addr.wrapping_add(self.address_mode_to_register(address_mode) as u16);
added & 0x00FF
}
IndirectX => {
let addr = self.address_space.read_data_u8(self.pc.wrapping_add(1));
let with_x = addr.wrapping_add(self.x);
let target = self.address_space.read_u16_zero_page(with_x);
target
}
IndirectY => {
let zero_page_addr =
self.address_space.read_data_u8(self.pc.wrapping_add(1));
let addr = self.address_space.read_u16_zero_page(zero_page_addr);
let with_y = addr.wrapping_add(self.y as u16);
with_y
}
_ => {
panic!("No other address modes support returning address to write data to");
}
}
}
fn get_src_by_address_mode(&self, address_mode: AddressingMode) -> u8 {
match address_mode {
Immediate | Relative => {
self.address_space.read_data_u8(self.pc.wrapping_add(1))
}
Absolute | AbsoluteX | AbsoluteY | ZeroPage | ZeroPageX | ZeroPageY | IndirectX
| IndirectY => {
let addr = self.get_addr_by_address_mode(address_mode);
self.address_space.read_data_u8(addr)
}
Accumulator => {
self.acc
}
Indirect => {
panic!("Indirect address mode does not return a u8 value");
}
Implicit => {
panic!("Implicit mode requires no operands");
}
}
}
fn num_bytes_from_mode(&self, address_mode: AddressingMode) -> u16 {
match address_mode {
Accumulator | Implicit => 1,
Absolute | AbsoluteX | AbsoluteY | Indirect => 3,
_ => 2
}
}
pub fn execute_next_instruction(&mut self) -> Cycles {
let opcode = self.address_space.read_data_u8(self.pc);
let instruction_info = self.opcode_map.get(&opcode).unwrap();
let operand_start = self.pc.wrapping_add(1);
let next_byte = self.address_space.read_data_u8(operand_start);
let next_two_bytes = self.address_space.read_data_u16(operand_start);
println!("{} {:<30} {:?} CYC:{} Stack (top 6): {:02X} {:02X} {:02X} {:02X} {:02X} {:02X}",
self.print_machine_code(instruction_info, next_byte, next_two_bytes),
self.print_assembly_command(instruction_info, next_byte, next_two_bytes),
self, self.total_cycles,
self.peek(1), self.peek(2), self.peek(3), self.peek(4), self.peek(5), self.peek(6));
let addr_mode = instruction_info.3;
let page_cycles = if OPCODES_EXTRA_CYCLES_ON_PAGE.contains(&instruction_info.1) {
self.check_page_boundary_crossed(addr_mode)
} else {
0
};
let mut cycles = instruction_info.2 + page_cycles;
let next_pc: u16 = match instruction_info.0 {
"ADC" => {
self.adc(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"ALR" => {
self.and(addr_mode);
self.lsr(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"ANC" => {
let src = self.and(addr_mode);
self.status.carry_flag = ((src >> 7) & 1) == 1;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"AND" => {
self.and(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"ARR" => {
self.and(addr_mode);
self.ror(Accumulator);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"ASL" => {
self.asl(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"ASO" => {
self.asl(addr_mode);
self.ora(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"AXA" => {
let target_addr = self.get_addr_by_address_mode(addr_mode);
let target_hi = (target_addr >> 8) as u8;
let final_result = (target_hi.wrapping_add(1)) & self.x & self.acc;
self.address_space.write_data(target_addr, final_result);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"AXS" => {
let anded_val = self.acc & self.x;
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), anded_val);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"BCC" => {
let (add_cycles, new_pc) =
self.branch_on_condition(&|| !self.status.carry_flag, addr_mode, &instruction_info.1);
cycles += add_cycles;
new_pc
}
"BCS" => {
let (add_cycles, new_pc) =
self.branch_on_condition(&|| self.status.carry_flag, addr_mode, &instruction_info.1);
cycles += add_cycles;
new_pc
}
"BEQ" => {
let (add_cycles, new_pc) =
self.branch_on_condition(&|| self.status.zero_flag, addr_mode, &instruction_info.1);
cycles += add_cycles;
new_pc
}
"BIT" => {
let val = self.get_src_by_address_mode(addr_mode);
self.set_sign(val);
self.status.overflow_flag = (0x40 & val) > 0;
self.set_zero(val & self.acc);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"BMI" => {
let (add_cycles, new_pc) =
self.branch_on_condition(&|| self.status.negative_flag, addr_mode, &instruction_info.1);
cycles += add_cycles;
new_pc
}
"BNE" => {
let (add_cycles, new_pc) =
self.branch_on_condition(&|| !self.status.zero_flag, addr_mode, &instruction_info.1);
cycles += add_cycles;
new_pc
}
"BPL" => {
let (add_cycles, new_pc) =
self.branch_on_condition(&|| !self.status.negative_flag, addr_mode, &instruction_info.1);
cycles += add_cycles;
new_pc
}
"BRK" => {
self.pc = self.pc.wrapping_add(1);
let pc_hi = (self.pc >> 8) & 0xFF;
let pc_lo = self.pc & 0xFF;
self.push(pc_hi as u8);
self.push(pc_lo as u8);
self.status.break_flag_1 = true;
self.push(self.status.as_bytes());
// Break flag 1 is only true on the stack.. Set it back to false
self.status.break_flag_1 = false;
self.status.interrupt_disable_flag = true;
self.address_space.read_data_u16(0xFFFE)
}
"BVC" => {
let (add_cycles, new_pc) =
self.branch_on_condition(&|| !self.status.overflow_flag,
addr_mode, &instruction_info.1);
cycles += add_cycles;
new_pc
}
"BVS" => {
let (add_cycles, new_pc) =
self.branch_on_condition(&|| self.status.overflow_flag,
addr_mode, &instruction_info.1);
cycles += add_cycles;
new_pc
}
"CLC" => {
self.status.carry_flag = false;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"CLD" => {
self.status.decimal_flag = false;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"CLI" => {
self.status.interrupt_disable_flag = false;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"CLV" => {
self.status.overflow_flag = false;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"CMP" => {
self.cmp(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"CPX" => {
let val = self.get_src_by_address_mode(addr_mode);
let cmp_x = (self.x as u16).wrapping_sub(val as u16);
self.set_carry((cmp_x < 0x100) as u8);
self.set_sign(cmp_x as u8);
self.set_zero((cmp_x as u8) & 0xFF);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"CPY" => {
let val = self.get_src_by_address_mode(addr_mode);
let cmp_y = (self.y as u16).wrapping_sub(val as u16);
self.set_carry((cmp_y < 0x100) as u8);
self.set_sign(cmp_y as u8);
self.set_zero((cmp_y as u8) & 0xFF);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"DCM" => {
self.dec(addr_mode);
self.cmp(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"DEC" => {
self.dec(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"DEX" => {
let x_val = self.x;
let dec_val = x_val.wrapping_sub(1);
self.set_sign(dec_val);
self.set_zero(dec_val);
self.x = dec_val;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"DEY" => {
let y_val = self.y;
let dec_val = y_val.wrapping_sub(1);
self.set_sign(dec_val);
self.set_zero(dec_val);
self.y = dec_val;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"EOR" => {
self.eor(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"INC" => {
self.inc(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"INS" => {
self.inc(addr_mode);
self.sbc(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"INX" => {
let x_val = self.x;
let dec_val = x_val.wrapping_add(1);
self.set_sign(dec_val);
self.set_zero(dec_val);
self.x = dec_val;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"INY" => {
let y_val = self.y;
let dec_val = y_val.wrapping_add(1);
self.set_sign(dec_val);
self.set_zero(dec_val);
self.y = dec_val;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"JMP" => {
match addr_mode {
Absolute => {
let target =
self.address_space.read_data_u16(self.pc.wrapping_add(1));
target
}
Indirect => {
let addr = self.address_space.read_data_u16(self.pc.wrapping_add(1));
let target;
if (addr as u8) == 0xFF {
// This is a 'booby-trap' in the 6502. For indirect JMPs to addresses
// of (xxFF), the most significant byte will be fetched from xx00 instead
// of the next page
let low_byte = self.address_space.read_data_u8(addr);
let high_byte = self.address_space.read_data_u8(addr & 0xFF00);
target = (low_byte as u16) | ((high_byte as u16) << 8)
} else {
target = self.address_space.read_data_u16(addr);
}
target
}
_ => { unimplemented!("Unsupported addressing mode for JMP") }
}
}
"JSR" => {
let addr = self.get_addr_by_address_mode(addr_mode);
let to_push_pc =
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
.wrapping_sub(1);
let pc_hi = (to_push_pc >> 8) & 0xFF;
let pc_lo = to_push_pc & 0xFF;
self.push(pc_hi as u8);
self.push(pc_lo as u8);
addr
}
"LAS" => {
let val = self.get_src_by_address_mode(addr_mode);
let anded = val & self.sp;
self.acc = anded;
self.x = anded;
self.sp = anded;
self.set_sign(anded);
self.set_zero(anded);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"LAX" => {
self.lda(addr_mode);
self.ldx(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"LDA" => {
self.lda(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"LDX" => {
self.ldx(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"LDY" => {
let val = self.get_src_by_address_mode(addr_mode);
self.y = val;
self.set_sign(val);
self.set_zero(val);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"LSE" => {
self.lsr(addr_mode);
self.eor(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"LSR" => {
self.lsr(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"NOP" => {
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"OAL" => {
let ored = 0xEE | self.acc;
self.set_sign(ored);
self.set_zero(ored);
self.acc = ored;
self.and(addr_mode);
self.tax();
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"ORA" => {
self.ora(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"PHA" => {
self.push(self.acc);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"PHP" => {
self.push(self.status.as_bytes());
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"PLA" => {
let val = self.pull();
self.acc = val;
self.set_sign(val);
self.set_zero(val);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"PLP" => {
let val = self.pull();
self.status = self.status.from_bytes(val);
self.status.break_flag_1 = false;
self.status.break_flag_2 = true;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"RLA" => {
self.rol(addr_mode);
self.and(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"ROL" => {
self.rol(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"ROR" => {
self.ror(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"RRA" => {
self.ror(addr_mode);
self.adc(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"RTI" => {
let sr = self.pull();
self.status = self.status.from_bytes(sr);
self.status.break_flag_1 = false;
self.status.break_flag_2 = true;
let addr1 = self.pull() as u16;
let addr2 = self.pull() as u16;
addr1 | (addr2 << 8)
}
"RTS" => {
let src = (self.pull() as u16).wrapping_add(((self.pull() as u16) << 8)
.wrapping_add(1));
src
}
"SAX" => {
let anded = self.acc & self.x;
let tmp_acc = self.acc;
self.acc = anded;
self.set_carry(1);
self.sbc(addr_mode);
self.x = self.acc;
self.acc = tmp_acc;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"SAY" => {
let target_addr = self.get_addr_by_address_mode(addr_mode);
let target_hi = (target_addr >> 8) as u8;
let final_result = (target_hi.wrapping_add(1)) & self.y;
self.address_space.write_data(target_addr, final_result);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"SBC" => {
self.sbc(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"SEC" => {
self.set_carry(1);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"SED" => {
self.status.decimal_flag = true;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"SEI" => {
self.status.interrupt_disable_flag = true;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"SKW" => {
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"STA" => {
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), self.acc);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"STX" => {
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), self.x);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"STY" => {
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), self.y);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"TAS" => {
let anded = self.x & self.acc;
self.sp = anded;
let target_addr = self.get_addr_by_address_mode(addr_mode);
let target_hi = (target_addr >> 8) as u8;
let final_result = (target_hi.wrapping_add(1)) & anded;
self.address_space.write_data(target_addr, final_result);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"TAX" => {
self.tax();
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"TAY" => {
self.y = self.acc;
self.set_sign(self.y);
self.set_zero(self.y);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"TSX" => {
self.x = self.sp;
self.set_sign(self.x);
self.set_zero(self.x);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"TXA" => {
self.txa();
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"TXS" => {
self.sp = self.x;
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"TYA" => {
self.acc = self.y;
self.set_sign(self.y);
self.set_zero(self.y);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"XAA" => {
self.txa();
self.and(addr_mode);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
"XAS" => {
let target_addr = self.get_addr_by_address_mode(addr_mode);
let target_hi = (target_addr >> 8) as u8;
let final_result = (target_hi.wrapping_add(1)) & self.x;
self.address_space.write_data(target_addr, final_result);
self.pc.wrapping_add(self.num_bytes_from_mode(addr_mode))
}
_ => {
unimplemented!("Unknown instruction");
}
};
self.pc = next_pc;
self.total_cycles = self.total_cycles + cycles;
cycles
}
fn push(&mut self, byte: u8) {
self.address_space.write_data((0x0100 as u16).wrapping_add(self.sp as u16), byte);
self.sp = self.sp.wrapping_sub(1);
}
fn pull(&mut self) -> u8 {
self.sp = self.sp.wrapping_add(1);
self.address_space.read_data_u8((0x0100 as u16).wrapping_add(self.sp as u16))
}
fn peek(&self, n: u8) -> u8 {
let inc_sp = self.sp.wrapping_add(n) as u16;
self.address_space.read_data_u8((0x0100 as u16).wrapping_add(inc_sp))
}
fn branch_on_condition(&self, condition: &dyn Fn() -> bool,
address_mode: AddressingMode,
opcode: &u8) -> (usize, u16) {
let val = self.get_src_by_address_mode(address_mode);
if condition() {
// One extra cycle for taking the branch, possibly another for crossing the page
let page_cycles = if BRANCH_EXTRA_CYCLES_ON_PAGE.contains(opcode) {
self.check_page_boundary_crossed(address_mode)
} else {
0
};
(1 + page_cycles,
self.rel_address(val).wrapping_add(self.num_bytes_from_mode(address_mode)))
} else {
(0, self.pc.wrapping_add(self.num_bytes_from_mode(address_mode)))
}
}
fn rel_address(&self, offset: u8) -> u16 {
if offset >> 7 == 1 {
// Negative - use two's complement to get the offset
let adjusted_offset = (!offset).wrapping_add(1);
self.pc.wrapping_sub(adjusted_offset as u16)
} else {
self.pc.wrapping_add(offset as u16)
}
}
fn set_sign(&mut self, src: u8) {
self.status.negative_flag = ((src >> 7) & 1) == 1;
}
fn set_zero(&mut self, src: u8) {
self.status.zero_flag = src == 0;
}
fn set_carry(&mut self, condition: u8) {
if condition != 0 {
self.status.carry_flag = true;
} else {
self.status.carry_flag = false;
}
}
fn print_machine_code(&self, instruction_info: &(&str, Opcode, Cycles, AddressingMode),
operand_u8: u8, operand_u16: u16) -> String {
let (_, opcode, _, address_mode) = instruction_info;
match address_mode {
Implicit | Accumulator => {
format!("{:02X} ", opcode)
}
Absolute | AbsoluteX | AbsoluteY | Indirect => {
format!("{:02X} {:02X} {:02X}", opcode, operand_u16 & 0x00FF, operand_u16 >> 8)
}
_ => {
format!("{:02X} {:02X} ", opcode, operand_u8)
}
}
}
fn print_assembly_command(&self, instruction_info: &(&str, Opcode, Cycles, AddressingMode),
operand_u8: u8, operand_u16: u16) -> String {
let (instr, _, _, address_mode) = instruction_info;
match address_mode {
Immediate => {
format!("{} #${:02X}", instr, operand_u8)
}
Relative => {
format!("{} ${:02X}", instr, operand_u8)
}
Accumulator => {
format!("{} A", instr)
}
Absolute => {
format!("{} ${:04X}", instr, operand_u16)
}
AbsoluteX => {
format!("{} ${:04X},X", instr, operand_u16)
}
AbsoluteY => {
format!("{} ${:04X},Y", instr, operand_u16)
}
ZeroPage => {
format!("{} ${:02X}", instr, operand_u8)
}
ZeroPageX => {
format!("{} ${:02X},X", instr, operand_u8)
}
ZeroPageY => {
format!("{} ${:02X},Y", instr, operand_u8)
}
Indirect => {
format!("{} (${:04X})", instr, operand_u16)
}
IndirectX => {
format!("{} (${:02X}, X)", instr, operand_u8)
}
IndirectY => {
format!("{} (${:02X}, Y)", instr, operand_u8)
}
Implicit => {
format!("{}", instr)
}
}
}
fn asl(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
self.set_carry(val & 0x80);
let new_val = (val << 1) & 0xff;
self.set_sign(new_val);
self.set_zero(new_val);
if addr_mode == AddressingMode::Accumulator {
self.acc = new_val;
} else {
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), new_val);
}
new_val
}
fn rol(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode) as u16;
let shifted = (val << 1) | (self.status.carry_flag as u16);
self.set_carry((shifted > 0xff) as u8);
self.set_sign(shifted as u8);
self.set_zero(shifted as u8);
if addr_mode == AddressingMode::Accumulator {
self.acc = shifted as u8;
} else {
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), shifted as u8);
}
shifted as u8
}
fn and(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
let new_acc = val & self.acc;
self.set_sign(new_acc);
self.set_zero(new_acc);
self.acc = new_acc;
new_acc
}
fn ora(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
let ored = val | self.acc;
self.set_sign(ored);
self.set_zero(ored);
self.acc = ored;
ored
}
fn lsr(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
self.set_carry(val & 0x01);
let shifted = val >> 1;
self.set_sign(shifted);
self.set_zero(shifted);
if addr_mode == AddressingMode::Accumulator {
self.acc = shifted;
} else {
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), shifted);
}
shifted
}
fn eor(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
let xored = val ^ self.acc;
self.set_sign(xored);
self.set_zero(xored);
self.acc = xored;
xored
}
fn ror(&mut self, addr_mode: AddressingMode) -> u8 {
let val = (self.get_src_by_address_mode(addr_mode) as u16)
| ((self.status.carry_flag as u16) << 8);
self.set_carry((val as u8) & 0x01);
let shifted = (val >> 1) as u8;
self.set_sign(shifted);
self.set_zero(shifted);
if addr_mode == AddressingMode::Accumulator {
self.acc = shifted;
} else {
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), shifted);
}
shifted
}
fn adc(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
let tmp: u16 = (self.acc as u16).wrapping_add(val as u16)
.wrapping_add(self.status.carry_flag as u16);
self.set_sign(tmp as u8);
self.set_zero(tmp as u8);
self.status.overflow_flag = !(((self.acc ^ val) & 0x80) > 0) &&
(((self.acc as u16 ^ tmp) & 0x80) > 0);
self.status.carry_flag = tmp > 0xff;
self.acc = tmp as u8;
tmp as u8
}
fn lda(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
self.acc = val;
self.set_sign(val);
self.set_zero(val);
val
}
fn ldx(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
self.x = val;
self.set_sign(val);
self.set_zero(val);
val
}
fn dec(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
let dec_val = val.wrapping_sub(1);
self.set_sign(dec_val);
self.set_zero(dec_val);
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), dec_val);
dec_val
}
fn cmp(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode) as u16;
let src = (self.acc as u16).wrapping_sub(val);
self.set_carry((src < 0x100) as u8);
self.set_sign(src as u8);
self.set_zero((src as u8) & 0xFF);
src as u8
}
fn inc(&mut self, addr_mode: AddressingMode) -> u8 {
let val = self.get_src_by_address_mode(addr_mode);
let dec_val = val.wrapping_add(1);
self.set_sign(dec_val);
self.set_zero(dec_val);
self.address_space.write_data(self.get_addr_by_address_mode(
addr_mode), dec_val);
dec_val
}
fn sbc(&mut self, addr_mode: AddressingMode) -> u8 {
let src = self.get_src_by_address_mode(addr_mode);
let tmp = (self.acc as u16).wrapping_sub(src as u16)
.wrapping_sub(!self.status.carry_flag as u16);
let u8_tmp = tmp as u8;
self.set_sign(u8_tmp);
self.set_zero(u8_tmp);
self.status.overflow_flag = (((self.acc ^ u8_tmp) & 0x80) > 0) &&
(((self.acc ^ src) & 0x80) > 0);
self.set_carry((tmp < 0x100) as u8);
self.acc = u8_tmp;
u8_tmp
}
fn txa(&mut self) -> u8 {
self.acc = self.x;
self.set_sign(self.acc);
self.set_zero(self.acc);
self.acc
}
fn tax(&mut self) -> u8 {
self.x = self.acc;
self.set_sign(self.x);
self.set_zero(self.x);
self.x
}
}
| true
|
35763977358cf7737675618f2e33bd5a39efb7b6
|
Rust
|
Greast/r-graph
|
/src/wrapper/random/edge.rs
|
UTF-8
| 6,823
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
use crate::dev::orientation::AddEdge as EdgeTrait;
use crate::dev::{
orientation, AddVertex, Edges, GetEdge, GetEdgeTo, GetVertex, Merge, Neighbours, RemoveEdge,
RemoveVertex, Vertices,
};
use rand::distributions::{Distribution, Standard};
use rand::random;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use crate::dev::transform::{transformers, Collect, Map};
use crate::wrapper::random::safe_map;
use std::hash::Hash;
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct Edge<Graph, EdgeKey = usize> {
graph: Graph,
edge_key: PhantomData<EdgeKey>,
}
impl<Graph, EdgeKey> Deref for Edge<Graph, EdgeKey> {
type Target = Graph;
fn deref(&self) -> &Self::Target {
&self.graph
}
}
impl<Graph, EdgeKey> DerefMut for Edge<Graph, EdgeKey> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.graph
}
}
impl<Graph, EdgeKey> From<Graph> for Edge<Graph, EdgeKey> {
fn from(graph: Graph) -> Self {
Self {
graph,
edge_key: Default::default(),
}
}
}
impl<Graph, EdgeKey, Value> AddVertex<Value> for Edge<Graph, EdgeKey>
where
Graph: AddVertex<Value>,
{
type Key = <Graph as AddVertex<Value>>::Key;
fn add_vertex(&mut self, value: Value) -> Result<Self::Key, Value> {
self.graph.add_vertex(value)
}
}
impl<Graph, VertexKey, EdgeKey, Value, Orientation> EdgeTrait<Orientation, VertexKey, Value>
for Edge<Graph, EdgeKey>
where
Orientation: orientation::Orientation,
Graph: EdgeTrait<Orientation, VertexKey, (EdgeKey, Value)>,
Standard: Distribution<EdgeKey>,
{
type EdgeKey = <Graph as EdgeTrait<Orientation, VertexKey, (EdgeKey, Value)>>::EdgeKey;
fn add_edge(
&mut self,
from: &VertexKey,
to: &VertexKey,
value: Value,
) -> Result<Self::EdgeKey, Value> {
let mut output = self.graph.add_edge(from, to, (random(), value));
while let Err((_, value)) = output {
output = self.graph.add_edge(from, to, (random(), value));
}
output.map_err(|x| x.1)
}
}
impl<Graph, VertexKey, EdgeKey> RemoveVertex<VertexKey> for Edge<Graph, EdgeKey>
where
Graph: RemoveVertex<VertexKey>,
{
type Output = <Graph as RemoveVertex<VertexKey>>::Output;
fn remove_vertex(&mut self, key: &VertexKey) -> Option<Self::Output> {
self.graph.remove_vertex(key)
}
}
impl<Graph, EdgeKey> RemoveEdge<EdgeKey> for Edge<Graph, EdgeKey>
where
Graph: RemoveEdge<EdgeKey>,
{
type Output = <Graph as RemoveEdge<EdgeKey>>::Output;
fn remove_edge(&mut self, key: &EdgeKey) -> Option<Self::Output> {
self.graph.remove_edge(key)
}
}
impl<Graph, VertexKey, EdgeKey> GetVertex<VertexKey> for Edge<Graph, EdgeKey>
where
Graph: GetVertex<VertexKey>,
{
type Output = <Graph as GetVertex<VertexKey>>::Output;
fn get_vertex(&self, key: &VertexKey) -> Option<&Self::Output> {
self.graph.get_vertex(key)
}
}
impl<Graph, EdgeKey> GetEdge<EdgeKey> for Edge<Graph, EdgeKey>
where
Graph: GetEdge<EdgeKey>,
{
type Output = <Graph as GetEdge<EdgeKey>>::Output;
fn get_edge(&self, key: &EdgeKey) -> Option<&Self::Output> {
self.graph.get_edge(key)
}
}
impl<'a, Graph, EdgeKey> GetEdgeTo<'a, EdgeKey> for Edge<Graph, EdgeKey>
where
Graph: GetEdgeTo<'a, EdgeKey>,
{
type Output = <Graph as GetEdgeTo<'a, EdgeKey>>::Output;
fn get_edge_to(&'a self, key: &EdgeKey) -> Option<Self::Output> {
self.graph.get_edge_to(key)
}
}
impl<'a, Graph, VertexKey, EdgeKey, Orientation> Neighbours<'a, Orientation, VertexKey>
for Edge<Graph, EdgeKey>
where
VertexKey: 'a,
Orientation: orientation::Orientation,
Graph: Neighbours<'a, Orientation, VertexKey>,
{
type Edge = <Graph as Neighbours<'a, Orientation, VertexKey>>::Edge;
type IntoIter = <Graph as Neighbours<'a, Orientation, VertexKey>>::IntoIter;
fn neighbours(&'a self, key: &VertexKey) -> Option<Self::IntoIter> {
self.graph.neighbours(key)
}
}
impl<'a, Graph, EdgeKey> Vertices<'a> for Edge<Graph, EdgeKey>
where
Graph: Vertices<'a>,
{
type Item = <Graph as Vertices<'a>>::Item;
type Output = <Graph as Vertices<'a>>::Output;
fn vertices(&'a self) -> Self::Output {
self.graph.vertices()
}
}
impl<'a, Graph, EdgeKey> Edges<'a> for Edge<Graph, EdgeKey>
where
Graph: Edges<'a>,
{
type Item = <Graph as Edges<'a>>::Item;
type Output = <Graph as Edges<'a>>::Output;
fn edges(&'a self) -> Self::Output {
self.graph.edges()
}
}
impl<'a, Graph2, Graph, EdgeKey> Merge<Edge<Graph2, EdgeKey>> for Edge<Graph, EdgeKey>
where
EdgeKey: 'a + Eq + Hash + Clone,
Graph: Map<transformers::EdgeKey, EdgeKey, EdgeKey, Box<dyn 'a + FnMut(EdgeKey) -> EdgeKey>>,
<Graph as Map<
transformers::EdgeKey,
EdgeKey,
EdgeKey,
Box<dyn 'a + FnMut(EdgeKey) -> EdgeKey>,
>>::Mapper: Collect<Output = Graph>,
Graph: Merge<Graph2>,
Standard: Distribution<EdgeKey>,
Graph2: 'a + GetEdge<EdgeKey>,
{
type Output = Edge<<Graph as Merge<Graph2>>::Output, EdgeKey>;
fn merge(
self,
other: Edge<Graph2, EdgeKey>,
) -> Result<Self::Output, (Self, Edge<Graph2, EdgeKey>)> {
safe_map(self.graph, other.graph)
.map(Edge::from)
.map_err(|opt| {
let (x, y) = opt.unwrap();
(x.into(), y.into())
})
}
}
impl<Type, Func, EdgeKey, Graph> Map<Type, EdgeKey, EdgeKey, Func> for Edge<Graph, EdgeKey>
where
Graph: Map<Type, EdgeKey, EdgeKey, Func>,
{
type Mapper = EdgeTransformer<<Graph as Map<Type, EdgeKey, EdgeKey, Func>>::Mapper, EdgeKey>;
fn map(self, func: Func) -> Self::Mapper {
let transformer = self.graph.map(func);
Self::Mapper {
transformer,
phantom: PhantomData,
}
}
}
pub struct EdgeTransformer<Trans, EdgeKey> {
transformer: Trans,
phantom: PhantomData<(EdgeKey,)>,
}
impl<Trans, EdgeKey> Collect for EdgeTransformer<Trans, EdgeKey>
where
Trans: Collect,
{
type Output = Edge<<Trans as Collect>::Output, EdgeKey>;
fn collect(self) -> Option<Self::Output> {
Edge {
graph: self.transformer.collect()?,
edge_key: PhantomData,
}
.into()
}
}
impl<Type, Func, Trans, EdgeKey> Map<Type, EdgeKey, EdgeKey, Func>
for EdgeTransformer<Trans, EdgeKey>
where
Trans: Map<Type, EdgeKey, EdgeKey, Func>,
{
type Mapper = EdgeTransformer<<Trans as Map<Type, EdgeKey, EdgeKey, Func>>::Mapper, EdgeKey>;
fn map(self, func: Func) -> Self::Mapper {
EdgeTransformer {
transformer: self.transformer.map(func),
phantom: PhantomData,
}
}
}
| true
|
fc014f834bf74cbfec692d742819240831dfbc13
|
Rust
|
ZakisM/http_lib
|
/src/header_map.rs
|
UTF-8
| 3,633
| 3.34375
| 3
|
[] |
no_license
|
use std::ops::Deref;
#[derive(Debug, Default, Clone)]
pub struct HeaderMap {
pub headers: Vec<(String, String)>,
}
#[allow(unused)]
impl HeaderMap {
pub fn new() -> Self {
Self::default()
}
pub fn from_header_lines(header_str_lines: &mut dyn Iterator<Item = &str>) -> Option<Self> {
let headers = header_str_lines.fold(HeaderMap::new(), |mut curr, next| {
let mut key_val = next.splitn(2, ": ");
let key = key_val.next();
let val = key_val.next();
if let (Some(key), Some(val)) = (key, val) {
curr.insert(key, val);
}
curr
});
if !headers.is_empty() {
Some(headers)
} else {
None
}
}
pub fn is_empty(&self) -> bool {
self.headers.is_empty()
}
pub fn insert(&mut self, key: &str, value: &str) {
let existing = self
.headers
.iter_mut()
.find(|(k, _)| *k == key)
.map(|(_, v)| v);
if let Some(existing) = existing {
*existing = value.to_owned();
} else {
self.headers.push((key.to_owned(), value.to_owned()));
}
}
pub fn remove(&mut self, key: &str) -> bool {
let key = key.to_lowercase();
let existing = self
.headers
.iter()
.position(|(k, _)| k.to_lowercase() == key);
if let Some(existing) = existing {
self.headers.remove(existing);
true
} else {
false
}
}
pub fn get(&self, key: &str) -> Option<&str> {
let key = key.to_lowercase();
self.headers
.iter()
.find(|(k, _)| k.to_lowercase() == key)
.map(|(_, v)| v.as_str())
}
pub fn get_mut(&mut self, key: &str) -> Option<&mut String> {
let key = key.to_lowercase();
self.headers
.iter_mut()
.find(|(k, _)| k.to_lowercase() == key)
.map(|(_, v)| v)
}
}
impl Deref for HeaderMap {
type Target = Vec<(String, String)>;
fn deref(&self) -> &Self::Target {
&self.headers
}
}
#[cfg(test)]
mod tests {
use crate::header_map::HeaderMap;
#[test]
fn test_insert() {
let mut header_map = HeaderMap::new();
header_map.insert("Transfer-Encoding", "chunked");
assert_eq!(header_map.get("Transfer-Encoding"), Some("chunked"));
header_map.insert("Transfer-Encoding", "gzip");
assert_eq!(header_map.get("Transfer-Encoding"), Some("gzip"));
}
#[test]
fn test_remove() {
let mut header_map = HeaderMap::new();
header_map.insert("Transfer-Encoding", "chunked");
assert_eq!(header_map.get("Transfer-Encoding"), Some("chunked"));
assert_eq!(header_map.remove("Transfer-Encoding"), true);
assert_eq!(header_map.get("Transfer-Encoding"), None);
}
#[test]
fn test_get() {
let mut header_map = HeaderMap::new();
header_map.insert("Transfer-Encoding", "chunked");
assert_eq!(header_map.get("Transfer-Encoding"), Some("chunked"));
}
#[test]
fn test_get_mut() {
let mut header_map = HeaderMap::new();
header_map.insert("Transfer-Encoding", "chunked");
assert_eq!(header_map.get("Transfer-Encoding"), Some("chunked"));
if let Some(te_mut) = header_map.get_mut("Transfer-Encoding") {
*te_mut = "compress".to_owned();
}
assert_eq!(header_map.get("Transfer-Encoding"), Some("compress"));
}
}
| true
|
5ac255edd131908e2e0d34fdfbc3ef7db87b7ce0
|
Rust
|
svmk/fund-watch-bot
|
/src/telegram/model/message_id.rs
|
UTF-8
| 415
| 2.71875
| 3
|
[] |
no_license
|
use crate::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, ValueObject)]
#[value_object(error_type = "Failure", load_fn = "MessageId::from_u32")]
pub struct MessageId(u32);
impl MessageId {
pub fn from_u32(value: u32) -> Result<MessageId, Failure> {
let value = MessageId(value);
return Ok(value);
}
pub fn to_u32(self) -> u32 {
return self.0;
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.