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 |
---|---|---|---|---|---|---|---|---|---|---|---|
472baa8a9a6aef9a6238f8df11455b93ccd84c1f
|
Rust
|
grabthequest/grabthequest-commons
|
/src/dto.rs
|
UTF-8
| 4,833 | 2.546875 | 3 |
[] |
no_license
|
use serde::{Serialize, Deserialize};
use std::cmp::Ordering;
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct RegisterDTO {
pub full_name: String,
pub email: String,
pub password: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FusionAuthRegistrationAdditionDTO {
pub application_id: String
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FusionAuthUserRegistrationDTO {
pub full_name: String,
pub email: String,
pub password: String
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FusionAuthLoginResponseDTO {
pub token: String,
pub user: UserDTO
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserDTO {
pub active: bool,
pub email: String,
pub full_name: String,
pub id: String
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct RegistrationDTO {
pub application_id: String,
pub authentication_token: String,
pub id: String,
pub insert_instant: u64,
pub last_login_instant: u64,
pub last_update_instant: u64,
pub username_status: String,
pub verified: bool
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FusionAuthRegisterResponseDTO {
pub registration: RegistrationDTO,
pub token: String,
pub user: UserDTO
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserQueryDTO {
pub user: UserDTO
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "camelCase")]
pub struct GameDTO {
pub id: i32
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GameEventDTO {
pub id: i32,
pub game_id: i32,
pub user_id: String,
pub user_name: String,
pub event_type: String,
pub problem_seq_no: Option<i32>,
pub timestamp: i64
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LanguageDTO {
pub id: i32,
pub name: String
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ProblemViewDTO {
pub id: i32,
pub title: String,
pub description: String,
pub languages: Vec<LanguageDTO>
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ProblemDTO {
pub id: Option<i32>,
pub title: String,
pub description: String,
pub timeout: i32,
pub test_cases: Vec<TestCaseDTO>
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TestCaseDTO {
pub id: Option<i32>,
pub problem_id: Option<i32>,
pub seq_no: i32,
pub input: String,
pub output: String
}
impl PartialEq for TestCaseDTO {
fn eq(&self, other: &TestCaseDTO) -> bool {
return self.id == other.id;
}
}
impl Eq for TestCaseDTO {}
impl PartialOrd for TestCaseDTO {
fn partial_cmp(&self, other: &TestCaseDTO) -> Option<Ordering> {
return Some(self.cmp(other));
}
}
impl Ord for TestCaseDTO {
fn cmp(&self, other: &TestCaseDTO) -> Ordering {
return self.seq_no.cmp(&other.seq_no);
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TestCaseSubmissionDTO {
pub seq_no: i32,
pub submission_id: String
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CodeSubmissionDTO {
pub code_submission_id: i32
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SubmissionTokenResponseDTO {
pub token: String
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SubmissionStatusResponseDTO {
pub id: u16,
pub description: String
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SubmissionDetailResponseDTO {
pub token: String,
pub status: SubmissionStatusResponseDTO
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BatchSubmissionsDetailResponseDTO {
pub submissions: Vec<SubmissionDetailResponseDTO>
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TestCaseResultDTO {
pub seq_no: i32,
pub submission_detail: SubmissionDetailResponseDTO
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GamePlayerDTO {
pub id: i32,
pub game_id: i32,
pub user_id: String,
pub major_score: i32,
pub minor_score: i32
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SubmissionEventDTO {
pub id: i32,
pub code_submission_id: i32,
pub code_submission_token_id: i32,
pub test_case_seq_no: i32,
pub status: String,
pub timestamp: i64
}
| true |
4a081025d854a7a30d2cfa72fda0a209af7ab50b
|
Rust
|
teruuuuuu/kyoupro
|
/rust/src/atcoder/beginner/q165/a.rs
|
UTF-8
| 571 | 2.859375 | 3 |
[] |
no_license
|
use std;
pub fn main() {
fn read<T: std::str::FromStr>() -> T {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim().parse::<T>().ok().unwrap()
}
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
read::<String>()
.split_whitespace()
.map(|e| e.parse().ok().unwrap())
.collect()
}
let k = read::<i32>();
let ab = read_vec::<i32>();
let a = ab[0];
let b = ab[1];
if (k - (a % k)) % k <= b - a {
println!("OK");
} else {
println!("NG");
}
}
// #[test]
// fn test() {
// main();
// }
| true |
808a1b421032f674139b627fe4dd4f2c8ccc6ecd
|
Rust
|
LukasKalbertodt/cantucci
|
/build.rs
|
UTF-8
| 2,660 | 2.796875 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::{fs, path::Path};
use anyhow::{anyhow, bail, Context as _, Result};
use shaderc::{Compiler, ShaderKind};
fn main() -> Result<()> {
compile_shaders()?;
Ok(())
}
const SHADERS: &[&str] = &[
"dome.vert",
"dome.frag",
"surface.vert",
"surface.frag",
];
fn compile_shaders() -> Result<()> {
let out_dir = Path::new(&std::env::var("OUT_DIR").unwrap()).join("shaders");
if !out_dir.exists() {
fs::create_dir(&out_dir)?;
}
let mut compiler = Compiler::new().unwrap();
for filename in SHADERS {
let full_path = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("src")
.join("shaders")
.join(filename);
let out_path = out_dir.join(format!("{}.spirv", filename));
if !full_path.exists() {
bail!("shader file '{}' does not exist", full_path.display());
}
// If the spirv file is newer than the source file, we skip this shader.
// Cargo makes sure the build script is only rerun if any of the shader
// files change, but we still want to avoid recompiling all shaders if
// one changed.
let skip = out_path.exists()
&& full_path.metadata()?.modified()? < out_path.metadata()?.modified()?;
if skip {
continue;
}
// Figure out shader kind by file extension.
let path = Path::new(filename);
let ext = path.extension().ok_or(anyhow!("no extension in shader filename"))?.to_str();
let kind = match ext {
Some("vert") => ShaderKind::Vertex,
Some("frag") => ShaderKind::Fragment,
_ => bail!("invalid shader file extension"),
};
// Actually compile shader and deal with errors.
let src = fs::read_to_string(&full_path)
.context(format!("failed to read '{}'", full_path.display()))?;
let result = compiler.compile_into_spirv(&src, kind, filename, "main", None);
let artifact = match result {
Ok(v) => v,
Err(shaderc::Error::CompilationError(_, msg)) => {
eprintln!("{}", msg);
bail!("failed to compile shader '{}'", filename);
}
Err(e) => Err(e)?,
};
for warning in artifact.get_warning_messages().lines() {
println!("cargo:warning={}", warning);
}
// Write out result.
fs::write(&out_path, artifact.as_binary_u8())
.context(format!("failed to write '{}'", out_path.display()))?;
println!("cargo:rerun-if-changed={}", full_path.display());
}
Ok(())
}
| true |
6cc86d9dda5f16b62871670ccccd05ef5dd1bd74
|
Rust
|
galenelias/AdventOfCode_2017
|
/src/Day1/mod.rs
|
UTF-8
| 653 | 3.21875 | 3 |
[] |
no_license
|
use std::io::{self, BufRead};
pub fn solve() {
println!("Enter input to checksum:");
let stdin = io::stdin();
let input = stdin.lock().lines().next().unwrap().unwrap();
let input_ints = input.chars().filter_map(|c| { return c.to_digit(10);}).collect::<Vec<u32>>();
let sum1 : u32 = input_ints.iter()
.zip(input_ints.iter().cycle().skip(1))
.filter_map(|(a, b)| { if a == b { Some(a) } else { None }})
.sum();
let sum2 : u32 = input_ints.iter()
.zip(input_ints.iter().cycle().skip(input_ints.len()/2))
.filter_map(|(a, b)| { if a == b { Some(a) } else { None }})
.sum();
println!("Part1: {}", sum1);
println!("Part2: {}", sum2);
}
| true |
05d9895db96ecdb7ee34756d1e8c9efc7d89d9cc
|
Rust
|
ArneBouillon/ultimate_ttt
|
/src/game/game_state.rs
|
UTF-8
| 7,789 | 2.953125 | 3 |
[] |
no_license
|
use super::board::{Board, Owned};
use super::player::Player;
use super::action::Action;
use crate::game::game_result::GameResult;
use rand::seq::SliceRandom;
use rand::Rng;
#[derive(Clone)]
pub struct GameState {
pub board: Board,
pub current_player: Player,
pub current_sub_x: Option<usize>,
pub current_sub_y: Option<usize>,
}
impl GameState {
pub fn new() -> GameState {
GameState {
board: Board::new(),
current_player: Player::Player1,
current_sub_x: None,
current_sub_y: None,
}
}
pub fn board(&self) -> &Board {
&self.board
}
pub fn board_mut(&mut self) -> &mut Board {
&mut self.board
}
pub fn current_player(&self) -> Player {
self.current_player
}
pub fn make_move(&mut self, sub_x: usize, sub_y: usize, x: usize, y: usize) -> Option<GameResult> {
let current_player = self.current_player();
let (new_x, new_y, result) = self.board_mut().make_move(Some(current_player.wins()),
sub_x,
sub_y,
x.clone(),
y.clone());
self.current_sub_x = new_x;
self.current_sub_y = new_y;
self.current_player = current_player.next();
result
}
pub fn play_randomly(&self) -> GameResult {
let mut actions = self.initialize_actions();
let mut new_game_state = self.clone();
loop {
let action = match new_game_state.current_sub_x {
None => {
let possible_actions = new_game_state.possible_actions();
let action = possible_actions.choose(&mut rand::thread_rng()).unwrap();
actions[3 * action.sub_y + action.sub_x].retain(|ac| ac.x != action.x || ac.y != action.y);
action.clone()
},
Some(sub_x) => {
let sub_y = new_game_state.current_sub_y.unwrap();
let random_num = rand::thread_rng().gen_range(0, actions[3 * sub_y + sub_x].len());
actions[3 * sub_y + sub_x].remove(random_num).clone()
},
};
let action_result = action.apply(&mut new_game_state);
if let Some(result) = action_result {
return result;
}
}
}
pub fn initialize_actions(&self) -> [Vec<Action>; 9] {
[
(0..9).filter_map(|i| {
match self.board.structure().items[0].structure().items[i].result() {
None => Some(Action::new(
0,
0,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
(0..9).filter_map(|i| {
match self.board.structure().items[1].structure().items[i].result() {
None => Some(Action::new(
1,
0,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
(0..9).filter_map(|i| {
match self.board.structure().items[2].structure().items[i].result() {
None => Some(Action::new(
2,
0,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
(0..9).filter_map(|i| {
match self.board.structure().items[3].structure().items[i].result() {
None => Some(Action::new(
0,
1,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
(0..9).filter_map(|i| {
match self.board.structure().items[4].structure().items[i].result() {
None => Some(Action::new(
1,
1,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
(0..9).filter_map(|i| {
match self.board.structure().items[5].structure().items[i].result() {
None => Some(Action::new(
2,
1,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
(0..9).filter_map(|i| {
match self.board.structure().items[6].structure().items[i].result() {
None => Some(Action::new(
0,
2,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
(0..9).filter_map(|i| {
match self.board.structure().items[7].structure().items[i].result() {
None => Some(Action::new(
1,
2,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
(0..9).filter_map(|i| {
match self.board.structure().items[8].structure().items[i].result() {
None => Some(Action::new(
2,
2,
i % 3,
i / 3,
false,
)),
Some(_) => None,
}
}).collect(),
]
}
pub fn possible_actions(&self) -> Vec<Action> {
match self.current_sub_x {
Some(sub_x) => {
let sub_y = self.current_sub_y.unwrap();
let sub_board_items = &self.board().get(sub_x, sub_y).structure().items;
let mut vec = Vec::with_capacity(9);
for i in 0..9 {
if sub_board_items[i].result().is_none() {
vec.push(Action::new(sub_x, sub_y, i % 3, i / 3, false));
}
}
vec
},
None => {
let mut vec = Vec::with_capacity(81);
let board_items = &self.board().structure().items;
for i in 0..9 {
let sub_board = &board_items[i];
if sub_board.result().is_some() {
continue;
}
let sub_board_items = &sub_board.structure().items;
let (sub_x, sub_y) = (i % 3, i / 3);
for j in 0..9 {
if sub_board_items[j].result().is_none() {
vec.push(Action::new(sub_x, sub_y, j % 3, j / 3, true));
}
}
}
vec
},
}
}
}
| true |
175e1ca76fcf8047e096c37ea9a34d8d45703a12
|
Rust
|
sgbstaking/SGBStakingDapp
|
/src/lib.rs
|
UTF-8
| 8,692 | 2.515625 | 3 |
[] |
no_license
|
//! SubGame Stake Dapp
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use frame_support::{
decl_error, decl_event, decl_module, decl_storage, dispatch, ensure,
traits::{Get, Currency, ReservableCurrency, ExistenceRequirement, Vec},
weights::{Weight, Pays, DispatchClass},
};
use frame_system::ensure_signed;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod default_weight;
pub trait WeightInfo {
fn sign_up() -> Weight;
fn stake() -> Weight;
fn unlock() -> Weight;
fn withdraw() -> Weight;
fn import_stake() -> Weight;
fn modify_user() -> Weight;
}
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
#[derive(Encode, Decode, Default)]
pub struct UserInfo<Account, ReferrerAccount> {
pub account: Account,
pub referrer_account: ReferrerAccount,
}
pub trait Config: frame_system::Config {
type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;
type Balances: Currency<Self::AccountId>;
type OwnerAddress: Get<Self::AccountId>;
type ImportAddress: Get<Self::AccountId>;
type WeightInfo: WeightInfo;
type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>;
}
decl_storage! {
trait Store for Module<T: Config> as Chips {
pub UserInfoMap get(fn user_info_map): map hasher(blake2_128_concat) T::AccountId => UserInfo<Vec<u8>, Vec<u8>>;
pub AccountMap get(fn account_map): map hasher(blake2_128_concat) Vec<u8> => T::AccountId;
pub UserStake get(fn user_stake): map hasher(blake2_128_concat) T::AccountId => BalanceOf<T>;
pub StakePool get(fn stake_pool): BalanceOf<T>;
}
}
decl_event!(
pub enum Event<T>
where
AccountId = <T as frame_system::Config>::AccountId,
Balance = BalanceOf<T>,
{
SignUp(AccountId, Vec<u8>, Vec<u8>),
Stake(AccountId, Balance),
Unlock(AccountId, Balance),
Withdraw(AccountId, Balance),
ModifyUser(AccountId, Vec<u8>, Vec<u8>),
}
);
decl_error! {
pub enum Error for Module<T: Config> {
UserExists,
AccountFormatIsWrong,
UserNotExists,
MoneyNotEnough,
PermissionDenied,
StakeAmountWrong,
}
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
type Error = Error<T>;
fn deposit_event() = default;
#[weight = (T::WeightInfo::sign_up(), DispatchClass::Normal, Pays::No)]
pub fn sign_up(origin, account: Vec<u8>, referrer_account: Vec<u8>) -> dispatch::DispatchResult {
let _who = ensure_signed(origin)?;
let _account_str = core::str::from_utf8(&account).unwrap().to_lowercase();
ensure!(_account_str.len() == 7, Error::<T>::AccountFormatIsWrong);
ensure!(_account_str != "gametop", Error::<T>::AccountFormatIsWrong);
let _account = _account_str.as_bytes().to_vec();
let _referrer_account_str = core::str::from_utf8(&referrer_account).unwrap().to_lowercase();
let _referrer_account = _referrer_account_str.as_bytes().to_vec();
ensure!(!UserInfoMap::<T>::contains_key(&_who), Error::<T>::UserExists);
ensure!(!AccountMap::<T>::contains_key(_account.clone()), Error::<T>::UserExists);
let user_info = UserInfo{
account: _account.clone(),
referrer_account: _referrer_account.clone(),
};
<UserInfoMap::<T>>::insert(&_who, user_info);
<AccountMap::<T>>::insert(_account.clone(), &_who);
Self::deposit_event(RawEvent::SignUp(_who, _account, _referrer_account));
Ok(())
}
#[weight = (T::WeightInfo::stake(), DispatchClass::Normal, Pays::No)]
pub fn stake(origin, amount: BalanceOf<T>) -> dispatch::DispatchResult {
let _who = ensure_signed(origin)?;
ensure!(UserInfoMap::<T>::contains_key(&_who), Error::<T>::UserNotExists);
T::Currency::reserve(&_who, amount).map_err(|_| Error::<T>::MoneyNotEnough )?;
<StakePool::<T>>::put(Self::stake_pool() + amount);
<UserStake::<T>>::insert(&_who, Self::user_stake(&_who) + amount);
Self::deposit_event(RawEvent::Stake(_who, amount));
Ok(())
}
#[weight = (T::WeightInfo::unlock(), DispatchClass::Normal, Pays::No)]
pub fn unlock(origin, _who: T::AccountId, amount: BalanceOf<T>) -> dispatch::DispatchResult {
let sender = ensure_signed(origin)?;
let owner = T::OwnerAddress::get();
ensure!(owner == sender, Error::<T>::PermissionDenied);
ensure!(UserInfoMap::<T>::contains_key(&_who), Error::<T>::UserNotExists);
ensure!(T::Currency::reserved_balance(&_who) >= amount, Error::<T>::MoneyNotEnough);
let user_stake = Self::user_stake(&_who);
ensure!(user_stake >= amount, Error::<T>::MoneyNotEnough);
let stake_pool = Self::stake_pool();
ensure!(stake_pool >= amount, Error::<T>::MoneyNotEnough);
T::Currency::unreserve(&_who, amount);
<StakePool::<T>>::put(stake_pool - amount);
<UserStake::<T>>::insert(&_who, user_stake - amount);
Self::deposit_event(RawEvent::Unlock(_who, amount));
Ok(())
}
#[weight = (T::WeightInfo::withdraw(), DispatchClass::Normal, Pays::No)]
pub fn withdraw(origin, _who: T::AccountId, amount: BalanceOf<T>) -> dispatch::DispatchResult {
let sender = ensure_signed(origin)?;
let owner = T::OwnerAddress::get();
ensure!(owner == sender, Error::<T>::PermissionDenied);
ensure!(UserInfoMap::<T>::contains_key(&_who), Error::<T>::UserNotExists);
ensure!(T::Currency::free_balance(&owner) >= amount, Error::<T>::MoneyNotEnough);
T::Currency::transfer(&sender, &_who, amount, ExistenceRequirement::KeepAlive)?;
Self::deposit_event(RawEvent::Withdraw(_who, amount));
Ok(())
}
#[weight = (T::WeightInfo::import_stake(), DispatchClass::Normal, Pays::No)]
pub fn import_stake(origin, _who: T::AccountId, amount: BalanceOf<T>) -> dispatch::DispatchResult {
let sender = ensure_signed(origin)?;
let owner = T::OwnerAddress::get();
let import_owner = T::ImportAddress::get();
ensure!(owner == sender, Error::<T>::PermissionDenied);
ensure!(UserInfoMap::<T>::contains_key(&_who), Error::<T>::UserNotExists);
T::Currency::transfer(&import_owner, &_who, amount, ExistenceRequirement::KeepAlive).map_err(|_| Error::<T>::MoneyNotEnough )?;
T::Currency::reserve(&_who, amount).map_err(|_| Error::<T>::MoneyNotEnough )?;
<StakePool::<T>>::put(Self::stake_pool() + amount);
<UserStake::<T>>::insert(&_who, Self::user_stake(&_who) + amount);
Self::deposit_event(RawEvent::Stake(_who, amount));
Ok(())
}
#[weight = (T::WeightInfo::modify_user(), DispatchClass::Normal, Pays::No)]
pub fn modify_user(origin, _who: T::AccountId, account: Vec<u8>, referrer_account: Vec<u8>) -> dispatch::DispatchResult {
let sender = ensure_signed(origin)?;
let owner = T::OwnerAddress::get();
ensure!(owner == sender, Error::<T>::PermissionDenied);
let _account_str = core::str::from_utf8(&account).unwrap().to_lowercase();
ensure!(_account_str.len() <= 7, Error::<T>::AccountFormatIsWrong);
ensure!(_account_str != "gametop", Error::<T>::AccountFormatIsWrong);
let _account = _account_str.as_bytes().to_vec();
let _referrer_account_str = core::str::from_utf8(&referrer_account).unwrap().to_lowercase();
let _referrer_account = _referrer_account_str.as_bytes().to_vec();
ensure!(AccountMap::<T>::contains_key(_account.clone()), Error::<T>::UserNotExists);
let _old_who = Self::account_map(_account.clone());
<UserInfoMap::<T>>::remove(&_old_who);
let user_info = UserInfo{
account: _account.clone(),
referrer_account: _referrer_account.clone(),
};
<UserInfoMap::<T>>::insert(&_who, user_info);
<AccountMap::<T>>::insert(_account.clone(), &_who);
Self::deposit_event(RawEvent::ModifyUser(_who, _account, _referrer_account));
Ok(())
}
}
}
impl<T: Config> Module<T> {
}
| true |
38b7f741a79370f67e8463a7ed77c9b9f1473cac
|
Rust
|
roelvanduijnhoven/adventofcode-2020
|
/day4/src/main.rs
|
UTF-8
| 567 | 3.015625 | 3 |
[] |
no_license
|
mod password;
mod validator;
use password::Password;
use validator::is_valid_pasword;
use std::fs;
fn main() {
let content = fs::read_to_string("assets/day4.in").expect("Something went wrong reading the file");
let passwords: Vec<Password> = content
.split("\n\n")
.map(|input| Password::from_string(input))
.collect();
let mut valid_passwords = 0;
for password in passwords {
if is_valid_pasword(&password) {
valid_passwords += 1;
}
}
println!("{} valid passwords", valid_passwords);
}
| true |
559e60a6f159f702415950fe3c481a78cf20250d
|
Rust
|
timothee-haudebourg/bottle
|
/src/remote.rs
|
UTF-8
| 6,939 | 2.65625 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::marker::Unsize;
use std::ops::{DispatchFromDyn, CoerceUnsized};
use std::sync::{Arc, Weak};
use std::cell::RefCell;
use std::mem::MaybeUninit;
use std::hash::{Hash, Hasher};
use std::collections::VecDeque;
use crate::{
Output,
Receiver,
Event,
EventQueueRef,
Handler,
Future,
future::LocalFuture,
Local,
ThreadLocal,
Emitter,
SubscriptionEvent,
Pending,
pending
};
pub struct Actor<T: ?Sized> {
// pub(crate) inbox: VecDeque<(Box<dyn Pending>, Arc<Mutex<pending::FutureState>>)>,
pub(crate) inbox: VecDeque<Box<dyn Pending>>,
pub(crate) is_busy: bool,
pub(crate) data: T
}
impl<T: ?Sized> Actor<T> {
/// Must be called from the actor thread.
pub(crate) unsafe fn post<E: Event>(&mut self, event: E) -> Output<E::Response> where T: 'static + Handler<E> {
let local = Receiver::new(&mut self.data);
local.handle(event)
}
pub(crate) unsafe fn init(&mut self, mut value: T) where T: Sized {
std::mem::swap(&mut self.data, &mut value);
std::mem::forget(value)
}
}
pub(crate) struct Inner<T: ?Sized> {
pub(crate) queue: EventQueueRef, // + 8
pub(crate) actor: RefCell<Actor<T>>
}
/// A pointer to a remote actor.
pub struct Remote<T: ?Sized> {
pub(crate) inner: Arc<Inner<T>> // + 8
}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Remote<U>> for Remote<T> {}
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Remote<U>> for Remote<T> {}
unsafe impl<T: ?Sized> Send for Remote<T> {}
unsafe impl<T: ?Sized> Sync for Remote<T> {}
impl<T: ?Sized> Remote<T> {
pub fn from<F>(queue: EventQueueRef, constructor: F) -> Remote<T> where T: 'static + Sized, F: 'static + Send + FnOnce() -> T {
unsafe {
let remote = Remote {
inner: Arc::new(Inner {
queue: queue,
actor: RefCell::new(Actor {
inbox: VecDeque::new(),
is_busy: false,
// Why it is safe.
// [1] We know the value won't be touched before initialization: the first
// message received by the remote pointer is the initialization request.
// This is because messages are processed in order in the queue. That is
// why (among other things) posting a message directly to a remote
// actor is unsafe.
// [2] We know the actor won't be dropped before initialization: the
// initialization request message holds a copy of the remote.
data: MaybeUninit::uninit().assume_init()
})
})
};
remote.inner.queue.request_initialization(remote.clone(), constructor);
remote
}
}
pub fn new(queue: EventQueueRef, value: T) -> Remote<T> where T: Send + Sized {
Remote {
inner: Arc::new(Inner {
queue: queue,
actor: RefCell::new(Actor {
inbox: VecDeque::new(),
is_busy: false,
data: value
})
})
}
}
pub fn as_ptr(&self) -> *const T {
let actor_ptr = self.inner.actor.as_ptr();
unsafe {
&(*actor_ptr).data
}
}
pub(crate) fn from_inner(inner: Arc<Inner<T>>) -> Remote<T> {
Remote {
inner
}
}
pub fn queue(&self) -> &EventQueueRef {
&self.inner.queue
}
/// Convert this pointer to a local pointer.
///
/// Return a local pointer to this pointer actor if `local` resides in the same thread as
/// the pointed actor, or `None`.
/// The `local` object is used as a proof that the conversion is valid.
///
/// # Safety
/// Even if the actor resides in the local thread, it may not be initialized yet.
/// As such, it is impossible to cast a remote pointer to a local pointer in a safe way.
/// Caller must ensure that the remote actor has not been created with [`Remote::from`], or
/// that it has been initialized.
pub unsafe fn local_to<L: ThreadLocal>(&self, local: &L) -> Option<Local<T>> {
if self.queue() == local.queue() {
Some(Local::from_inner(self.inner.clone()))
} else {
None
}
}
pub fn send<E: Event>(&self, event: E) -> Future<T, E::Response> where E: 'static, T: 'static + Handler<E> {
self.inner.queue.push(self.clone(), event)
}
pub(crate) fn post<E: Event>(&self, pending: Box<pending::ToReceive<E, T>>) -> LocalFuture<T, E::Response> where E: 'static, T: 'static + Handler<E> {
let future_state = pending.state().clone();
{
let mut actor = self.inner.actor.borrow_mut();
if actor.is_busy || !actor.inbox.is_empty() {
actor.inbox.push_front(pending);
return LocalFuture::new(future_state)
}
}
pending.process();
LocalFuture::new(future_state)
}
pub(crate) fn post_any(&self, pending: Box<dyn Pending>) {
{
let mut actor = self.inner.actor.borrow_mut();
if actor.is_busy || !actor.inbox.is_empty() {
actor.inbox.push_front(pending);
return
}
}
pending.process()
}
/// Restart the remote events execution.
///
/// This must be called from the actor's thread,
/// and only when no futures bound to this actor are executing.
pub(crate) unsafe fn restart(&self) {
// check if there is any pending events.
let pending = {
let mut actor = self.inner.actor.borrow_mut();
actor.is_busy = false;
actor.inbox.pop_back()
};
// if there is, process it since the actor is not busy anymore.
if let Some(pending) = pending {
pending.process()
}
}
pub fn subscribe<E: Event>(&self, subscriber: Remote<dyn Handler<E>>) -> Future<T, bool> where E: 'static, T: 'static + Emitter<E> {
self.send(SubscriptionEvent::Subscribe(subscriber))
}
pub fn downgrade(&self) -> WeakRemote<T> {
WeakRemote {
inner: Arc::downgrade(&self.inner)
}
}
}
impl<T: ?Sized> Clone for Remote<T> {
fn clone(&self) -> Remote<T> {
Remote {
inner: self.inner.clone()
}
}
}
impl<T: ?Sized> PartialEq for Remote<T> {
fn eq(&self, other: &Remote<T>) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
impl<T: ?Sized> Eq for Remote<T> {}
impl<T: ?Sized> Hash for Remote<T> {
fn hash<H: Hasher>(&self, h: &mut H) {
(&*self.inner as *const Inner<T>).hash(h)
}
}
/// A pointer to a remote actor.
pub struct WeakRemote<T: ?Sized> {
pub(crate) inner: Weak<Inner<T>>
}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WeakRemote<U>> for WeakRemote<T> {}
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<WeakRemote<U>> for WeakRemote<T> {}
unsafe impl<T: ?Sized> Send for WeakRemote<T> {}
unsafe impl<T: ?Sized> Sync for WeakRemote<T> {}
impl<T: ?Sized> WeakRemote<T> {
pub fn upgrade(&self) -> Option<Remote<T>> {
if let Some(inner) = self.inner.upgrade() {
Some(Remote {
inner
})
} else {
None
}
}
pub fn send<E: Event>(&self, event: E) -> Option<Future<T, E::Response>> where E: 'static, T: 'static + Handler<E> {
if let Some(remote) = self.upgrade() {
Some(remote.send(event))
} else {
None
}
}
}
impl<T: ?Sized> Clone for WeakRemote<T> {
fn clone(&self) -> WeakRemote<T> {
WeakRemote {
inner: self.inner.clone()
}
}
}
impl<T: ?Sized> PartialEq for WeakRemote<T> {
fn eq(&self, other: &WeakRemote<T>) -> bool {
Weak::ptr_eq(&self.inner, &other.inner)
}
}
impl<T: ?Sized> Eq for WeakRemote<T> {}
| true |
d16700e3aaf6ff4f32b40ca23eafa8fed90009cc
|
Rust
|
robjsliwa/mem_query
|
/wasm/src/memory.rs
|
UTF-8
| 1,257 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
use memquery::errors::Error;
use serde_json::{json, Value};
#[no_mangle]
pub fn alloc(len: usize) -> *mut u8 {
let mut buf = Vec::with_capacity(len);
let ptr = buf.as_mut_ptr();
std::mem::forget(buf);
ptr
}
#[no_mangle]
pub unsafe fn dealloc(ptr: *mut u8, size: usize) {
// take ownership and deallocates
let _ = Vec::from_raw_parts(ptr, size, size);
}
pub unsafe fn string_from_ptr(ptr: *mut u8, len: usize) -> String {
let data = Vec::from_raw_parts(ptr, len, len);
String::from_utf8_lossy(&data[..]).into_owned()
}
pub unsafe fn string_to_ptr(value: &str) -> *mut u8 {
let mut b: Vec<u8> = value.as_bytes().iter().cloned().collect();
b.push(0);
let ptr = b.as_mut_ptr();
std::mem::forget(b);
ptr
}
pub unsafe fn json_from_ptr(ptr: *mut u8, len: usize) -> Result<Value, Error> {
let jsonstr = string_from_ptr(ptr, len);
let v = serde_json::from_str::<Value>(&jsonstr)?;
Ok(v)
}
pub unsafe fn json_to_ptr(jsvalue: &Value) -> *mut u8 {
let jsvalstr = jsvalue.to_string();
string_to_ptr(&jsvalstr)
}
pub unsafe fn result_to_ptr(result: Result<&Value, Error>) -> *mut u8 {
match result {
Ok(v) => json_to_ptr(&json!({ "value": v })),
Err(e) => json_to_ptr(&json!({ "error": json!(e.to_string()) })),
}
}
| true |
f09ebd52868a303657c589a783e22f08885f7c2b
|
Rust
|
elizlotto/relay
|
/compiler/crates/graphql-transforms/src/skip_unreachable_node.rs
|
UTF-8
| 8,090 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use fnv::FnvHashMap;
use graphql_ir::{
Condition, ConditionValue, FragmentDefinition, FragmentSpread, Program, Selection, Transformed,
TransformedMulti, TransformedValue, Transformer,
};
use interner::StringKey;
use std::sync::Arc;
pub fn skip_unreachable_node(program: &Program) -> Program {
let fragments = program
.fragments()
.filter_map(|fragment| {
if fragment.selections.is_empty() {
None
} else {
Some((fragment.name.item, (Arc::clone(fragment), None)))
}
})
.collect();
let mut skip_unreachable_node_transform = SkipUnreachableNodeTransform::new(fragments);
skip_unreachable_node_transform
.transform_program(program)
.replace_or_else(|| program.clone())
}
type VisitedFragments = FnvHashMap<
StringKey,
(
Arc<FragmentDefinition>,
Option<Transformed<FragmentDefinition>>,
),
>;
pub struct SkipUnreachableNodeTransform {
visited_fragments: VisitedFragments,
}
impl Transformer for SkipUnreachableNodeTransform {
const NAME: &'static str = "SkipUnreachableNodeTransform";
const VISIT_ARGUMENTS: bool = true;
const VISIT_DIRECTIVES: bool = true;
fn transform_program(&mut self, program: &Program) -> TransformedValue<Program> {
// Iterate over the operation ASTs. Whenever we encounter a FragmentSpread (by way of
// fn transform_fragment_spread) look up that the associated FragmentDefinition.
// Crawl that FragmentDefinition for other FragmentSpreads and repeat.
// Delete that FragmentSpread if the associated FragmentDefinition was deleted.
//
// Throughout, when we encounter a condition node with a constant predicate, either remove
// it or replace it with its contents.
//
// @include(if: false) => remove
// @skip(if: true) => remove
// @include(if: true) => replace with contents
// @include(if: false) => replace with contents
//
// Removal of a condition or spread can result in a FragmentDefinition being deleted.
let mut next_program = Program::new(Arc::clone(&program.schema));
let mut has_changes = false;
for operation in program.operations() {
match self.transform_operation(operation) {
Transformed::Delete => has_changes = true,
Transformed::Keep => next_program.insert_operation(Arc::clone(operation)),
Transformed::Replace(replacement) => {
has_changes = true;
next_program.insert_operation(Arc::new(replacement))
}
}
}
for fragment in self.visited_fragments.values() {
match fragment {
(_, None) | (_, Some(Transformed::Delete)) => {
has_changes = true;
}
(fragment, Some(Transformed::Keep)) => {
next_program.insert_fragment(Arc::clone(fragment));
}
(_, Some(Transformed::Replace(replacement))) => {
next_program.insert_fragment(Arc::new(replacement.clone()));
has_changes = true;
}
}
}
if has_changes {
TransformedValue::Replace(next_program)
} else {
TransformedValue::Keep
}
}
fn transform_fragment(
&mut self,
fragment: &FragmentDefinition,
) -> Transformed<FragmentDefinition> {
// Remove the fragment with empty selections
let selections = self.transform_selections(&fragment.selections);
if let TransformedValue::Replace(selections) = &selections {
if selections.is_empty() {
return Transformed::Delete;
}
}
let directives = self.transform_directives(&fragment.directives);
if selections.should_keep() && directives.should_keep() {
return Transformed::Keep;
}
Transformed::Replace(FragmentDefinition {
directives: directives.replace_or_else(|| fragment.directives.clone()),
selections: selections.replace_or_else(|| fragment.selections.clone()),
..fragment.clone()
})
}
fn transform_selections(
&mut self,
selections: &[Selection],
) -> TransformedValue<Vec<Selection>> {
self.transform_list_multi(selections, Self::map_selection_multi)
}
fn transform_fragment_spread(&mut self, spread: &FragmentSpread) -> Transformed<Selection> {
if self.should_delete_fragment_definition(spread.fragment.item) {
Transformed::Delete
} else {
Transformed::Keep
}
}
}
impl SkipUnreachableNodeTransform {
pub fn new(visited_fragments: VisitedFragments) -> Self {
Self { visited_fragments }
}
fn should_delete_fragment_definition(&mut self, key: StringKey) -> bool {
let fragment = {
let (fragment, visited_opt) = if let Some(entry) = self.visited_fragments.get(&key) {
entry
} else {
return true;
};
if let Some(visited) = visited_opt {
return matches!(visited, Transformed::Delete);
}
Arc::clone(fragment)
};
let transformed = self.transform_fragment(&fragment);
let should_delete = matches!(transformed, Transformed::Delete);
// N.B. we must call self.visited_fragments.get* twice, because we cannot have
// a reference to visited_opt and call transform_segment, which requires an
// exclusive reference to self.
let (_fragment, visited_opt) = self.visited_fragments.get_mut(&key).unwrap();
*visited_opt = Some(transformed);
should_delete
}
fn map_selection_multi(&mut self, selection: &Selection) -> TransformedMulti<Selection> {
match selection {
Selection::FragmentSpread(selection) => {
self.transform_fragment_spread(selection).into()
}
Selection::InlineFragment(selection) => {
self.transform_inline_fragment(selection).into()
}
Selection::LinkedField(selection) => self.transform_linked_field(selection).into(),
Selection::ScalarField(selection) => self.transform_scalar_field(selection).into(),
Selection::Condition(condition) => self.transform_constant_conditions(condition),
}
}
fn transform_constant_conditions(
&mut self,
condition: &Condition,
) -> TransformedMulti<Selection> {
if let ConditionValue::Constant(b) = condition.value {
// passing_value == "what the value needs to be in order to include the contents"
// in other words, @skip has passing_value of false
// and @include has passing_value of true
//
// so, b == condition.passing_value implies that the condition is redundant,
// and b != condition.passing_value implies that the whole node can be removed
let keep_contents = b == condition.passing_value;
if keep_contents {
// @include(if: true) or @skip(if: false)
let contents = match self.transform_selections(&condition.selections) {
TransformedValue::Keep => &condition.selections,
TransformedValue::Replace(ref t) => t,
}
.clone();
TransformedMulti::ReplaceMultiple(contents)
} else {
// @include(if: false) or @skip(if: true)
TransformedMulti::Delete
}
} else {
self.transform_condition(condition).into()
}
}
}
| true |
a4099574fdeb1da1a782cf6ce7bfe2012acb8f19
|
Rust
|
ibvd/app_config
|
/src/config.rs
|
UTF-8
| 9,220 | 3.015625 | 3 |
[] |
no_license
|
use shellexpand::tilde;
use std::fs;
use crate::hooks::{CommandConf, FileConf, Hook, RawConf, TemplateConf};
use crate::providers::{AppCfgConf, MockConf, ParamStoreConf, Provider};
type TResult<T> = Result<T, toml::de::Error>;
// This is a bit hard to read, but here is the deal.
// There is a BTree in <maps> that contains the structure of the config file
// There is a Vec in <hooks> where we store our final structs
// This macro will loop over every hook in <maps>, convert the hook into a struct
// and push the result into <hooks>.
#[macro_export]
macro_rules! parse_hooks {
( $( $maps:expr, $hooks:expr, $($section:expr, $conf:ty),+)? ) => {
{ $(
for hook_section in $maps["hooks"].as_table().unwrap().keys() {
$(
if hook_section.as_str() == $section {
let conf: TResult<$conf> = $maps["hooks"][$section]
.clone().try_into();
match conf {
Err(e) => config_err(&e, $section),
Ok(conf) => {
let x = conf.convert();
$hooks.push( Box::new(x) );
},
}
}
)+
}
)? }
};
}
// Like for parse_hooks above, but instead we only want one provider. So it is
// an if / else if / else if ... / chain. Erroring out if nothing matches.
// There is a BTree in <maps> that contains the structure of the config file
// This macro will check for each provider in <maps>, convert the provider into a
// struct and save the result into <provider>.
#[macro_export]
macro_rules! parse_providers {
( $( $maps:expr, $provider_type:expr, $provider:expr,
$($section:expr, $conf:ty),+)? ) => {
{ $(
if ! true { }
$(
// AppCfg
else if $provider_type.as_str() == $section {
let conf: TResult<$conf> = $maps["providers"][$section]
.clone().try_into();
// Pretty print any parsing errors
if let Err(e) = &conf { config_err(&e, $section); }
let x = conf.unwrap().convert();
$provider = Box::new(x);
}
)+
// If no valid provider found, panic with an error
else {
eprintln!("Error, no valid providers found");
std::process::exit(exitcode::CONFIG);
}
)? }
};
}
/// Config:
/// Parse toml config file and validate all the parameters
#[derive(Debug)]
pub struct Config {
pub provider: Box<dyn Provider>,
pub hooks: Vec<Box<dyn Hook>>,
}
impl Config {
/// Read toml formatted config file located @ <path>,
/// and parse it into a Config struct.
/// Will panic if it can not locate or parse the file.
pub fn from_file(path: &str) -> Config {
let expanded_path = String::from(tilde(&path));
let file_contents: String = match fs::read_to_string(expanded_path) {
Ok(file_contents) => file_contents,
Err(e) => {
eprintln!("Could not open {}: {}", path, e);
std::process::exit(exitcode::OSFILE);
}
};
let toml_maps: toml::Value = match toml::from_str(&file_contents) {
Ok(config) => config,
Err(e) => {
eprintln!("Could not parse {}: {}", path, e);
std::process::exit(exitcode::CONFIG);
}
};
// Extract provider from config file
let p: Box<dyn Provider> = Config::get_provider(&toml_maps);
// Extract hooks from config file
let h: Vec<Box<dyn Hook>> = Config::get_hooks(&toml_maps);
Config {
provider: p,
hooks: h,
}
}
/// Parse the config file looking for one and only one backend provider
/// Will panic on any errors.
fn get_provider(maps: &toml::Value) -> Box<dyn Provider> {
// Validate Providers are present
if !maps.as_table().unwrap().contains_key("providers") {
eprintln!("Error, configuation must include a backend provider");
std::process::exit(exitcode::CONFIG);
}
if maps["providers"].as_table().unwrap().len() != 1 {
eprintln!("Error, configuation must include only one backend provider");
std::process::exit(exitcode::CONFIG);
}
let mut provider: Box<dyn Provider>;
// This is done just to let us use a macro to parse the providers. Rust
// gets confused. We will panic before this provider ever gets further.
provider = Box::new(
MockConf {
data: "".to_string(),
}
.convert(),
);
// Since we know we have just one provider key, let's get it
let provider_type = maps["providers"].as_table().unwrap().keys().last().unwrap();
// This macro will find the configured provider in <maps> and instantiate
// the provider struct in <provider>. It will panic if no provider is found
// or if there is a parsing error in the provider section.
parse_providers!(
maps, provider_type, provider,
"mock", MockConf,
"appconfig", AppCfgConf,
"param_store", ParamStoreConf
);
provider
}
/// Parse the config file looking for hooks
/// The order in the vec will be the same as specified in the config file
/// Will panic on any errors.
// For odering to work, the toml dependency must feature preserve order
// e.g. # Cargo.toml
// e.g. toml = { version = "0.5.7", features=["preserve_order"] }
fn get_hooks(maps: &toml::Value) -> Vec<Box<dyn Hook>> {
let mut hooks: Vec<Box<dyn Hook>> = Vec::new();
// Validate there are at least some hooks in the config file
if !maps.as_table().unwrap().contains_key("hooks") {
return hooks;
}
// This macro will instantiate a struct for each hook found in
// maps["hooks"], and push that hook into the 'hooks' vector
parse_hooks!(
maps, hooks,
"template", TemplateConf,
"file", FileConf,
"raw", RawConf,
"command", CommandConf
);
hooks
}
}
fn config_err(e: &toml::de::Error, section: &str) {
eprintln!("Could not parse {} config: {:#?}", section, e);
std::process::exit(exitcode::CONFIG);
}
#[cfg(test)]
mod test {
use super::*;
use crate::hooks::template::DataType;
use crate::hooks::{Command, File, Hook, Template};
use crate::providers::AppCfg;
fn gen_full_config() -> String {
"[providers.appconfig]
application = \"myApp\"
environment = \"dev\"
configuration = \"myConf\"
client_id = \"42\"
[hooks.template]
file = \"./tests/test_template.tmpl\"
source_type = \"yaml\"
[hooks.file]
outfile = \"raw_output.txt\"
[hooks.command]
command = \"echo\"
pipe_data = true
"
.to_string()
}
fn gen_min_config() -> String {
"[providers.appconfig]
application = \"myApp\"
environment = \"dev\"
configuration = \"myConf\"
client_id = \"42\""
.to_string()
}
fn gen_appconfig_struct() -> AppCfg {
AppCfg::new(&"myApp", &"dev", &"myConf", &"42", &None)
}
fn gen_template_struct() -> Template {
Template::new(
&String::from(
"{{#each hosts}}
[Peer]
EndPoint = {{this.name}}
PublicKey = {{this.public_key}}
{{/each}}
",
),
DataType::YAML,
None,
)
}
fn gen_file_struct() -> File {
File::new(&"raw_output.txt")
}
fn gen_command_struct() -> Command {
Command::new(&"echo", true)
}
#[test]
// We can not compare structs directly since they are hidden behind a
// dynamic trait, The compiler has no idea what struct will be there at
// compile time. So the best we can do is print them and compare the
// output strings from the Debug trait.
fn test_get_provider() {
let config_str = gen_full_config();
let tml: toml::Value = toml::from_str(&config_str).unwrap();
let expected_str = format!("{:?}", gen_appconfig_struct());
let provider_str = format!("{:?}", Config::get_provider(&tml));
assert_eq!(expected_str, provider_str);
}
#[test]
fn test_get_hooks() {
let config_str = gen_full_config();
let tml: toml::Value = toml::from_str(&config_str).unwrap();
let h = Config::get_hooks(&tml);
let hook_str = format!("{:?}", h);
let expected: Vec<Box<dyn Hook>> = vec![
Box::new(gen_template_struct()),
Box::new(gen_file_struct()),
Box::new(gen_command_struct()),
];
let expected_str = format!("{:?}", expected);
assert_eq!(hook_str, expected_str);
}
#[test]
fn test_get_empty_hooks() {
let config_str = gen_min_config();
let tml: toml::Value = toml::from_str(&config_str).unwrap();
let h = Config::get_hooks(&tml);
let hook_str = format!("{:?}", h);
let expected_str = format!("[]");
assert_eq!(expected_str, hook_str);
}
}
| true |
e8848762735d2306b253523c3fdc1f09a7a15934
|
Rust
|
lythesia/leet
|
/rs/src/quests/zero_one_matrix.rs
|
UTF-8
| 2,042 | 3.453125 | 3 |
[] |
no_license
|
/**
* [542] 01 Matrix
*
* Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]
Example 2:
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
There is at least one 0 in mat.
*/
pub struct Solution {}
// submission codes start here
use std::cmp::min;
use std::collections::VecDeque;
const DIR: [(i32, i32); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)];
impl Solution {
pub fn update_matrix(mut mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let (m, n) = (mat.len(), mat[0].len());
let mut queue = VecDeque::new();
let mut ans = mat.clone();
for k in 0..m*n {
let (i, j) = (k/n, k%n);
if mat[i][j] == 0 {
queue.push_back((i, j));
ans[i][j] = 0;
} else {
ans[i][j] = 10010;
}
}
while let Some((x, y)) = queue.pop_front() {
for (dx, dy) in DIR {
let (nx, ny) = (x as i32 + dx, y as i32 + dy);
if nx >=0 && nx < m as i32 && ny >= 0 && ny < n as i32 {
let (i, j) = (nx as usize, ny as usize);
if mat[i][j] != 0 {
mat[i][j] = 0;
queue.push_back((i, j));
ans[i][j] = min(ans[i][j], ans[x][y] + 1);
}
}
}
}
ans
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
// assert_eq!(vec_vec![[0,0,0],[0,1,0],[0,0,0]], Solution::update_matrix(vec_vec![[0,0,0],[0,1,0],[0,0,0]]));
assert_eq!(vec_vec![[0,0,0],[0,1,0],[1,2,1]],
Solution::update_matrix(vec_vec![[0,0,0],[0,1,0],[1,1,1]]));
}
}
| true |
e034d1c41eea095fcdd2fe3a8e708021fc36fa74
|
Rust
|
IThawk/rust-project
|
/rust-master/src/librustc_target/spec/x86_64_unknown_uefi.rs
|
UTF-8
| 2,697 | 2.671875 | 3 |
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
// This defines the amd64 target for UEFI systems as described in the UEFI specification. See the
// uefi-base module for generic UEFI options. On x86_64 systems (mostly called "x64" in the spec)
// UEFI systems always run in long-mode, have the interrupt-controller pre-configured and force a
// single-CPU execution.
// The win64 ABI is used. It differs from the sysv64 ABI, so we must use a windows target with
// LLVM. "x86_64-unknown-windows" is used to get the minimal subset of windows-specific features.
use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::uefi_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
// We disable MMX and SSE for now, even though UEFI allows using them. Problem is, you have to
// enable these CPU features explicitly before their first use, otherwise their instructions
// will trigger an exception. Rust does not inject any code that enables AVX/MMX/SSE
// instruction sets, so this must be done by the firmware. However, existing firmware is known
// to leave these uninitialized, thus triggering exceptions if we make use of them. Which is
// why we avoid them and instead use soft-floats. This is also what GRUB and friends did so
// far.
// If you initialize FP units yourself, you can override these flags with custom linker
// arguments, thus giving you access to full MMX/SSE acceleration.
base.features = "-mmx,-sse,+soft-float".to_string();
// UEFI systems run without a host OS, hence we cannot assume any code locality. We must tell
// LLVM to expect code to reference any address in the address-space. The "large" code-model
// places no locality-restrictions, so it fits well here.
base.code_model = Some("large".to_string());
// UEFI mirrors the calling-conventions used on windows. In case of x86-64 this means small
// structs will be returned as int. This shouldn't matter much, since the restrictions placed
// by the UEFI specifications forbid any ABI to return structures.
base.abi_return_struct_as_int = true;
Ok(Target {
llvm_target: "x86_64-unknown-windows".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:w-i64:64-f80:128-n8:16:32:64-S128".to_string(),
target_os: "uefi".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
arch: "x86_64".to_string(),
linker_flavor: LinkerFlavor::Lld(LldFlavor::Link),
options: base,
})
}
| true |
e814cb700f059db3d71a58e6755a708fcc2389be
|
Rust
|
ogoestcc/database
|
/src/models/wherables/user_ratings.rs
|
UTF-8
| 1,608 | 2.828125 | 3 |
[] |
no_license
|
use crate::{
database::{Filter, Wherable},
models::{
self,
wherables::{Rating, User},
},
services::types::ratings::WhereClause,
};
#[cfg(feature = "postgres")]
use queler::clause::Clause;
#[derive(Debug, Clone, Default)]
pub struct UserRatings(User, Rating);
impl Wherable for UserRatings {
#[cfg(feature = "postgres")]
fn clause(&self) -> Clause {
let user = self.0.clause();
let rating = self.1.clause();
queler::clause! { user, rating }
}
}
impl From<Rating> for UserRatings {
fn from(w: Rating) -> Self {
(User::default(), w).into()
}
}
impl From<User> for UserRatings {
fn from(w: User) -> Self {
(w, Rating::default()).into()
}
}
impl From<WhereClause> for UserRatings {
fn from(w: WhereClause) -> Self {
(User::default(), Rating::from(w)).into()
}
}
impl<U: Into<User>, R: Into<Rating>> From<(U, R)> for UserRatings {
fn from((uw, rw): (U, R)) -> Self {
Self(uw.into(), rw.into())
}
}
impl<B: Into<UserRatings> + Clone> From<&B> for UserRatings {
fn from(item: &B) -> Self {
item.clone().into()
}
}
impl Filter<models::Users> for UserRatings {
fn filter(&self, user: &models::Users) -> bool {
self.0.filter(user)
}
}
impl Filter<models::Ratings> for UserRatings {
fn filter(&self, rating: &models::Ratings) -> bool {
self.1.filter(rating)
}
}
impl Filter<models::UserRatings> for UserRatings {
fn filter(&self, user_rating: &models::UserRatings) -> bool {
self.0.filter(&user_rating.user)
}
}
| true |
129d85fbb43499387a93954c707b46a7fe270f5e
|
Rust
|
mactsouk/introRustLC
|
/day2/L5/http_server/src/main.rs
|
UTF-8
| 543 | 2.6875 | 3 |
[] |
no_license
|
extern crate hyper;
extern crate rand;
use rand::Rng;
use hyper::Server;
use hyper::server::Request;
use hyper::server::Response;
fn hello(_: Request, res: Response) {
let number = rand::thread_rng().gen_range(0, 100);
let data = format!("{}\r\n", number);
res.send(data.as_bytes()).expect("Failed to send data!");
}
fn main() {
let port = ::std::env::args().nth(1).unwrap();
let ip_and_port = "127.0.0.1".to_string() + ":" + &port;
let ip_port: &str = &ip_and_port;
Server::http(ip_port).unwrap().handle(hello).unwrap();
}
| true |
6794de5f0987c7af25a3e1d008b5c33ff23df93f
|
Rust
|
MutexUnlocked/Sinope
|
/src/block.rs
|
UTF-8
| 2,692 | 3.09375 | 3 |
[] |
no_license
|
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use sha2::{Sha256, Digest};
use crate::proof::Proof;
use crate::transcation::Transaction;
pub enum BarErr {
Nothing
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Block {
nonce: Option<u64>,
timestamp: Option<u128>,
transactions: Option<Vec<Transaction>>,
hash: Option<Vec<u8>>,
prev_hash: Option<Vec<u8>>,
}
impl Block {
// Creates a new block
pub fn new(prev_hash: Vec<u8>, transactions: Vec<Transaction>) -> Self {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards!");
let timestamp = since_the_epoch.as_millis();
//TODO: Implement proof of work and fix nonce
let mut b = Block{
nonce: None,
timestamp: Some(timestamp),
transactions: Some(transactions),
hash: None,
prev_hash: Some(prev_hash),
};
let mut proof = Proof::new(&mut b);
let (n, h) = proof.run();
b.nonce = Some(n);
b.hash = Some(h);
b
}
pub fn hash_transactions(&self) -> Vec<u8>{
let mut t_hash: Vec<u8> = Vec::new();
for t in self.transactions().ok().unwrap().iter(){
t_hash.append(&mut t.id.clone().unwrap());
}
t_hash
}
// Immutable access.
pub fn transactions(&self) -> Result<&Vec<Transaction>, BarErr> {
match self.transactions {
Some(ref x) => Ok(x),
None => Err(BarErr::Nothing)
}
}
pub fn timestamp(&self) -> Result<&u128, BarErr> {
match self.timestamp {
Some(ref x) => Ok(x),
None => Err(BarErr::Nothing)
}
}
pub fn hash(&self) -> Result<&Vec<u8>, BarErr> {
match self.hash {
Some(ref x) => Ok(x),
None => Err(BarErr::Nothing)
}
}
pub fn prev_hash(&self) -> Result<&Vec<u8>, BarErr> {
match self.prev_hash {
Some(ref x) => Ok(x),
None => Err(BarErr::Nothing)
}
}
pub fn nonce(&self) -> Result<&u64, BarErr> {
match self.nonce {
Some(ref x) => Ok(x),
None => Err(BarErr::Nothing)
}
}
pub fn serialize(&self) -> Vec<u8>{
bincode::serialize(&self).unwrap()
}
pub fn deserialize(encoded: Vec<u8>) -> Block{
bincode::deserialize(&encoded[..]).unwrap()
}
pub fn genesis(coinbase: Vec<Transaction>) -> Self{
let v: Vec<u8> = vec![0;0];
let block = Block::new(v, coinbase);
block
}
}
| true |
a5c25d1b89008b8c39e781a71119a5da1c4d5b0b
|
Rust
|
matthew-mcallister/playstation-emulator
|
/src/cpu/operations/sltu.rs
|
UTF-8
| 1,327 | 3.390625 | 3 |
[] |
no_license
|
use crate::cpu::delay::Delay;
use crate::cpu::exception::Exception;
use crate::cpu::interconnect::Interconnect;
use crate::cpu::operations::Operation;
use crate::cpu::registers::Registers;
use crate::instruction::Instruction;
/// After that we encounter the instruction 0x0043082b which encodes the
/// “set on less than unsigned"(STLU) opcode:
///
/// sltu $1, $2, $3
///
/// This instruction compares the value of two registers ($2 and $3 in this case)
/// and sets the value of a third one ($1) to either 0 or 1 depending on the result
/// of the “less than" comparison:
pub struct Sltu {
instruction: Instruction
}
impl Sltu {
pub fn new(instruction: Instruction) -> impl Operation {
Sltu {
instruction
}
}
}
impl Operation for Sltu {
fn perform(&self, registers: &mut Registers, _: &mut Interconnect, _: &mut Delay) -> Result<(), Exception> {
let d = self.instruction.d();
let s = self.instruction.s();
let t = self.instruction.t();
let v = registers.reg(s) < registers.reg(t);
registers.set_reg(d, v as u32);
Ok(())
}
fn gnu(&self) -> String {
let d = self.instruction.d();
let s = self.instruction.s();
let t = self.instruction.t();
format!("SLTU {}, {}, {}", d, s, t)
}
}
| true |
51d360fa2882cf902cbdf30a83f0f8f563d0210e
|
Rust
|
gnoliyil/fuchsia
|
/src/lib/storage/vfs/rust/src/service/common.rs
|
UTF-8
| 8,832 | 2.515625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Code shared between several modules of the service implementation.
use {
fidl_fuchsia_io as fio,
fuchsia_zircon::Status,
libc::{S_IRUSR, S_IWUSR},
};
/// POSIX emulation layer access attributes for all services created with service().
pub const POSIX_READ_WRITE_PROTECTION_ATTRIBUTES: u32 = S_IRUSR | S_IWUSR;
/// Validate that the requested flags for a new connection are valid. It is a bit tricky as
/// depending on the presence of the `OPEN_FLAG_NODE_REFERENCE` flag we are effectively validating
/// two different cases: with `OPEN_FLAG_NODE_REFERENCE` the connection will be attached to the
/// service node itself, and without `OPEN_FLAG_NODE_REFERENCE` the connection will be forwarded to
/// the backing service.
///
/// `new_connection_validate_flags` will preserve `OPEN_FLAG_NODE_REFERENCE` to make it easier for
/// the caller to distinguish these two cases.
///
/// On success, returns the validated and cleaned flags. On failure, it returns a [`Status`]
/// indicating the problem.
///
/// Changing this function can be dangerous! Flags operations may have security implications.
pub fn new_connection_validate_flags(
mut flags: fio::OpenFlags,
mode: u32,
) -> Result<fio::OpenFlags, Status> {
// There should be no MODE_TYPE_* flags set, except for, possibly, MODE_TYPE_SERVICE when the
// target is a service.
if (mode & !fio::MODE_PROTECTION_MASK) & !fio::MODE_TYPE_SERVICE != 0 {
if mode & fio::MODE_TYPE_MASK == fio::MODE_TYPE_DIRECTORY {
return Err(Status::NOT_DIR);
} else if mode & fio::MODE_TYPE_MASK == fio::MODE_TYPE_FILE {
return Err(Status::NOT_FILE);
} else {
return Err(Status::INVALID_ARGS);
};
}
// A service is not a directory.
flags &= !fio::OpenFlags::NOT_DIRECTORY;
// For services any OPEN_FLAG_POSIX_* flags are ignored as they only apply to directories.
flags &= !(fio::OpenFlags::POSIX_WRITABLE | fio::OpenFlags::POSIX_EXECUTABLE);
if flags.intersects(fio::OpenFlags::DIRECTORY) {
return Err(Status::NOT_DIR);
}
if flags.intersects(fio::OpenFlags::NODE_REFERENCE) {
flags &= !(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
if flags.intersects(!fio::OPEN_FLAGS_ALLOWED_WITH_NODE_REFERENCE) {
return Err(Status::INVALID_ARGS);
}
flags &= fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::DESCRIBE;
return Ok(flags);
}
// All the flags we have already checked above and removed.
debug_assert!(!flags.intersects(
fio::OpenFlags::DIRECTORY
| fio::OpenFlags::NOT_DIRECTORY
| fio::OpenFlags::POSIX_WRITABLE
| fio::OpenFlags::POSIX_EXECUTABLE
| fio::OpenFlags::NODE_REFERENCE
));
// A service might only be connected to when read permissions are present.
if !flags.intersects(fio::OpenFlags::RIGHT_READABLE) {
return Err(Status::ACCESS_DENIED);
}
let allowed_flags =
fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE | fio::OpenFlags::DESCRIBE;
// Anything else is also not allowed.
if flags.intersects(!allowed_flags) {
return Err(Status::INVALID_ARGS);
}
Ok(flags)
}
#[cfg(test)]
mod tests {
use super::new_connection_validate_flags;
use {fidl_fuchsia_io as fio, fuchsia_zircon::Status};
/// Assertion for when `new_connection_validate_flags` should succeed => `ncvf_ok`.
fn ncvf_ok(flags: fio::OpenFlags, mode: u32, expected_new_flags: fio::OpenFlags) {
match new_connection_validate_flags(flags, mode) {
Ok(new_flags) => assert_eq!(
expected_new_flags, new_flags,
"new_connection_validate_flags returned unexpected set of flags.\n\
Expected: {:X}\n\
Actual: {:X}",
expected_new_flags, new_flags
),
Err(status) => panic!("new_connection_validate_flags failed. Status: {}", status),
}
}
/// Assertion for when `new_connection_validate_flags` should fail => `ncvf_err`.
fn ncvf_err(flags: fio::OpenFlags, mode: u32, expected_status: Status) {
match new_connection_validate_flags(flags, mode) {
Ok(new_flags) => panic!(
"new_connection_validate_flags should have failed.\n\
Got new flags: {:X}",
new_flags
),
Err(status) => assert_eq!(expected_status, status),
}
}
/// Common combination for the service tests.
const READ_WRITE: fio::OpenFlags = fio::OpenFlags::empty()
.union(fio::OpenFlags::RIGHT_READABLE)
.union(fio::OpenFlags::RIGHT_WRITABLE);
#[test]
fn node_reference_basic() {
// OPEN_FLAG_NODE_REFERENCE is preserved.
ncvf_ok(fio::OpenFlags::NODE_REFERENCE, 0, fio::OpenFlags::NODE_REFERENCE);
// Access flags are dropped.
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::RIGHT_READABLE,
0,
fio::OpenFlags::NODE_REFERENCE,
);
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::RIGHT_WRITABLE,
0,
fio::OpenFlags::NODE_REFERENCE,
);
// OPEN_FLAG_DESCRIBE is preserved.
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::DESCRIBE,
0,
fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::DESCRIBE,
);
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE | READ_WRITE | fio::OpenFlags::DESCRIBE,
0,
fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::DESCRIBE,
);
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::NOT_DIRECTORY,
0,
fio::OpenFlags::NODE_REFERENCE,
);
ncvf_err(fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::DIRECTORY, 0, Status::NOT_DIR);
}
#[test]
fn service_basic() {
// Access flags are required and preserved.
ncvf_ok(READ_WRITE, 0, READ_WRITE);
ncvf_ok(fio::OpenFlags::RIGHT_READABLE, 0, fio::OpenFlags::RIGHT_READABLE);
ncvf_err(fio::OpenFlags::RIGHT_WRITABLE, 0, Status::ACCESS_DENIED);
// OPEN_FLAG_DESCRIBE is allowed.
ncvf_ok(READ_WRITE | fio::OpenFlags::DESCRIBE, 0, READ_WRITE | fio::OpenFlags::DESCRIBE);
ncvf_ok(READ_WRITE | fio::OpenFlags::NOT_DIRECTORY, 0, READ_WRITE);
ncvf_err(READ_WRITE | fio::OpenFlags::DIRECTORY, 0, Status::NOT_DIR);
}
#[test]
fn node_reference_posix() {
// OPEN_FLAG_POSIX_* is ignored for services.
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE
| fio::OpenFlags::POSIX_WRITABLE
| fio::OpenFlags::POSIX_EXECUTABLE,
0,
fio::OpenFlags::NODE_REFERENCE,
);
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE
| fio::OpenFlags::DESCRIBE
| fio::OpenFlags::POSIX_WRITABLE
| fio::OpenFlags::POSIX_EXECUTABLE,
0,
fio::OpenFlags::NODE_REFERENCE | fio::OpenFlags::DESCRIBE,
);
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE
| READ_WRITE
| fio::OpenFlags::POSIX_WRITABLE
| fio::OpenFlags::POSIX_EXECUTABLE,
0,
fio::OpenFlags::NODE_REFERENCE,
);
}
#[test]
fn service_posix() {
// OPEN_FLAG_POSIX_* is ignored for services.
ncvf_ok(
READ_WRITE | fio::OpenFlags::POSIX_WRITABLE | fio::OpenFlags::POSIX_EXECUTABLE,
0,
READ_WRITE,
);
ncvf_ok(
READ_WRITE
| fio::OpenFlags::DESCRIBE
| fio::OpenFlags::POSIX_WRITABLE
| fio::OpenFlags::POSIX_EXECUTABLE,
0,
READ_WRITE | fio::OpenFlags::DESCRIBE,
);
}
#[test]
fn file() {
ncvf_err(fio::OpenFlags::NODE_REFERENCE, fio::MODE_TYPE_FILE, Status::NOT_FILE);
ncvf_err(READ_WRITE, fio::MODE_TYPE_FILE, Status::NOT_FILE);
}
#[test]
fn mode_directory() {
ncvf_err(fio::OpenFlags::NODE_REFERENCE, fio::MODE_TYPE_DIRECTORY, Status::NOT_DIR);
ncvf_err(READ_WRITE, fio::MODE_TYPE_DIRECTORY, Status::NOT_DIR);
}
#[test]
fn mode_service() {
ncvf_ok(
fio::OpenFlags::NODE_REFERENCE,
fio::MODE_TYPE_SERVICE,
fio::OpenFlags::NODE_REFERENCE,
);
ncvf_ok(READ_WRITE, fio::MODE_TYPE_SERVICE, READ_WRITE);
}
}
| true |
ae5e498414b2103a462c34dc7c5bca7a2e82fb93
|
Rust
|
IThawk/rust-project
|
/rust-master/src/test/ui/regions/regions-nested-fns.rs
|
UTF-8
| 427 | 2.875 | 3 |
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
fn ignore<T>(t: T) {}
fn nested<'x>(x: &'x isize) {
let y = 3;
let mut ay = &y; //~ ERROR E0495
ignore::<Box<dyn for<'z> FnMut(&'z isize)>>(Box::new(|z| {
ay = x;
ay = &y;
ay = z;
}));
ignore::< Box<dyn for<'z> FnMut(&'z isize) -> &'z isize>>(Box::new(|z| {
if false { return x; } //~ ERROR E0312
if false { return ay; }
return z;
}));
}
fn main() {}
| true |
644f86c7802c4316f45f256bc1dcec1f98b4ac28
|
Rust
|
karliss/bitflip
|
/src/encoding.rs
|
UTF-8
| 4,557 | 3.296875 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
use std::fs;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use std::str;
pub struct Encoding {
pub byte_to_char: [char; 256],
pub char_to_byte: HashMap<char, u8>,
}
impl Encoding {
fn new() -> Encoding {
Encoding {
byte_to_char: ['?'; 256],
char_to_byte: HashMap::new(),
}
}
fn get_encoding_dir() -> Result<PathBuf, std::io::Error> {
Ok(crate::resource::get_resource_dir()?.join("encodings"))
}
pub fn get_encoding(name: &str) -> Result<Encoding, std::io::Error> {
let encoding_dir = Encoding::get_encoding_dir()?;
Encoding::load(&encoding_dir.join(name))
}
pub fn load(path: &Path) -> Result<Encoding, std::io::Error> {
let mut result = Encoding::new();
let buf = fs::read_to_string(&path)?;
let mut i = 0;
let mut done = false;
for c in buf.chars() {
if i >= 256 {
break;
}
match c {
'\n' => {
if !done {
result.byte_to_char[i] = ' '; //editors tend to strip trailing space
result.char_to_byte.entry(' ').or_insert(i as u8);
} else {
done = false;
}
i += 1;
}
_ => {
if !done {
done = true;
result.byte_to_char[i] = c;
result.char_to_byte.entry(c).or_insert(i as u8);
}
}
}
}
if i != 256 {
return Err(Error::new(
ErrorKind::InvalidData,
format!("Incorrect height {} expected 256", i),
));
}
Ok(result)
}
pub fn decode_utf8<'a>(
&self,
mut input: str::Chars<'a>,
out: &mut [u8],
) -> Result<(usize, &'a str), std::io::Error> {
let mut produced = 0 as usize;
let n = out.len();
while produced < n {
if let Some(c) = input.next() {
if let Some(byte) = self.char_to_byte.get(&c) {
out[produced] = *byte;
produced += 1;
} else {
return Err(Error::from(ErrorKind::InvalidData));
}
} else {
return Ok((produced, ""));
}
}
Ok((produced, input.as_str()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn read_err() {
let encoding = Encoding::load(Path::new("doesn't exist"));
assert_eq!(encoding.is_err(), true);
}
#[test]
fn appproximate_437_check() {
let encoding = Encoding::get_encoding("437").unwrap();
assert_eq!(encoding.char_to_byte.get(&'a'), Some(&b'a'));
assert_eq!(encoding.char_to_byte.get(&'Z'), Some(&b'Z'));
assert_eq!(encoding.byte_to_char[b'a' as usize], 'a');
assert_eq!(encoding.byte_to_char[b'Z' as usize], 'Z');
//last symbol
assert_eq!(encoding.char_to_byte.get(&'\u{00a0}'), Some(&255));
assert_eq!(encoding.byte_to_char[255], '\u{00a0}');
// Non symetric matching and possibly empty line
assert_eq!(encoding.char_to_byte.get(&' '), Some(&0));
assert_eq!(encoding.byte_to_char[0], ' ');
assert_eq!(encoding.byte_to_char[b' ' as usize], ' ');
//low
assert_eq!(encoding.byte_to_char[1], '☺');
assert_eq!(encoding.char_to_byte.get(&'☺'), Some(&1));
//high
assert_eq!(encoding.byte_to_char[230], 'µ');
assert_eq!(encoding.char_to_byte.get(&'µ'), Some(&230));
//nonexisting
assert_eq!(encoding.char_to_byte.get(&'\n'), None);
}
#[test]
fn from_utf8() {
let encoding = Encoding::get_encoding("437").unwrap();
let mut buf = [0u8; 256];
let txt = "abcdefABCDEF123456";
let (len, tail) = encoding.decode_utf8(txt.chars(), &mut buf).unwrap();
assert_eq!(len, txt.len());
assert_eq!(&buf[..len], b"abcdefABCDEF123456");
assert_eq!(tail, "");
let mut buf = [0u8; 5];
let txt = "123456";
assert_eq!(
encoding.decode_utf8(txt.chars(), &mut buf).unwrap(),
(5, "6")
);
assert_eq!(&buf, b"12345");
assert!(encoding.decode_utf8("āēūž".chars(), &mut buf).is_err());
}
}
| true |
8ab23f14d9db3690a66fffe0b6da6bffd9bd1f17
|
Rust
|
byronwilliams/code-samples
|
/status.rs
|
UTF-8
| 1,642 | 2.90625 | 3 |
[] |
no_license
|
extern mod std;
extern mod extra;
use std::io;
use std::path;
use std::run::process_output;
use std::str;
use extra::time;
use std::rt::io::timer::sleep;
static GREEN: &'static str = "#00EE55";
static GREY: &'static str = "#DDDDDD";
fn load(filename: ~str) -> ~str {
let read_result: Result<@Reader, ~str>;
read_result = io::file_reader(~path::Path(filename));
match read_result {
Ok(file) => {
return file.read_c_str();
},
Err(e) => {
println(fmt!("Error reading lines: %?", e));
return ~"";
}
}
}
fn colour(s: ~str, c: &'static str) -> ~str {
return "\\" + c + "\\" + s;
}
fn run(hostname: &~str) {
let curTime = time::now();
let sDate: ~str = colour(curTime.strftime("%a %Y-%m-%d"),GREY);
let sTime: ~str = colour(curTime.strftime("%H:%M"),GREEN);
let sTZ: ~str = colour(curTime.strftime("%z"),GREY);
let acpiOutput = process_output(&"/usr/bin/acpi",&[]);
let acpiStatus = str::from_utf8(acpiOutput.output);
let parts = acpiStatus.word_iter().to_owned_vec();
let percentage = parts[3].trim_chars(&',');
let acpiThermalOutput = process_output(&"/usr/bin/acpi",&[~"-t"]);
let acpiThermalStatus = str::from_utf8(acpiThermalOutput.output);
let thermalParts = acpiThermalStatus.word_iter().to_owned_vec();
let temp = thermalParts[3].trim_chars(&',');
let msg = fmt!("%s %s %s %s %s %s", percentage, temp, sDate, sTime, sTZ, *hostname);
process_output(&"/usr/bin/wmfs",&[~"-s",~"0",msg]);
}
fn main() {
let rawHostname = load(~"/etc/hostname");
let hostname: ~str = rawHostname.trim().to_str();
loop {
run(&hostname);
sleep(5000);
}
}
| true |
d08973a9822ee29bad47a6b21e04e23e45ba1283
|
Rust
|
maekawatoshiki/XScript
|
/src/vm.rs
|
UTF-8
| 2,212 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
use vm_base::VMInst;
use ansi_term::{Colour, Style};
#[derive(Clone)]
pub struct VM {
pub stack: [i64; 1024],
pub bp_stack: Vec<usize>,
pub sp: usize,
pub bp: usize,
}
impl VM {
pub fn new() -> VM {
VM {
stack: [0; 1024],
bp_stack: Vec::new(),
sp: 0,
bp: 0,
}
}
}
impl VM {
pub fn run(&mut self, insts: Vec<VMInst>) {
for inst in insts {
self.run_inst(inst.clone());
for i in 0..8 {
print!(
"{}{}{} ",
if i == self.sp {
Colour::Red.paint("[")
} else if i == self.bp {
Colour::Green.paint("[")
} else {
Style::new().bold().paint("[")
},
self.stack[i],
if i == self.bp {
Colour::Green.paint("]")
} else if i == self.sp {
Colour::Red.paint("]")
} else {
Style::new().bold().paint("]")
},
);
}
println!("\t\t:{:?}", inst);
}
}
pub fn run_inst(&mut self, inst: VMInst) {
match inst {
VMInst::Entry(n) => {
self.bp_stack.push(self.bp);
self.sp += n;
self.bp = self.sp;
}
VMInst::StoreV(n) => self.stack[self.bp - n] = self.stack[self.sp],
VMInst::LoadV(n) => {
self.sp += 1;
self.stack[self.sp] = self.stack[self.bp - n]
}
VMInst::PushI(n) => {
self.sp += 1;
self.stack[self.sp] = n;
}
VMInst::Add => {
let a = self.stack[self.sp];
let b = self.stack[self.sp - 1];
self.sp -= 1;
self.stack[self.sp] = a + b;
}
VMInst::Ret => {
self.bp = self.bp_stack.pop().unwrap();
self.sp = self.bp
}
_ => {}
}
}
}
| true |
65f80c9acbfe31f3ee50eb9ee82b04f61ba3ddf6
|
Rust
|
gnoliyil/fuchsia
|
/src/lib/diagnostics/inspect/rust/src/writer/types/int_array.rs
|
UTF-8
| 4,649 | 2.765625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::writer::{ArithmeticArrayProperty, ArrayProperty, Inner, InnerValueType, InspectType};
use tracing::error;
#[cfg(test)]
use inspect_format::{Block, Container};
/// Inspect int array data type.
///
/// NOTE: do not rely on PartialEq implementation for true comparison.
/// Instead leverage the reader.
///
/// NOTE: Operations on a Default value are no-ops.
#[derive(Debug, PartialEq, Eq, Default)]
pub struct IntArrayProperty {
pub(crate) inner: Inner<InnerValueType>,
}
impl InspectType for IntArrayProperty {}
crate::impl_inspect_type_internal!(IntArrayProperty);
impl ArrayProperty for IntArrayProperty {
type Type = i64;
fn set(&self, index: usize, value: impl Into<Self::Type>) {
if let Some(ref inner_ref) = self.inner.inner_ref() {
inner_ref
.state
.try_lock()
.and_then(|mut state| {
state.set_array_int_slot(inner_ref.block_index, index, value.into())
})
.unwrap_or_else(|err| {
error!(?err, "Failed to set property");
});
}
}
fn clear(&self) {
if let Some(ref inner_ref) = self.inner.inner_ref() {
inner_ref
.state
.try_lock()
.and_then(|mut state| state.clear_array(inner_ref.block_index, 0))
.unwrap_or_else(|e| {
error!("Failed to clear property. Error: {:?}", e);
});
}
}
}
impl ArithmeticArrayProperty for IntArrayProperty {
fn add(&self, index: usize, value: i64) {
if let Some(ref inner_ref) = self.inner.inner_ref() {
inner_ref
.state
.try_lock()
.and_then(|mut state| state.add_array_int_slot(inner_ref.block_index, index, value))
.unwrap_or_else(|err| {
error!(?err, "Failed to add property");
});
}
}
fn subtract(&self, index: usize, value: i64) {
if let Some(ref inner_ref) = self.inner.inner_ref() {
inner_ref
.state
.try_lock()
.and_then(|mut state| {
state.subtract_array_int_slot(inner_ref.block_index, index, value)
})
.unwrap_or_else(|err| {
error!(?err, "Failed to subtract property");
});
}
}
}
#[cfg(test)]
impl IntArrayProperty {
/// Returns the [`Block`][Block] associated with this value.
pub fn get_block(&self) -> Option<Block<Container>> {
self.inner.inner_ref().and_then(|inner_ref| {
inner_ref
.state
.try_lock()
.and_then(|state| state.heap().get_block(inner_ref.block_index))
.ok()
})
}
/// Returns the index of the value's block in the VMO.
pub fn block_index(&self) -> u32 {
self.inner.inner_ref().unwrap().block_index
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::writer::Length;
use crate::Inspector;
#[fuchsia::test]
fn test_int_array() {
// Create and use a default value.
let default = IntArrayProperty::default();
default.add(1, 1);
let inspector = Inspector::new();
let root = inspector.root();
let node = root.create_child("node");
let node_block = node.get_block().unwrap();
{
let array = node.create_int_array("array_property", 5);
assert_eq!(array.len().unwrap(), 5);
let array_block = array.get_block().unwrap();
array.set(0, 5);
assert_eq!(array_block.array_get_int_slot(0).unwrap(), 5);
array.add(0, 5);
assert_eq!(array_block.array_get_int_slot(0).unwrap(), 10);
array.subtract(0, 3);
assert_eq!(array_block.array_get_int_slot(0).unwrap(), 7);
array.set(1, 2);
array.set(3, -3);
for (i, value) in [7, 2, 0, -3, 0].iter().enumerate() {
assert_eq!(array_block.array_get_int_slot(i).unwrap(), *value);
}
array.clear();
for i in 0..5 {
assert_eq!(0, array_block.array_get_int_slot(i).unwrap());
}
assert_eq!(node_block.child_count().unwrap(), 1);
}
assert_eq!(node_block.child_count().unwrap(), 0);
}
}
| true |
6abaed94aca9deac2bbfa4d504e65139194be72a
|
Rust
|
vermaneerajin/jql
|
/src/group_walker.rs
|
UTF-8
| 2,222 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
use crate::apply_filter::apply_filter;
use crate::flatten_json_array::flatten_json_array;
use crate::get_selection::get_selection;
use crate::truncate::truncate_json;
use crate::types::{Group, MaybeArray, Selection};
use serde_json::json;
use serde_json::Value;
/// Walks through a group.
pub fn group_walker(
(spread, root, selectors, filters, truncate): &Group,
json: &Value,
) -> Selection {
// Empty group, return early.
if selectors.is_empty() && root.is_none() {
return Err(String::from("Empty group"));
}
match get_selection(&selectors, &json) {
Ok(ref items) => {
// Check for an empty selection, in this case we assume that the
// user expects to get back the complete raw JSON for this group.
let output_json = if items.is_empty() {
json.clone()
} else {
json!(items.last())
};
let is_spreading = spread.is_some();
let output = match apply_filter(&filters, &output_json) {
Ok(filtered) => match filtered {
MaybeArray::Array(array) => Ok(if is_spreading {
flatten_json_array(&json!(array))
} else {
json!(array)
}),
MaybeArray::NonArray(single_value) => {
if is_spreading {
Err(String::from("Only arrays can be flattened"))
} else {
// We know that we are holding a single value
// wrapped inside a MaybeArray::NonArray enum.
// We need to pick the first item of the vector.
Ok(json!(single_value[0]))
}
}
},
Err(error) => Err(error),
};
match truncate {
Some(_) => match output {
Ok(value) => Ok(truncate_json(value)),
Err(error) => Err(error),
},
None => output,
}
}
Err(items) => Err(items),
}
}
| true |
b54137c9f881b2be78bb20207bab3afddd8b7129
|
Rust
|
callensm/wksp
|
/src/workspace.rs
|
UTF-8
| 1,331 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
use std::fs::{create_dir_all, File};
use std::path::Path;
use super::logger;
use super::template::{Template, TemplateError};
#[derive(Debug)]
pub struct Workspace {
template: Template,
file_name: String,
root: String,
}
impl Workspace {
pub fn new(template_file: &str, home: &str, root: &str) -> Result<Workspace, TemplateError> {
let template = Template::new(template_file, home)?;
Ok(Workspace {
template: template,
file_name: template_file.to_owned(),
root: root.to_owned(),
})
}
pub fn build(&self) {
let mut folder_paths = Vec::<String>::new();
let mut file_paths = Vec::<String>::new();
self
.template
.compile(&self.root, &mut folder_paths, &mut file_paths);
self.create_folders(&folder_paths);
self.create_files(&file_paths);
logger::successful_build(&self.file_name);
}
fn create_folders(&self, folders: &Vec<String>) {
for f in folders {
match create_dir_all(Path::new(f)) {
Ok(()) => continue,
Err(_e) => logger::failed_build(logger::ItemType::Folder, f),
}
}
}
fn create_files(&self, files: &Vec<String>) {
for f in files {
match File::create(Path::new(f)) {
Ok(_file) => continue,
Err(_e) => logger::failed_build(logger::ItemType::File, f),
}
}
}
}
| true |
ad24239a5b40c7679ee10117c9d077123b6f6fcc
|
Rust
|
BurtonQin/yamux
|
/src/frame/header.rs
|
UTF-8
| 4,747 | 2.515625 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Copyright 2018 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 or MIT license, at your option.
//
// A copy of the Apache License, Version 2.0 is included in the software as
// LICENSE-APACHE and a copy of the MIT license is included in the software
// as LICENSE-MIT. You may also obtain a copy of the Apache License, Version 2.0
// at https://www.apache.org/licenses/LICENSE-2.0 and a copy of the MIT license
// at https://opensource.org/licenses/MIT.
use crate::{frame::{Data, WindowUpdate, Ping, GoAway}, stream};
use std::marker::PhantomData;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Type {
Data,
WindowUpdate,
Ping,
GoAway
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Version(pub u8);
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Len(pub u32);
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Flags(pub u16);
impl Flags {
pub fn contains(self, other: Flags) -> bool {
self.0 & other.0 == other.0
}
pub fn and(self, other: Flags) -> Flags {
Flags(self.0 | other.0)
}
}
/// Termination code for use with GoAway frames.
pub const CODE_TERM: u32 = 0;
/// Protocol error code for use with GoAway frames.
pub const ECODE_PROTO: u32 = 1;
/// Internal error code for use with GoAway frames.
pub const ECODE_INTERNAL: u32 = 2;
pub const SYN: Flags = Flags(1);
pub const ACK: Flags = Flags(2);
pub const FIN: Flags = Flags(4);
pub const RST: Flags = Flags(8);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RawHeader {
pub version: Version,
pub typ: Type,
pub flags: Flags,
pub stream_id: stream::Id,
pub length: Len
}
#[derive(Clone, Debug)]
pub struct Header<T> {
raw_header: RawHeader,
header_type: PhantomData<T>
}
impl<T> Header<T> {
pub(crate) fn assert(raw: RawHeader) -> Self {
Header {
raw_header: raw,
header_type: PhantomData
}
}
pub fn id(&self) -> stream::Id {
self.raw_header.stream_id
}
pub fn flags(&self) -> Flags {
self.raw_header.flags
}
pub fn into_raw(self) -> RawHeader {
self.raw_header
}
}
impl Header<Data> {
pub fn data(id: stream::Id, len: u32) -> Self {
Header {
raw_header: RawHeader {
version: Version(0),
typ: Type::Data,
flags: Flags(0),
stream_id: id,
length: Len(len)
},
header_type: PhantomData
}
}
pub fn syn(&mut self) {
self.raw_header.flags.0 |= SYN.0
}
pub fn ack(&mut self) {
self.raw_header.flags.0 |= ACK.0
}
pub fn fin(&mut self) {
self.raw_header.flags.0 |= FIN.0
}
pub fn rst(&mut self) {
self.raw_header.flags.0 |= RST.0
}
pub fn len(&self) -> u32 {
self.raw_header.length.0
}
}
impl Header<WindowUpdate> {
pub fn window_update(id: stream::Id, credit: u32) -> Self {
Header {
raw_header: RawHeader {
version: Version(0),
typ: Type::WindowUpdate,
flags: Flags(0),
stream_id: id,
length: Len(credit)
},
header_type: PhantomData
}
}
pub fn syn(&mut self) {
self.raw_header.flags.0 |= SYN.0
}
pub fn ack(&mut self) {
self.raw_header.flags.0 |= ACK.0
}
pub fn fin(&mut self) {
self.raw_header.flags.0 |= FIN.0
}
pub fn rst(&mut self) {
self.raw_header.flags.0 |= RST.0
}
pub fn credit(&self) -> u32 {
self.raw_header.length.0
}
}
impl Header<Ping> {
pub fn ping(nonce: u32) -> Self {
Header {
raw_header: RawHeader {
version: Version(0),
typ: Type::Ping,
flags: Flags(0),
stream_id: stream::Id::new(0),
length: Len(nonce)
},
header_type: PhantomData
}
}
pub fn syn(&mut self) {
self.raw_header.flags.0 |= SYN.0
}
pub fn ack(&mut self) {
self.raw_header.flags.0 |= ACK.0
}
pub fn nonce(&self) -> u32 {
self.raw_header.length.0
}
}
impl Header<GoAway> {
pub fn go_away(error_code: u32) -> Self {
Header {
raw_header: RawHeader {
version: Version(0),
typ: Type::GoAway,
flags: Flags(0),
stream_id: stream::Id::new(0),
length: Len(error_code)
},
header_type: PhantomData
}
}
pub fn error_code(&self) -> u32 {
self.raw_header.length.0
}
}
| true |
0f102e23e149bce9c0d8806215a34e86fb7d39a9
|
Rust
|
Lokathor/bytemuck
|
/tests/checked_tests.rs
|
UTF-8
| 12,942 | 2.78125 | 3 |
[
"Zlib",
"Apache-2.0",
"MIT"
] |
permissive
|
use core::{
mem::size_of,
num::{NonZeroU32, NonZeroU8},
};
use bytemuck::{checked::CheckedCastError, *};
#[test]
fn test_try_cast_slice() {
// some align4 data
let nonzero_u32_slice: &[NonZeroU32] = &[
NonZeroU32::new(4).unwrap(),
NonZeroU32::new(5).unwrap(),
NonZeroU32::new(6).unwrap(),
];
// contains bytes with invalid bitpattern for NonZeroU8
assert_eq!(
checked::try_cast_slice::<NonZeroU32, NonZeroU8>(nonzero_u32_slice),
Err(CheckedCastError::InvalidBitPattern)
);
// the same data as align1
let the_bytes: &[u8] = checked::try_cast_slice(nonzero_u32_slice).unwrap();
assert_eq!(
nonzero_u32_slice.as_ptr() as *const NonZeroU32 as usize,
the_bytes.as_ptr() as *const u8 as usize
);
assert_eq!(
nonzero_u32_slice.len() * size_of::<NonZeroU32>(),
the_bytes.len() * size_of::<u8>()
);
// by taking one byte off the front, we're definitely mis-aligned for
// NonZeroU32.
let mis_aligned_bytes = &the_bytes[1..];
assert_eq!(
checked::try_cast_slice::<u8, NonZeroU32>(mis_aligned_bytes),
Err(CheckedCastError::PodCastError(
PodCastError::TargetAlignmentGreaterAndInputNotAligned
))
);
// by taking one byte off the end, we're aligned but would have slop bytes for
// NonZeroU32
let the_bytes_len_minus1 = the_bytes.len() - 1;
let slop_bytes = &the_bytes[..the_bytes_len_minus1];
assert_eq!(
checked::try_cast_slice::<u8, NonZeroU32>(slop_bytes),
Err(CheckedCastError::PodCastError(PodCastError::OutputSliceWouldHaveSlop))
);
// if we don't mess with it we can up-alignment cast
checked::try_cast_slice::<u8, NonZeroU32>(the_bytes).unwrap();
}
#[test]
fn test_try_cast_slice_mut() {
// some align4 data
let u32_slice: &mut [u32] = &mut [4, 5, 6];
// contains bytes with invalid bitpattern for NonZeroU8
assert_eq!(
checked::try_cast_slice_mut::<u32, NonZeroU8>(u32_slice),
Err(CheckedCastError::InvalidBitPattern)
);
// some align4 data
let u32_slice: &mut [u32] = &mut [0x4444_4444, 0x5555_5555, 0x6666_6666];
let u32_len = u32_slice.len();
let u32_ptr = u32_slice.as_ptr();
// the same data as align1, nonzero bytes
let the_nonzero_bytes: &mut [NonZeroU8] =
checked::try_cast_slice_mut(u32_slice).unwrap();
let the_nonzero_bytes_len = the_nonzero_bytes.len();
let the_nonzero_bytes_ptr = the_nonzero_bytes.as_ptr();
assert_eq!(
u32_ptr as *const u32 as usize,
the_nonzero_bytes_ptr as *const NonZeroU8 as usize
);
assert_eq!(
u32_len * size_of::<u32>(),
the_nonzero_bytes_len * size_of::<NonZeroU8>()
);
// the same data as align1
let the_bytes: &mut [u8] = checked::try_cast_slice_mut(u32_slice).unwrap();
let the_bytes_len = the_bytes.len();
let the_bytes_ptr = the_bytes.as_ptr();
assert_eq!(
u32_ptr as *const u32 as usize,
the_bytes_ptr as *const u8 as usize
);
assert_eq!(
u32_len * size_of::<u32>(),
the_bytes_len * size_of::<NonZeroU8>()
);
// by taking one byte off the front, we're definitely mis-aligned for u32.
let mis_aligned_bytes = &mut the_bytes[1..];
assert_eq!(
checked::try_cast_slice_mut::<u8, NonZeroU32>(mis_aligned_bytes),
Err(CheckedCastError::PodCastError(
PodCastError::TargetAlignmentGreaterAndInputNotAligned
))
);
// by taking one byte off the end, we're aligned but would have slop bytes for
// NonZeroU32
let the_bytes_len_minus1 = the_bytes.len() - 1;
let slop_bytes = &mut the_bytes[..the_bytes_len_minus1];
assert_eq!(
checked::try_cast_slice_mut::<u8, NonZeroU32>(slop_bytes),
Err(CheckedCastError::PodCastError(PodCastError::OutputSliceWouldHaveSlop))
);
// if we don't mess with it we can up-alignment cast, since there are no
// zeroes in the original slice
checked::try_cast_slice_mut::<u8, NonZeroU32>(the_bytes).unwrap();
}
#[test]
fn test_types() {
let _: NonZeroU32 = checked::cast(1.0_f32);
let _: &mut NonZeroU32 = checked::cast_mut(&mut 1.0_f32);
let _: &NonZeroU32 = checked::cast_ref(&1.0_f32);
let _: &[NonZeroU32] = checked::cast_slice(&[1.0_f32]);
let _: &mut [NonZeroU32] = checked::cast_slice_mut(&mut [1.0_f32]);
//
let _: Result<NonZeroU32, CheckedCastError> = checked::try_cast(1.0_f32);
let _: Result<&mut NonZeroU32, CheckedCastError> =
checked::try_cast_mut(&mut 1.0_f32);
let _: Result<&NonZeroU32, CheckedCastError> =
checked::try_cast_ref(&1.0_f32);
let _: Result<&[NonZeroU32], CheckedCastError> =
checked::try_cast_slice(&[1.0_f32]);
let _: Result<&mut [NonZeroU32], CheckedCastError> =
checked::try_cast_slice_mut(&mut [1.0_f32]);
}
#[test]
fn test_try_pod_read_unaligned() {
let u32s = [0xaabbccdd, 0x11223344_u32];
let bytes = bytemuck::checked::cast_slice::<u32, u8>(&u32s);
#[cfg(target_endian = "big")]
assert_eq!(
checked::try_pod_read_unaligned::<NonZeroU32>(&bytes[1..5]),
Ok(NonZeroU32::new(0xbbccdd11).unwrap())
);
#[cfg(target_endian = "little")]
assert_eq!(
checked::try_pod_read_unaligned::<NonZeroU32>(&bytes[1..5]),
Ok(NonZeroU32::new(0x44aabbcc).unwrap())
);
let u32s = [0; 2];
let bytes = bytemuck::checked::cast_slice::<u32, u8>(&u32s);
assert_eq!(
checked::try_pod_read_unaligned::<NonZeroU32>(&bytes[1..5]),
Err(CheckedCastError::InvalidBitPattern)
);
}
#[test]
fn test_try_from_bytes() {
let nonzero_u32s = [
NonZeroU32::new(0xaabbccdd).unwrap(),
NonZeroU32::new(0x11223344).unwrap(),
];
let bytes = bytemuck::checked::cast_slice::<NonZeroU32, u8>(&nonzero_u32s);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[..4]),
Ok(&nonzero_u32s[0])
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[..5]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[..3]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[1..5]),
Err(CheckedCastError::PodCastError(
PodCastError::TargetAlignmentGreaterAndInputNotAligned
))
);
let zero_u32s = [0, 0x11223344_u32];
let bytes = bytemuck::checked::cast_slice::<u32, u8>(&zero_u32s);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[..4]),
Err(CheckedCastError::InvalidBitPattern)
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[4..]),
Ok(&NonZeroU32::new(zero_u32s[1]).unwrap())
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[..5]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[..3]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[1..5]),
Err(CheckedCastError::PodCastError(
PodCastError::TargetAlignmentGreaterAndInputNotAligned
))
);
}
#[test]
fn test_try_from_bytes_mut() {
let a = 0xaabbccdd_u32;
let b = 0x11223344_u32;
let mut u32s = [a, b];
let bytes = bytemuck::checked::cast_slice_mut::<u32, u8>(&mut u32s);
assert_eq!(
checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..4]),
Ok(&mut NonZeroU32::new(a).unwrap())
);
assert_eq!(
checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[4..]),
Ok(&mut NonZeroU32::new(b).unwrap())
);
assert_eq!(
checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..5]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
assert_eq!(
checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..3]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[1..5]),
Err(CheckedCastError::PodCastError(
PodCastError::TargetAlignmentGreaterAndInputNotAligned
))
);
let mut u32s = [0, b];
let bytes = bytemuck::checked::cast_slice_mut::<u32, u8>(&mut u32s);
assert_eq!(
checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..4]),
Err(CheckedCastError::InvalidBitPattern)
);
assert_eq!(
checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[4..]),
Ok(&mut NonZeroU32::new(b).unwrap())
);
assert_eq!(
checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..5]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
assert_eq!(
checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..3]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
assert_eq!(
checked::try_from_bytes::<NonZeroU32>(&bytes[1..5]),
Err(CheckedCastError::PodCastError(
PodCastError::TargetAlignmentGreaterAndInputNotAligned
))
);
}
#[test]
fn test_from_bytes() {
let abcd = 0xaabbccdd_u32;
let aligned_bytes = bytemuck::bytes_of(&abcd);
assert_eq!(
checked::from_bytes::<NonZeroU32>(aligned_bytes),
&NonZeroU32::new(abcd).unwrap()
);
assert!(core::ptr::eq(
checked::from_bytes(aligned_bytes) as *const NonZeroU32 as *const u32,
&abcd
));
}
#[test]
fn test_from_bytes_mut() {
let mut a = 0xaabbccdd_u32;
let a_addr = &a as *const _ as usize;
let aligned_bytes = bytemuck::bytes_of_mut(&mut a);
assert_eq!(
*checked::from_bytes_mut::<NonZeroU32>(aligned_bytes),
NonZeroU32::new(0xaabbccdd).unwrap()
);
assert_eq!(
checked::from_bytes_mut::<NonZeroU32>(aligned_bytes) as *const NonZeroU32
as usize,
a_addr
);
}
// like #[should_panic], but can be a part of another test, instead of requiring
// it to be it's own test.
macro_rules! should_panic {
($ex:expr) => {
assert!(
std::panic::catch_unwind(|| {
let _ = $ex;
})
.is_err(),
concat!("should have panicked: `", stringify!($ex), "`")
);
};
}
#[test]
fn test_panics() {
should_panic!(checked::cast::<u32, NonZeroU32>(0));
should_panic!(checked::cast_ref::<u32, NonZeroU32>(&0));
should_panic!(checked::cast_mut::<u32, NonZeroU32>(&mut 0));
should_panic!(checked::cast_slice::<u8, NonZeroU32>(&[1u8, 2u8]));
should_panic!(checked::cast_slice_mut::<u8, NonZeroU32>(&mut [1u8, 2u8]));
should_panic!(checked::from_bytes::<NonZeroU32>(&[1u8, 2]));
should_panic!(checked::from_bytes::<NonZeroU32>(&[1u8, 2, 3, 4, 5]));
should_panic!(checked::from_bytes_mut::<NonZeroU32>(&mut [1u8, 2]));
should_panic!(checked::from_bytes_mut::<NonZeroU32>(&mut [1u8, 2, 3, 4, 5]));
// use cast_slice on some u32s to get some align>=4 bytes, so we can know
// we'll give from_bytes unaligned ones.
let aligned_bytes = bytemuck::cast_slice::<u32, u8>(&[0, 0]);
should_panic!(checked::from_bytes::<NonZeroU32>(aligned_bytes));
should_panic!(checked::from_bytes::<NonZeroU32>(&aligned_bytes[1..5]));
should_panic!(checked::pod_read_unaligned::<NonZeroU32>(
&aligned_bytes[1..5]
));
}
#[test]
fn test_char() {
assert_eq!(checked::try_cast::<u32, char>(0), Ok('\0'));
assert_eq!(checked::try_cast::<u32, char>(0xd7ff), Ok('\u{d7ff}'));
assert_eq!(
checked::try_cast::<u32, char>(0xd800),
Err(CheckedCastError::InvalidBitPattern)
);
assert_eq!(
checked::try_cast::<u32, char>(0xdfff),
Err(CheckedCastError::InvalidBitPattern)
);
assert_eq!(checked::try_cast::<u32, char>(0xe000), Ok('\u{e000}'));
assert_eq!(checked::try_cast::<u32, char>(0x10ffff), Ok('\u{10ffff}'));
assert_eq!(
checked::try_cast::<u32, char>(0x110000),
Err(CheckedCastError::InvalidBitPattern)
);
assert_eq!(
checked::try_cast::<u32, char>(-1i32 as u32),
Err(CheckedCastError::InvalidBitPattern)
);
}
#[test]
fn test_bool() {
assert_eq!(checked::try_cast::<u8, bool>(0), Ok(false));
assert_eq!(checked::try_cast::<u8, bool>(1), Ok(true));
for i in 2..=255 {
assert_eq!(
checked::try_cast::<u8, bool>(i),
Err(CheckedCastError::InvalidBitPattern)
);
}
assert_eq!(checked::try_from_bytes::<bool>(&[1]), Ok(&true));
assert_eq!(
checked::try_from_bytes::<bool>(&[3]),
Err(CheckedCastError::InvalidBitPattern)
);
assert_eq!(
checked::try_from_bytes::<bool>(&[0, 1]),
Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
);
}
#[test]
fn test_all_nonzero() {
use core::num::*;
macro_rules! test_nonzero {
($nonzero:ty: $primitive:ty) => {
assert_eq!(
checked::try_cast::<$primitive, $nonzero>(0),
Err(CheckedCastError::InvalidBitPattern)
);
assert_eq!(
checked::try_cast::<$primitive, $nonzero>(1),
Ok(<$nonzero>::new(1).unwrap())
);
};
}
test_nonzero!(NonZeroU8: u8);
test_nonzero!(NonZeroI8: i8);
test_nonzero!(NonZeroU16: u16);
test_nonzero!(NonZeroI16: i16);
test_nonzero!(NonZeroU32: u32);
test_nonzero!(NonZeroI32: i32);
test_nonzero!(NonZeroU64: u64);
test_nonzero!(NonZeroI64: i64);
test_nonzero!(NonZeroU128: u128);
test_nonzero!(NonZeroI128: i128);
test_nonzero!(NonZeroUsize: usize);
test_nonzero!(NonZeroIsize: isize);
}
| true |
ff9dd1693416c7db384dde9b0f0f10804eafb795
|
Rust
|
ippSD/raytracing
|
/src/radiation.rs
|
UTF-8
| 4,819 | 2.890625 | 3 |
[] |
no_license
|
//! Radiation module. Includes structures, traits and implementations
//! for computing the View Factors inside the world.
use std::f32::consts::PI;
use std::fmt::{Display, Formatter, Error};
use rand::random;
use crate::vectors::{Vec3, Vec3Methods};
use crate::rays::Ray;
use crate::objects::{Form, SurfaceFunctions, HittableList};
use crate::hittable::{HitRecord, Hittable};
/// View Factors structure.
pub struct Vfs {
pub vfs: Vec<Vec<f32>>
}
/// View Factors methods.
impl Vfs {
/// Constructor.
pub fn new() -> Vfs {
Vfs { vfs: Vec::new() }
}
/// From list of view factors Vec<Vec<f32>>.
pub fn from(vfs: Vec<Vec<f32>>) -> Vfs {
Vfs { vfs }
}
}
/// View Factor trait for world.
pub trait ViewFactors {
/// Compute the view factor for two objects on the world by means of
/// the Monte Carlo Method.
///
/// # Parameters:
///
/// * `self`: world of objects.
/// * `n`: number of iterations on the Monte Carlo method.
/// * `form_1_idx`: World index pointing at the first (main) object.
/// * `form_2_idx`: World index pointing at the second object.
///
/// # Returns:
///
/// * `f32`: View factor from object 1 to 2, $F_{12}$.
fn view_factor(&self, n: usize, form_1_idx: usize, form_2_idx: usize) -> f32;
/// Compute the view factors on the world by means of
/// the Monte Carlo Method.
///
/// # Parameters:
///
/// * `self`: world of objects.
/// * `n`: number of iterations on the Monte Carlo method.
///
/// # Returns:
///
/// * `Vfs`: View factors of the world objects.
fn view_factors(&self, n: usize) -> Vfs;
}
impl ViewFactors for HittableList {
fn view_factor(&self, n: usize, form_1_idx: usize, form_2_idx: usize) -> f32 {
let form_1: &Form = self.forms.get(form_1_idx).unwrap();
let form_2: &Form = self.forms.get(form_2_idx).unwrap();
let mut temp: f32 = 0e0;
let mut l;
let mut r12: Vec3;
let mut n1: Vec3;
let mut n2: Vec3;
let mut cos_beta1: f32;
let mut cos_beta2: f32;
let mut s1: f32;
let mut t1: f32;
let mut s2: f32;
let mut t2: f32;
let mut da1: f32;
let mut da2: f32;
let mut p1: Vec3;
let mut p2: Vec3;
let mut hit_rec: Option<HitRecord> = None;
let mut ray: Ray;
for _ in 0..n {
s1 = random();
t1 = random();
s2 = random();
t2 = random();
p1 = form_1.point(s1, t1);
n1 = form_1.normal(s1, t1);
p2 = form_2.point(s2, t2);
n2 = form_2.normal(s2, t2);
r12 = p2 - p1;
l = r12.length();
cos_beta1 = r12.dot(&n1) / l;
cos_beta2 = (-r12).dot(&n2) / l;
ray = Ray::new(p1, r12.unit_vector());
cos_beta2 = match self.hit(&ray, 1e-8, l, &mut hit_rec) {
true => match &hit_rec {
Some(rec) => match rec.hit_elem == form_2_idx {
true => cos_beta2,
false => 0e0,
}
None => 0e0,
}
false => {
cos_beta2
}
};
if cos_beta1 < 0e0 || cos_beta2 < 0e0 {
cos_beta1 = 0e0
}
da1 = form_1.diff_a(s1, t1);
da2 = form_2.diff_a(s2, t2);
// println!("C1: {}, C2: {}, L: {}", cos_beta1, cos_beta2, l);
temp = temp + cos_beta1 * cos_beta2 / l.powi(2) * da1 * da2;
}
return temp / PI / form_1.area() / (n as f32);
}
fn view_factors(&self, n: usize) -> Vfs {
let n_objs: usize = self.forms.len();
let mut viewfactors: Vec<Vec<f32>> = Vec::new();
for i in 0..n_objs {
let mut views_i: Vec<f32> = Vec::new();
for j in (i+1)..n_objs {
views_i.push(
self.view_factor(
n,
i,
j
)
);
}
viewfactors.push(views_i);
}
Vfs::from(viewfactors)
}
}
/// Display trait implementation on Vfs.
impl Display for Vfs {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let n: usize = self.vfs.len();
let mut vjs: &Vec<f32>;
for i in 0..n {
vjs = self.vfs.get(i).unwrap();
for j in 0..(n-i-1) {
writeln!(
f,
"F({},{}) = {:.4}",
i,
j + i + 1,
vjs.get(j).unwrap())?;
}
}
Ok(())
}
}
| true |
c41d652e494d6d2c5f07a55a94117fdce615299c
|
Rust
|
acmcarther/space_coop
|
/prototype2/client/infra/dag/src/lib.rs
|
UTF-8
| 7,419 | 2.765625 | 3 |
[] |
no_license
|
extern crate daggy;
extern crate itertools;
use daggy::NodeIndex;
use daggy::Walker;
use daggy::petgraph::graph::DefIndex;
use itertools::Itertools;
use std::collections::HashMap;
use std::convert::From;
use std::fmt::{Debug, Display, Error, Formatter};
use std::hash::Hash;
pub trait DagConstraints: Clone + Debug + Hash + Eq {}
impl<T> DagConstraints for T where T: Clone + Debug + Hash + Eq {}
/// Contains systems and their dependencies
pub struct Dag<I: DagConstraints> {
name_to_idx: HashMap<I, NodeIndex<DefIndex>>,
name_to_alias: HashMap<I, String>,
internal_dag: daggy::Dag<(), ()>,
}
impl<I: DagConstraints> Dag<I> {
pub fn new() -> Dag<I> {
Dag {
name_to_idx: HashMap::new(),
name_to_alias: HashMap::new(),
internal_dag: daggy::Dag::new(),
}
}
/// Provide a human-readable name for this type
pub fn add_alias(&mut self, system_name: &I, alias: String) {
self.name_to_alias.insert(system_name.clone(), alias);
}
/// Adds a dependency from the first system on the second one, indicating
/// that the second one
/// should go first
pub fn add_dependency(&mut self, system_name: &I, other_name: I) {
if *system_name == other_name {
println!("Tried to make {:?} depend on itself!", system_name);
panic!("Dag dependency error! Tried to depend on self! Check stdout for details.");
}
self.add_system(system_name);
self.add_system(&other_name);
let system_node = self.name_to_idx.get(system_name).unwrap();
let other_node = self.name_to_idx.get(&other_name).unwrap();
match self.internal_dag.add_edge(system_node.clone(), other_node.clone(), ()) {
Err(daggy::WouldCycle(_)) => self.cycle_panic(system_name, &other_name),
_ => (),
}
}
/// Throw a whole bunch of deps in at once
pub fn add_dependency_set(&mut self, system_name: &I, others: &[I]) {
others.iter().foreach(|other_name| {
self.add_dependency(system_name, other_name.clone());
})
}
/// Internal method that panics if the system already exists
pub fn add_system(&mut self, system_name: &I) {
if !self.name_to_idx.contains_key(system_name) {
self.force_add_system(system_name);
}
}
/// Internal method that panics if the system already exists
fn force_add_system(&mut self, system_name: &I) {
assert!(!self.name_to_idx.contains_key(system_name),
"Internal add_system method was called with system that already exists");
let node = self.internal_dag.add_node(());
self.name_to_idx.insert(system_name.clone(), node);
}
/// Diagnostic method for panicking on edge insert and printing the dag that
/// caused the panic
fn cycle_panic(&self, system_name: &I, other_name: &I) {
println!("Dag error on add_dependency! Tried to add a dependency from ({:?}) on ({:?})",
system_name,
other_name);
println!("The existing dag was:");
println!("{}", self);
panic!("Dag cycle error! Check stdout for the offending nodes and dag");
}
}
impl<I: DagConstraints> Display for Dag<I> {
/// Print the dag with the system names
fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
let name_to_idx = &self.name_to_idx;
let internal_dag = &self.internal_dag;
let mut idx_to_name = HashMap::new();
name_to_idx.iter().foreach(|(k, v)| {
idx_to_name.insert(v, k);
});
writeln!(formatter, "").unwrap();
name_to_idx.iter().foreach(|(k, v)| {
writeln!(formatter, "\"{}\": [", alias_name(k, &self.name_to_alias)).unwrap();
internal_dag.children(v.clone())
.iter(&internal_dag)
.map(|(_, n)| idx_to_name.get(&n).unwrap())
.foreach(|name| {
writeln!(formatter,
" \"{}\"",
alias_name(name.clone(), &self.name_to_alias))
.unwrap();
});
writeln!(formatter, "]").unwrap();
});
Ok(())
}
}
fn alias_name<I: DagConstraints>(name: &I, name_to_alias: &HashMap<I, String>) -> String {
name_to_alias.get(name).cloned().unwrap_or(format!("{:?}", name))
}
/// Contains numbered priorities for systems
pub struct PriorityMap<I: DagConstraints> {
priorities: HashMap<I, usize>,
name_to_alias: HashMap<I, String>,
}
impl<I: DagConstraints> PriorityMap<I> {
pub fn get(&self, name: &I) -> Option<usize> {
self.priorities.get(name).cloned()
}
}
impl<I: DagConstraints> From<Dag<I>> for PriorityMap<I> {
fn from(dag: Dag<I>) -> PriorityMap<I> {
let mut idx_to_name = HashMap::new();
dag.name_to_idx.iter().foreach(|(k, v)| {
idx_to_name.insert(v, k);
});
let origin = dag.internal_dag
.graph()
.node_indices()
.find(|n| dag.internal_dag.children(n.clone()).iter(&dag.internal_dag).count() == 0);
let priorities = match origin {
None => HashMap::new(), // Empty Dag
Some(_) => {
let mut priorities: HashMap<I, usize> = HashMap::new();
// Toposort the nodes (deps before their dependents).
let nodes = daggy::petgraph::algo::toposort(dag.internal_dag.graph());
nodes.into_iter()
.enumerate()
.map(|(idx, item)| (idx, idx_to_name.get(&item).unwrap()))
.foreach(|(idx, item)| {
// WTF? Double clone?
// Needed to compile. Probably got a double ref somewhere in here
priorities.insert(item.clone().clone(), idx);
});
priorities
},
};
PriorityMap {
priorities: priorities,
name_to_alias: dag.name_to_alias,
}
}
}
impl<I: DagConstraints> Display for PriorityMap<I> {
fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
let mut priority_set = self.priorities.clone().into_iter().collect::<Vec<(I, usize)>>();
priority_set.sort_by_key(|&(_, v)| v);
priority_set.reverse();
priority_set.into_iter()
.map(|(n, v)| (alias_name(&n, &self.name_to_alias), v))
.foreach(|(n, _)| {
writeln!(formatter, "{}", n).unwrap();
});
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adding_dependencies_works() {
let mut dag = Dag::new();
let s1 = "first_system".to_owned();
let s2 = "second_system".to_owned();
let s3 = "third_system".to_owned();
dag.add_dependency(&s1, &s2);
dag.add_dependency(&s2, &s3);
}
#[test]
#[should_panic(expected = "Dag cycle error! Check stdout for the offending nodes and dag")]
fn creating_cycles_panics() {
let mut dag = Dag::new();
let s1 = "first_system".to_owned();
let s2 = "second_system".to_owned();
dag.add_dependency(&s1, &s2);
dag.add_dependency(&s2, &s1);
}
#[test]
fn priority_map_yields_correct_priorities() {
let mut dag = Dag::new();
let s1 = "first_system".to_owned();
let s2 = "second_system".to_owned();
let s3 = "third_system".to_owned();
dag.add_dependency(&s1, &s2);
dag.add_dependency(&s2, &s3);
let priority_map = PriorityMap::from(dag);
assert_eq!(priority_map.get(&s1), Some(0));
assert_eq!(priority_map.get(&s2), Some(1));
assert_eq!(priority_map.get(&s3), Some(2));
}
#[test]
#[should_panic(expected = "Dag dependency error! Tried to depend on self! Check stdout for details.")]
fn dont_depend_on_yourself_dumbass() {
let mut dag = Dag::new();
let s1 = "first_system".to_owned();
dag.add_dependency(&s1, &s1);
}
}
| true |
ea5d50f93e4f86efb42a63b32480fa358ecba9b1
|
Rust
|
hecrj/ggez
|
/src/graphics/mod.rs
|
UTF-8
| 36,501 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
//! The `graphics` module performs the actual drawing of images, text, and other
//! objects with the [`Drawable`](trait.Drawable.html) trait. It also handles
//! basic loading of images and text.
//!
//! This module also manages graphics state, coordinate systems, etc.
//! The default coordinate system has the origin in the upper-left
//! corner of the screen, with Y increasing downwards.
//!
//! This library differs significantly in performance characteristics from the
//! `LÖVE` library that it is based on. Many operations that are batched by default
//! in love (e.g. drawing primitives like rectangles or circles) are *not* batched
//! in `ggez`, so render loops with a large number of draw calls can be very slow.
//! The primary solution to efficiently rendering a large number of primitives is
//! a [`SpriteBatch`](spritebatch/struct.SpriteBatch.html), which can be orders
//! of magnitude more efficient than individual
//! draw calls.
//!
//! The `pipe` module is auto-generated by `gfx_defines!`. You shouldn't need to
//! touch it, but alas we can't exclude it from `cargo doc`.
use std::collections::HashMap;
use std::convert::From;
use std::fmt;
use std::path::Path;
use std::u16;
use gfx;
use gfx::texture;
use gfx::Device;
use gfx::Factory;
use gfx_device_gl;
use glutin;
use crate::conf;
use crate::conf::WindowMode;
use crate::context::Context;
use crate::context::DebugId;
use crate::GameError;
use crate::GameResult;
pub(crate) mod canvas;
pub(crate) mod context;
pub(crate) mod drawparam;
pub(crate) mod image;
pub(crate) mod mesh;
pub(crate) mod shader;
pub(crate) mod text;
pub(crate) mod types;
pub use mint;
pub(crate) use nalgebra as na;
pub mod spritebatch;
pub use crate::graphics::canvas::*;
pub use crate::graphics::drawparam::*;
pub use crate::graphics::image::*;
pub use crate::graphics::mesh::*;
pub use crate::graphics::shader::*;
pub use crate::graphics::text::*;
pub use crate::graphics::types::*;
// This isn't really particularly nice, but it's only used
// in a couple places and it's not very easy to change or configure.
// Since the next major project is "rewrite the graphics engine" I think
// we're fine just leaving it.
//
// It exists basically because gfx-rs is incomplete and we can't *always*
// specify texture formats and such entirely at runtime, which we need to
// do to make sRGB handling work properly.
pub(crate) type BuggoSurfaceFormat = gfx::format::Srgba8;
type ShaderResourceType = [f32; 4];
/// A trait providing methods for working with a particular backend, such as OpenGL,
/// with associated gfx-rs types for that backend. As a user you probably
/// don't need to touch this unless you want to write a new graphics backend
/// for ggez. (Trust me, you don't.)
pub trait BackendSpec: fmt::Debug {
/// gfx resource type
type Resources: gfx::Resources;
/// gfx factory type
type Factory: gfx::Factory<Self::Resources> + Clone;
/// gfx command buffer type
type CommandBuffer: gfx::CommandBuffer<Self::Resources>;
/// gfx device type
type Device: gfx::Device<Resources = Self::Resources, CommandBuffer = Self::CommandBuffer>;
/// A helper function to take a RawShaderResourceView and turn it into a typed one based on
/// the surface type defined in a `BackendSpec`.
///
/// But right now we only allow surfaces that use [f32;4] colors, so we can freely
/// hardcode this in the `ShaderResourceType` type.
fn raw_to_typed_shader_resource(
&self,
texture_view: gfx::handle::RawShaderResourceView<Self::Resources>,
) -> gfx::handle::ShaderResourceView<<Self as BackendSpec>::Resources, ShaderResourceType> {
// gfx::memory::Typed is UNDOCUMENTED, aiee!
// However there doesn't seem to be an official way to turn a raw tex/view into a typed
// one; this API oversight would probably get fixed, except gfx is moving to a new
// API model. So, that also fortunately means that undocumented features like this
// probably won't go away on pre-ll gfx...
let typed_view: gfx::handle::ShaderResourceView<_, ShaderResourceType> =
gfx::memory::Typed::new(texture_view);
typed_view
}
/// Helper function that turns a raw to typed texture.
/// A bit hacky since we can't really specify surface formats as part
/// of this that well, alas. There's some functions, like
/// `gfx::Encoder::update_texture()`, that don't seem to have a `_raw()`
/// counterpart, so we need this, so we need `BuggoSurfaceFormat` to
/// keep fixed at compile time what texture format we're actually using.
/// Oh well!
fn raw_to_typed_texture(
&self,
texture_view: gfx::handle::RawTexture<Self::Resources>,
) -> gfx::handle::Texture<
<Self as BackendSpec>::Resources,
<BuggoSurfaceFormat as gfx::format::Formatted>::Surface,
> {
let typed_view: gfx::handle::Texture<
_,
<BuggoSurfaceFormat as gfx::format::Formatted>::Surface,
> = gfx::memory::Typed::new(texture_view);
typed_view
}
/// Returns the version of the backend, `(major, minor)`.
///
/// So for instance if the backend is using OpenGL version 3.2,
/// it would return `(3, 2)`.
fn version_tuple(&self) -> (u8, u8);
/// Returns the glutin `Api` enum for this backend.
fn api(&self) -> glutin::Api;
/// Returns the text of the vertex and fragment shader files
/// to create default shaders for this backend.
fn shaders(&self) -> (&'static [u8], &'static [u8]);
/// Returns a string containing some backend-dependent info.
fn info(&self, device: &Self::Device) -> String;
/// Creates the window.
fn init<'a>(
&self,
window_builder: glutin::WindowBuilder,
gl_builder: glutin::ContextBuilder<'a>,
events_loop: &glutin::EventsLoop,
color_format: gfx::format::Format,
depth_format: gfx::format::Format,
) -> Result<
(
glutin::WindowedContext,
Self::Device,
Self::Factory,
gfx::handle::RawRenderTargetView<Self::Resources>,
gfx::handle::RawDepthStencilView<Self::Resources>,
),
glutin::CreationError,
>;
/// Create an Encoder for the backend.
fn encoder(factory: &mut Self::Factory) -> gfx::Encoder<Self::Resources, Self::CommandBuffer>;
/// Resizes the viewport for the backend. (right now assumes a Glutin window...)
fn resize_viewport(
&self,
color_view: &gfx::handle::RawRenderTargetView<Self::Resources>,
depth_view: &gfx::handle::RawDepthStencilView<Self::Resources>,
color_format: gfx::format::Format,
depth_format: gfx::format::Format,
window: &glutin::WindowedContext,
) -> Option<(
gfx::handle::RawRenderTargetView<Self::Resources>,
gfx::handle::RawDepthStencilView<Self::Resources>,
)>;
}
/// A backend specification for OpenGL.
/// This is different from [`Backend`](../conf/enum.Backend.html)
/// because this needs to be its own struct to implement traits
/// upon, and because there may need to be a layer of translation
/// between what the user asks for in the config, and what the
/// graphics backend code actually gets from the driver.
///
/// You shouldn't normally need to fiddle with this directly
/// but it has to be public because generic types like
/// [`Shader`](type.Shader.html) depend on it.
#[derive(Debug, Copy, Clone, PartialEq, Eq, SmartDefault)]
pub struct GlBackendSpec {
#[default = 3]
major: u8,
#[default = 2]
minor: u8,
#[default(glutin::Api::OpenGl)]
api: glutin::Api,
}
impl From<conf::Backend> for GlBackendSpec {
fn from(c: conf::Backend) -> Self {
match c {
conf::Backend::OpenGL { major, minor } => Self {
major,
minor,
api: glutin::Api::OpenGl,
},
conf::Backend::OpenGLES { major, minor } => Self {
major,
minor,
api: glutin::Api::OpenGlEs,
},
}
}
}
impl BackendSpec for GlBackendSpec {
type Resources = gfx_device_gl::Resources;
type Factory = gfx_device_gl::Factory;
type CommandBuffer = gfx_device_gl::CommandBuffer;
type Device = gfx_device_gl::Device;
fn version_tuple(&self) -> (u8, u8) {
(self.major, self.minor)
}
fn api(&self) -> glutin::Api {
self.api
}
fn shaders(&self) -> (&'static [u8], &'static [u8]) {
match self.api {
glutin::Api::OpenGl => (
include_bytes!("shader/basic_150.glslv"),
include_bytes!("shader/basic_150.glslf"),
),
glutin::Api::OpenGlEs => (
include_bytes!("shader/basic_es300.glslv"),
include_bytes!("shader/basic_es300.glslf"),
),
a => panic!("Unsupported API: {:?}, should never happen", a),
}
}
fn init<'a>(
&self,
window_builder: glutin::WindowBuilder,
gl_builder: glutin::ContextBuilder<'a>,
events_loop: &glutin::EventsLoop,
color_format: gfx::format::Format,
depth_format: gfx::format::Format,
) -> Result<
(
glutin::WindowedContext,
Self::Device,
Self::Factory,
gfx::handle::RawRenderTargetView<Self::Resources>,
gfx::handle::RawDepthStencilView<Self::Resources>,
),
glutin::CreationError,
> {
gfx_window_glutin::init_raw(
window_builder,
gl_builder,
events_loop,
color_format,
depth_format,
)
}
fn info(&self, device: &Self::Device) -> String {
let info = device.get_info();
format!(
"Driver vendor: {}, renderer {}, version {:?}, shading language {:?}",
info.platform_name.vendor,
info.platform_name.renderer,
info.version,
info.shading_language
)
}
fn encoder(factory: &mut Self::Factory) -> gfx::Encoder<Self::Resources, Self::CommandBuffer> {
factory.create_command_buffer().into()
}
fn resize_viewport(
&self,
color_view: &gfx::handle::RawRenderTargetView<Self::Resources>,
depth_view: &gfx::handle::RawDepthStencilView<Self::Resources>,
color_format: gfx::format::Format,
depth_format: gfx::format::Format,
window: &glutin::WindowedContext,
) -> Option<(
gfx::handle::RawRenderTargetView<Self::Resources>,
gfx::handle::RawDepthStencilView<Self::Resources>,
)> {
// Basically taken from the definition of
// gfx_window_glutin::update_views()
let dim = color_view.get_dimensions();
assert_eq!(dim, depth_view.get_dimensions());
if let Some((cv, dv)) =
gfx_window_glutin::update_views_raw(window, dim, color_format, depth_format)
{
Some((cv, dv))
} else {
None
}
}
}
const QUAD_VERTS: [Vertex; 4] = [
Vertex {
pos: [0.0, 0.0],
uv: [0.0, 0.0],
color: [1.0, 1.0, 1.0, 1.0],
},
Vertex {
pos: [1.0, 0.0],
uv: [1.0, 0.0],
color: [1.0, 1.0, 1.0, 1.0],
},
Vertex {
pos: [1.0, 1.0],
uv: [1.0, 1.0],
color: [1.0, 1.0, 1.0, 1.0],
},
Vertex {
pos: [0.0, 1.0],
uv: [0.0, 1.0],
color: [1.0, 1.0, 1.0, 1.0],
},
];
const QUAD_INDICES: [u16; 6] = [0, 1, 2, 0, 2, 3];
gfx_defines! {
/// Structure containing fundamental vertex data.
vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv",
color: [f32;4] = "a_VertColor",
}
/// Internal structure containing values that are different for each
/// drawable object. This is the per-object data that
/// gets fed into the shaders.
vertex InstanceProperties {
// the columns here are for the transform matrix;
// you can't shove a full matrix into an instance
// buffer, annoyingly.
col1: [f32; 4] = "a_TCol1",
col2: [f32; 4] = "a_TCol2",
col3: [f32; 4] = "a_TCol3",
col4: [f32; 4] = "a_TCol4",
src: [f32; 4] = "a_Src",
color: [f32; 4] = "a_Color",
}
/// Internal structure containing global shader state.
constant Globals {
mvp_matrix: [[f32; 4]; 4] = "u_MVP",
}
// Internal structure containing graphics pipeline state.
// This can't be a doc comment though because it somehow
// breaks the gfx_defines! macro though. :-(
pipeline pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
tex: gfx::TextureSampler<[f32; 4]> = "t_Texture",
globals: gfx::ConstantBuffer<Globals> = "Globals",
rect_instance_properties: gfx::InstanceBuffer<InstanceProperties> = (),
// The default values here are overwritten by the
// pipeline init values in `shader::create_shader()`.
out: gfx::RawRenderTarget =
("Target0",
gfx::format::Format(gfx::format::SurfaceType::R8_G8_B8_A8, gfx::format::ChannelType::Srgb),
gfx::state::ColorMask::all(), Some(gfx::preset::blend::ALPHA)
),
}
}
impl fmt::Display for InstanceProperties {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut matrix_vec: Vec<f32> = vec![];
matrix_vec.extend(&self.col1);
matrix_vec.extend(&self.col2);
matrix_vec.extend(&self.col3);
matrix_vec.extend(&self.col4);
let matrix = na::Matrix4::from_column_slice(&matrix_vec);
writeln!(
f,
"Src: ({},{}+{},{})",
self.src[0], self.src[1], self.src[2], self.src[3]
)?;
writeln!(f, "Color: {:?}", self.color)?;
write!(f, "Matrix: {}", matrix)
}
}
impl Default for InstanceProperties {
fn default() -> Self {
InstanceProperties {
col1: [1.0, 0.0, 0.0, 0.0],
col2: [0.0, 1.0, 0.0, 0.0],
col3: [1.0, 0.0, 1.0, 0.0],
col4: [1.0, 0.0, 0.0, 1.0],
src: [0.0, 0.0, 1.0, 1.0],
color: [1.0, 1.0, 1.0, 1.0],
}
}
}
/// A structure for conveniently storing `Sampler`'s, based off
/// their `SamplerInfo`.
pub(crate) struct SamplerCache<B>
where
B: BackendSpec,
{
samplers: HashMap<texture::SamplerInfo, gfx::handle::Sampler<B::Resources>>,
}
impl<B> SamplerCache<B>
where
B: BackendSpec,
{
fn new() -> Self {
SamplerCache {
samplers: HashMap::new(),
}
}
fn get_or_insert(
&mut self,
info: texture::SamplerInfo,
factory: &mut B::Factory,
) -> gfx::handle::Sampler<B::Resources> {
let sampler = self
.samplers
.entry(info)
.or_insert_with(|| factory.create_sampler(info));
sampler.clone()
}
}
impl From<gfx::buffer::CreationError> for GameError {
fn from(e: gfx::buffer::CreationError) -> Self {
use gfx::buffer::CreationError;
match e {
CreationError::UnsupportedBind(b) => GameError::RenderError(format!(
"Could not create buffer: Unsupported Bind ({:?})",
b
)),
CreationError::UnsupportedUsage(u) => GameError::RenderError(format!(
"Could not create buffer: Unsupported Usage ({:?})",
u
)),
CreationError::Other => {
GameError::RenderError("Could not create buffer: Unknown error".to_owned())
}
}
}
}
// **********************************************************************
// DRAWING
// **********************************************************************
/// Clear the screen to the background color.
pub fn clear(ctx: &mut Context, color: Color) {
let gfx = &mut ctx.gfx_context;
let linear_color: types::LinearColor = color.into();
let c: [f32; 4] = linear_color.into();
gfx.encoder.clear_raw(&gfx.data.out, c.into());
}
/// Draws the given `Drawable` object to the screen by calling its
/// [`draw()`](trait.Drawable.html#tymethod.draw) method.
pub fn draw<D, T>(ctx: &mut Context, drawable: &D, params: T) -> GameResult
where
D: Drawable,
T: Into<DrawParam>,
{
let params = params.into();
drawable.draw(ctx, params)
}
/// Tells the graphics system to actually put everything on the screen.
/// Call this at the end of your [`EventHandler`](../event/trait.EventHandler.html)'s
/// [`draw()`](../event/trait.EventHandler.html#tymethod.draw) method.
///
/// Unsets any active canvas.
pub fn present(ctx: &mut Context) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
gfx.data.out = gfx.screen_render_target.clone();
// We might want to give the user more control over when the
// encoder gets flushed eventually, if we want them to be able
// to do their own gfx drawing. HOWEVER, the whole pipeline type
// thing is a bigger hurdle, so this is fine for now.
gfx.encoder.flush(&mut *gfx.device);
gfx.window.swap_buffers()?;
gfx.device.cleanup();
Ok(())
}
/// Take a screenshot by outputting the current render surface
/// (screen or selected canvas) to an `Image`.
pub fn screenshot(ctx: &mut Context) -> GameResult<Image> {
// TODO LATER: This makes the screenshot upside-down form some reason...
// Probably because all our images are upside down, for coordinate reasons!
// How can we fix it?
use gfx::memory::Bind;
let debug_id = DebugId::get(ctx);
let gfx = &mut ctx.gfx_context;
let (w, h, _depth, aa) = gfx.data.out.get_dimensions();
let surface_format = gfx.color_format();
let gfx::format::Format(surface_type, channel_type) = surface_format;
let texture_kind = gfx::texture::Kind::D2(w, h, aa);
let texture_info = gfx::texture::Info {
kind: texture_kind,
levels: 1,
format: surface_type,
bind: Bind::TRANSFER_SRC | Bind::TRANSFER_DST | Bind::SHADER_RESOURCE,
usage: gfx::memory::Usage::Data,
};
let target_texture = gfx
.factory
.create_texture_raw(texture_info, Some(channel_type), None)?;
let image_info = gfx::texture::ImageInfoCommon {
xoffset: 0,
yoffset: 0,
zoffset: 0,
width: w,
height: h,
depth: 0,
format: surface_format,
mipmap: 0,
};
let mut local_encoder: gfx::Encoder<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer> =
gfx.factory.create_command_buffer().into();
local_encoder.copy_texture_to_texture_raw(
gfx.data.out.get_texture(),
None,
image_info,
&target_texture,
None,
image_info,
)?;
local_encoder.flush(&mut *gfx.device);
let resource_desc = gfx::texture::ResourceDesc {
channel: channel_type,
layer: None,
min: 0,
max: 0,
swizzle: gfx::format::Swizzle::new(),
};
let shader_resource = gfx
.factory
.view_texture_as_shader_resource_raw(&target_texture, resource_desc)?;
let image = Image {
texture: shader_resource,
texture_handle: target_texture,
sampler_info: gfx.default_sampler_info,
blend_mode: None,
width: w,
height: h,
debug_id,
};
Ok(image)
}
// **********************************************************************
// GRAPHICS STATE
// **********************************************************************
/// Get the default filter mode for new images.
pub fn default_filter(ctx: &Context) -> FilterMode {
let gfx = &ctx.gfx_context;
gfx.default_sampler_info.filter.into()
}
/// Returns a string that tells a little about the obtained rendering mode.
/// It is supposed to be human-readable and will change; do not try to parse
/// information out of it!
pub fn renderer_info(ctx: &Context) -> GameResult<String> {
let backend_info = ctx.gfx_context.backend_spec.info(&*ctx.gfx_context.device);
Ok(format!(
"Requested {:?} {}.{} Core profile, actually got {}.",
ctx.gfx_context.backend_spec.api,
ctx.gfx_context.backend_spec.major,
ctx.gfx_context.backend_spec.minor,
backend_info
))
}
/// Returns a rectangle defining the coordinate system of the screen.
/// It will be `Rect { x: left, y: top, w: width, h: height }`
///
/// If the Y axis increases downwards, the `height` of the `Rect`
/// will be negative.
pub fn screen_coordinates(ctx: &Context) -> Rect {
ctx.gfx_context.screen_rect
}
/// Sets the default filter mode used to scale images.
///
/// This does not apply retroactively to already created images.
pub fn set_default_filter(ctx: &mut Context, mode: FilterMode) {
let gfx = &mut ctx.gfx_context;
let new_mode = mode.into();
let sampler_info = texture::SamplerInfo::new(new_mode, texture::WrapMode::Clamp);
// We create the sampler now so we don't end up creating it at some
// random-ass time while we're trying to draw stuff.
let _sampler = gfx.samplers.get_or_insert(sampler_info, &mut *gfx.factory);
gfx.default_sampler_info = sampler_info;
}
/// Sets the bounds of the screen viewport.
///
/// The default coordinate system has (0,0) at the top-left corner
/// with X increasing to the right and Y increasing down, with the
/// viewport scaled such that one coordinate unit is one pixel on the
/// screen. This function lets you change this coordinate system to
/// be whatever you prefer.
///
/// The `Rect`'s x and y will define the top-left corner of the screen,
/// and that plus its w and h will define the bottom-right corner.
pub fn set_screen_coordinates(context: &mut Context, rect: Rect) -> GameResult {
let gfx = &mut context.gfx_context;
gfx.set_projection_rect(rect);
gfx.calculate_transform_matrix();
gfx.update_globals()
}
/// Sets the raw projection matrix to the given homogeneous
/// transformation matrix.
///
/// You must call [`apply_transformations(ctx)`](fn.apply_transformations.html)
/// after calling this to apply these changes and recalculate the
/// underlying MVP matrix.
pub fn set_projection<M>(context: &mut Context, proj: M)
where
M: Into<mint::ColumnMatrix4<f32>>,
{
let proj = Matrix4::from(proj.into());
let gfx = &mut context.gfx_context;
gfx.set_projection(proj);
}
/// Premultiplies the given transformation matrix with the current projection matrix
///
/// You must call [`apply_transformations(ctx)`](fn.apply_transformations.html)
/// after calling this to apply these changes and recalculate the
/// underlying MVP matrix.
pub fn mul_projection<M>(context: &mut Context, transform: M)
where
M: Into<mint::ColumnMatrix4<f32>>,
{
let transform = Matrix4::from(transform.into());
let gfx = &mut context.gfx_context;
let curr = gfx.projection();
gfx.set_projection(transform * curr);
}
/// Gets a copy of the context's raw projection matrix
pub fn projection(context: &Context) -> mint::ColumnMatrix4<f32> {
let gfx = &context.gfx_context;
gfx.projection().into()
}
/// Pushes a homogeneous transform matrix to the top of the transform
/// (model) matrix stack of the `Context`. If no matrix is given, then
/// pushes a copy of the current transform matrix to the top of the stack.
///
/// You must call [`apply_transformations(ctx)`](fn.apply_transformations.html)
/// after calling this to apply these changes and recalculate the
/// underlying MVP matrix.
///
/// A [`DrawParam`](struct.DrawParam.html) can be converted into an appropriate
/// transform matrix by turning it into a [`DrawTransform`](struct.DrawTransform.html):
///
/// ```rust,no_run
/// # use ggez::*;
/// # use ggez::graphics::*;
/// # fn main() {
/// # let ctx = &mut ContextBuilder::new("foo", "bar").build().unwrap().0;
/// let param = /* DrawParam building */
/// # DrawParam::new();
/// let transform = param.to_matrix();
/// graphics::push_transform(ctx, Some(transform));
/// # }
/// ```
pub fn push_transform<M>(context: &mut Context, transform: Option<M>)
where
M: Into<mint::ColumnMatrix4<f32>>,
{
let transform = transform.map(|transform| Matrix4::from(transform.into()));
let gfx = &mut context.gfx_context;
if let Some(t) = transform {
gfx.push_transform(t);
} else {
let copy = *gfx
.modelview_stack
.last()
.expect("Matrix stack empty, should never happen");
gfx.push_transform(copy);
}
}
/// Pops the transform matrix off the top of the transform
/// (model) matrix stack of the `Context`.
///
/// You must call [`apply_transformations(ctx)`](fn.apply_transformations.html)
/// after calling this to apply these changes and recalculate the
/// underlying MVP matrix.
pub fn pop_transform(context: &mut Context) {
let gfx = &mut context.gfx_context;
gfx.pop_transform();
}
/// Sets the current model transformation to the given homogeneous
/// transformation matrix.
///
/// You must call [`apply_transformations(ctx)`](fn.apply_transformations.html)
/// after calling this to apply these changes and recalculate the
/// underlying MVP matrix.
///
/// A [`DrawParam`](struct.DrawParam.html) can be converted into an appropriate
/// transform matrix with `DrawParam::to_matrix()`.
/// ```rust,no_run
/// # use ggez::*;
/// # use ggez::graphics::*;
/// # fn main() {
/// # let ctx = &mut ContextBuilder::new("foo", "bar").build().unwrap().0;
/// let param = /* DrawParam building */
/// # DrawParam::new();
/// let transform = param.to_matrix();
/// graphics::set_transform(ctx, transform);
/// # }
/// ```
pub fn set_transform<M>(context: &mut Context, transform: M)
where
M: Into<mint::ColumnMatrix4<f32>>,
{
let transform = transform.into();
let gfx = &mut context.gfx_context;
gfx.set_transform(Matrix4::from(transform));
}
/// Gets a copy of the context's current transform matrix
pub fn transform(context: &Context) -> mint::ColumnMatrix4<f32> {
let gfx = &context.gfx_context;
gfx.transform().into()
}
/// Premultiplies the given transform with the current model transform.
///
/// You must call [`apply_transformations(ctx)`](fn.apply_transformations.html)
/// after calling this to apply these changes and recalculate the
/// underlying MVP matrix.
///
/// A [`DrawParam`](struct.DrawParam.html) can be converted into an appropriate
/// transform matrix by turning it into a [`DrawTransform`](struct.DrawTransform.html):
///
/// ```rust,no_run
/// # use ggez::nalgebra as na;
/// # use ggez::*;
/// # use ggez::graphics::*;
/// # fn main() {
/// # let ctx = &mut ContextBuilder::new("foo", "bar").build().unwrap().0;
/// let param = /* DrawParam building */
/// # DrawParam::new();
/// let transform = param.to_matrix();
/// graphics::mul_transform(ctx, transform);
/// # }
/// ```
pub fn mul_transform<M>(context: &mut Context, transform: M)
where
M: Into<mint::ColumnMatrix4<f32>>,
{
let transform = Matrix4::from(transform.into());
let gfx = &mut context.gfx_context;
let curr = gfx.transform();
gfx.set_transform(curr * transform);
}
/// Sets the current model transform to the origin transform (no transformation)
///
/// You must call [`apply_transformations(ctx)`](fn.apply_transformations.html)
/// after calling this to apply these changes and recalculate the
/// underlying MVP matrix.
pub fn origin(context: &mut Context) {
let gfx = &mut context.gfx_context;
gfx.set_transform(Matrix4::identity());
}
/// Calculates the new total transformation (Model-View-Projection) matrix
/// based on the matrices at the top of the transform and view matrix stacks
/// and sends it to the graphics card.
pub fn apply_transformations(context: &mut Context) -> GameResult {
let gfx = &mut context.gfx_context;
gfx.calculate_transform_matrix();
gfx.update_globals()
}
/// Sets the blend mode of the currently active shader program
pub fn set_blend_mode(ctx: &mut Context, mode: BlendMode) -> GameResult {
ctx.gfx_context.set_blend_mode(mode)
}
/// Sets the window mode, such as the size and other properties.
///
/// Setting the window mode may have side effects, such as clearing
/// the screen or setting the screen coordinates viewport to some
/// undefined value (for example, the window was resized). It is
/// recommended to call
/// [`set_screen_coordinates()`](fn.set_screen_coordinates.html) after
/// changing the window size to make sure everything is what you want
/// it to be.
pub fn set_mode(context: &mut Context, mode: WindowMode) -> GameResult {
let gfx = &mut context.gfx_context;
gfx.set_window_mode(mode)?;
// Save updated mode.
context.conf.window_mode = mode;
Ok(())
}
/// Sets the window to fullscreen or back.
pub fn set_fullscreen(context: &mut Context, fullscreen: conf::FullscreenType) -> GameResult {
let mut window_mode = context.conf.window_mode;
window_mode.fullscreen_type = fullscreen;
set_mode(context, window_mode)
}
/// Sets the window size/resolution to the specified width and height.
pub fn set_drawable_size(context: &mut Context, width: f32, height: f32) -> GameResult {
let mut window_mode = context.conf.window_mode;
window_mode.width = width;
window_mode.height = height;
set_mode(context, window_mode)
}
/// Sets whether or not the window is resizable.
pub fn set_resizable(context: &mut Context, resizable: bool) -> GameResult {
let mut window_mode = context.conf.window_mode;
window_mode.resizable = resizable;
set_mode(context, window_mode)
}
/// Sets the window icon.
pub fn set_window_icon<P: AsRef<Path>>(context: &mut Context, path: Option<P>) -> GameResult<()> {
let icon = match path {
Some(p) => {
let p: &Path = p.as_ref();
Some(context::load_icon(p, &mut context.filesystem)?)
}
None => None,
};
context.gfx_context.window.set_window_icon(icon);
Ok(())
}
/// Sets the window title.
pub fn set_window_title(context: &Context, title: &str) {
context.gfx_context.window.set_title(title);
}
/// Returns a reference to the Glutin window.
/// Ideally you should not need to use this because ggez
/// would provide all the functions you need without having
/// to dip into Glutin itself. But life isn't always ideal.
pub fn window(context: &Context) -> &glutin::Window {
let gfx = &context.gfx_context;
&gfx.window
}
/// Returns the size of the window in pixels as (width, height),
/// including borders, titlebar, etc.
/// Returns zeros if the window doesn't exist.
pub fn size(context: &Context) -> (f32, f32) {
let gfx = &context.gfx_context;
let dpi = gfx.window.get_hidpi_factor();
gfx.window
.get_outer_size()
.map(|logical_size| logical_size.to_physical(dpi))
.map(|physical_size| (physical_size.width as f32, physical_size.height as f32))
.unwrap_or((0.0, 0.0))
}
/// Returns the size of the window's underlying drawable in pixels as (width, height).
/// Returns zeros if window doesn't exist.
pub fn drawable_size(context: &Context) -> (f32, f32) {
let gfx = &context.gfx_context;
let dpi = gfx.window.get_hidpi_factor();
gfx.window
.get_inner_size()
.map(|logical_size| logical_size.to_physical(dpi))
.map(|physical_size| (physical_size.width as f32, physical_size.height as f32))
.unwrap_or((0.0, 0.0))
}
/// Returns raw `gfx-rs` state objects, if you want to use `gfx-rs` to write
/// your own graphics pipeline then this gets you the interfaces you need
/// to do so.
///
/// Returns all the relevant objects at once;
/// getting them one by one is awkward 'cause it tends to create double-borrows
/// on the Context object.
pub fn gfx_objects(
context: &mut Context,
) -> (
&mut <GlBackendSpec as BackendSpec>::Factory,
&mut <GlBackendSpec as BackendSpec>::Device,
&mut gfx::Encoder<
<GlBackendSpec as BackendSpec>::Resources,
<GlBackendSpec as BackendSpec>::CommandBuffer,
>,
gfx::handle::RawDepthStencilView<<GlBackendSpec as BackendSpec>::Resources>,
gfx::handle::RawRenderTargetView<<GlBackendSpec as BackendSpec>::Resources>,
) {
let gfx = &mut context.gfx_context;
let f = &mut gfx.factory;
let d = gfx.device.as_mut();
let e = &mut gfx.encoder;
let dv = gfx.depth_view.clone();
let cv = gfx.data.out.clone();
(f, d, e, dv, cv)
}
/// All types that can be drawn on the screen implement the `Drawable` trait.
pub trait Drawable {
/// Draws the drawable onto the rendering target.
fn draw(&self, ctx: &mut Context, param: DrawParam) -> GameResult;
/// Returns a bounding box in the form of a `Rect`.
///
/// It returns `Option` because some `Drawable`s may have no bounding box
/// (an empty `SpriteBatch` for example).
fn dimensions(&self, ctx: &mut Context) -> Option<Rect>;
/// Sets the blend mode to be used when drawing this drawable.
/// This overrides the general [`graphics::set_blend_mode()`](fn.set_blend_mode.html).
/// If `None` is set, defers to the blend mode set by
/// `graphics::set_blend_mode()`.
fn set_blend_mode(&mut self, mode: Option<BlendMode>);
/// Gets the blend mode to be used when drawing this drawable.
fn blend_mode(&self) -> Option<BlendMode>;
}
/// Applies `DrawParam` to `Rect`.
pub fn transform_rect(rect: Rect, param: DrawParam) -> Rect {
let w = param.src.w * param.scale.x * rect.w;
let h = param.src.h * param.scale.y * rect.h;
let offset_x = w * param.offset.x;
let offset_y = h * param.offset.y;
let dest_x = param.dest.x - offset_x;
let dest_y = param.dest.y - offset_y;
let mut r = Rect {
w,
h,
x: dest_x + rect.x * param.scale.x,
y: dest_y + rect.y * param.scale.y,
};
r.rotate(param.rotation);
r
}
#[cfg(test)]
mod tests {
use crate::graphics::{transform_rect, DrawParam, Rect};
use approx::assert_relative_eq;
use std::f32::consts::PI;
#[test]
fn headless_test_transform_rect() {
{
let r = Rect {
x: 0.0,
y: 0.0,
w: 1.0,
h: 1.0,
};
let param = DrawParam::new();
let real = transform_rect(r, param);
let expected = r;
assert_relative_eq!(real, expected);
}
{
let r = Rect {
x: -1.0,
y: -1.0,
w: 2.0,
h: 1.0,
};
let param = DrawParam::new().scale([0.5, 0.5]);
let real = transform_rect(r, param);
let expected = Rect {
x: -0.5,
y: -0.5,
w: 1.0,
h: 0.5,
};
assert_relative_eq!(real, expected);
}
{
let r = Rect {
x: -1.0,
y: -1.0,
w: 1.0,
h: 1.0,
};
let param = DrawParam::new().offset([0.5, 0.5]);
let real = transform_rect(r, param);
let expected = Rect {
x: -1.5,
y: -1.5,
w: 1.0,
h: 1.0,
};
assert_relative_eq!(real, expected);
}
{
let r = Rect {
x: 1.0,
y: 0.0,
w: 2.0,
h: 1.0,
};
let param = DrawParam::new().rotation(PI * 0.5);
let real = transform_rect(r, param);
let expected = Rect {
x: -1.0,
y: 1.0,
w: 1.0,
h: 2.0,
};
assert_relative_eq!(real, expected);
}
{
let r = Rect {
x: -1.0,
y: -1.0,
w: 2.0,
h: 1.0,
};
let param = DrawParam::new()
.scale([0.5, 0.5])
.offset([0.0, 1.0])
.rotation(PI * 0.5);
let real = transform_rect(r, param);
let expected = Rect {
x: 0.5,
y: -0.5,
w: 0.5,
h: 1.0,
};
assert_relative_eq!(real, expected);
}
}
}
| true |
fca2b1ca07718a93b0324a84061b75adc0d591c9
|
Rust
|
m4b/goblin
|
/src/pe/options.rs
|
UTF-8
| 366 | 2.65625 | 3 |
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
/// Parsing Options structure for the PE parser
#[derive(Debug, Copy, Clone)]
pub struct ParseOptions {
/// Wether the parser should resolve rvas or not. Default: true
pub resolve_rva: bool,
}
impl ParseOptions {
/// Returns a parse options structure with default values
pub fn default() -> Self {
ParseOptions { resolve_rva: true }
}
}
| true |
4b357690d35ab3650e277d8ee03300bbdd7ef10e
|
Rust
|
thenixan/advent-of-code-2018
|
/src/days/third.rs
|
UTF-8
| 5,467 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::collections::HashMap;
use std::fmt;
use std::fmt::Formatter;
use std::io::BufRead;
use std::str::FromStr;
use days::print_header;
use days::read_file;
pub fn run_first_task() {
print_header(3, 1);
match read_file("days/3/input")
.map(|reader| first_task_job(reader)) {
Ok(x) => println!("Result: {}", x),
Err(_) => println!("Error"),
};
}
fn first_task_job<T>(reader: T) -> usize where T: BufRead {
reader
.lines()
.filter_map(|line| line.ok())
.filter_map(|line| line.parse::<Tile>().ok())
.fold(HashMap::new(), |mut plot, tile| {
for i in tile.padding_left..tile.padding_left + tile.size.width {
for j in tile.padding_top..tile.padding_top + tile.size.height {
let val = plot.entry((i, j)).or_insert_with(|| 0);
*val += 1;
}
}
plot
})
.iter()
.filter(|&(_, v)| { *v > 1 })
.count()
}
pub fn run_second_task() {
print_header(3, 2);
match read_file("days/3/input")
.map(|reader| second_task_job(reader)) {
Ok(x) => println!("Result: {}", x),
Err(_) => println!("Error")
};
}
fn second_task_job<T>(reader: T) -> String where T: BufRead {
let tiles = reader
.lines()
.filter_map(|line| line.ok())
.filter_map(|line| line.parse::<Tile>().ok())
.collect::<Vec<_>>();
let plot = tiles
.iter()
.fold(HashMap::new(), |mut plot, tile| {
for i in tile.padding_left..tile.padding_left + tile.size.width {
for j in tile.padding_top..tile.padding_top + tile.size.height {
let val = plot.entry((i, j)).or_insert_with(|| 0);
*val += 1;
}
}
plot
})
.into_iter()
.filter(|&(_, v)| { v == 1 })
.collect::<HashMap<_, _>>();
tiles.into_iter().find(|tile| tile.find_disconnected(&plot).is_some()).unwrap().id
}
type Plot = HashMap<(i32, i32), i32>;
struct Size {
height: i32,
width: i32,
}
impl Tile {
fn find_disconnected(&self, plot: &Plot) -> Option<&Tile> {
let mut i = self.padding_left;
let mut result = true;
while result && i < self.padding_left + self.size.width {
let mut j = self.padding_top;
while result && j < self.padding_top + self.size.height {
match plot.get(&(i, j)) {
Some(x) => if *x != 1 { result = false; },
None => result = false,
}
j += 1
}
i += 1;
}
match result {
true => Some(self),
false => None,
}
}
}
impl Size {
fn new(height: i32, width: i32) -> Size {
Size { height, width }
}
}
impl fmt::Display for Size {
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
write!(f, "(h: {}, w: {}", self.height, self.width)
}
}
impl FromStr for Size {
type Err = String;
fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
let parts: Vec<&str> = s.split(|c| c == 'x').collect();
let width = parts[0].parse::<i32>();
let height = parts[1].parse::<i32>();
match (width, height) {
(Ok(w), Ok(h)) => Ok(Size::new(h, w)),
_ => Err("error parsing sizes".to_string()),
}
}
}
struct Tile {
id: String,
size: Size,
padding_top: i32,
padding_left: i32,
}
impl Tile {
fn new(id: String, padding_left: i32, padding_top: i32, size: Size) -> Tile {
Tile { id, size, padding_top, padding_left }
}
}
impl fmt::Display for Tile {
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
write!(f, "id: {}, size: {}, left: {}, top: {}", self.id, self.size, self.padding_left, self.padding_top)
}
}
impl FromStr for Tile {
type Err = String;
fn from_str(s: &str) -> Result<Tile, Self::Err> {
let parts: Vec<&str> = s.split_whitespace().collect();
let id: &str = &parts[0][1..];
let paddings: Vec<&str> = parts[2].split(|c| c == ',' || c == ':').collect();
let padding_left = paddings[0].parse::<i32>();
let padding_top = paddings[1].parse::<i32>();
match (padding_left, padding_top) {
(Ok(left), Ok(top)) => {
let size = parts[3].parse::<Size>();
match size {
Ok(s) => Ok(Tile::new(id.to_string(), left, top, s)),
Err(e) => Err(e)
}
}
_ => Err("cannot parse paddings".to_string()),
}
}
}
#[cfg(test)]
mod tests {
use test::Bencher;
use days::third::first_task_job;
use days::third::second_task_job;
#[test]
fn test_task_one() {
assert_eq!(4, first_task_job("#1 @ 1,3: 4x4\n#2 @ 3,1: 4x4\n#3 @ 5,5: 2x2".as_bytes()))
}
#[bench]
fn bench_first(b: &mut Bencher) {
b.iter(|| first_task_job("#1 @ 1,3: 4x4\n#2 @ 3,1: 4x4\n#3 @ 5,5: 2x2".as_bytes()));
}
#[test]
fn test_task_two() {
assert_eq!("3", second_task_job("#1 @ 1,3: 4x4\n#2 @ 3,1: 4x4\n#3 @ 5,5: 2x2".as_bytes()))
}
#[bench]
fn bench_second(b: &mut Bencher) {
b.iter(|| second_task_job("#1 @ 1,3: 4x4\n#2 @ 3,1: 4x4\n#3 @ 5,5: 2x2".as_bytes()));
}
}
| true |
c8e74548ece00be41a9ee8383c6080ac1fbd2e95
|
Rust
|
arcnmx/specialize-rs
|
/src/lib.rs
|
UTF-8
| 20,280 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
#![cfg_attr(test, feature(specialization))]
/*!
* Experimental specialization macros.
*
* Syntax is highly volatile and subject to change. The use of these macros
* requires an unstable rust compiler and the `#![feature(specialization)]`
* crate attribute.
*
* ## constrain!()
*
* `constrain!()` attempts to add additional trait bounds to a generic type.
*
* ```
* # #![feature(specialization)]
* # #[macro_use]
* # extern crate specialize;
* # fn main() { }
* use std::io::{Write, Read, Seek, SeekFrom, Cursor, Repeat};
*
* fn generic_function<T: Read>(read: &mut T) {
* if let Some(read_seek) = constrain!(ref mut [read: Read + Seek] = Cursor<Repeat>) {
* read_seek.seek(SeekFrom::Start(0));
* } else if constrain!(type [T: Write]) {
* // ...
* }
* }
* ```
*
* ### Caveats and Notes
*
* There are a few oddities in the above example...
*
* 1. You must specify a name for the trait to be used behind the scenes for
* specialization, as in `IsReadSeek`. It may be called whatever you like.
* 2. A default fallback type that implements the desired trait bounds must also
* be provided. This type must be concrete but will never be used or
* instantiated, and is only used to appease the type checker.
* 3. The `ref` and `mut` keywords may be left out in order to move or immutably
* borrow the value.
* 4. The `read` value part may be an expression if surrounded in parenthesis.
*
* ### Concrete constrain!()
*
* `constrain!()` can also be used to convert a generic type into a concrete type.
* Similar to `Any::downcast_ref`, but enforced at compile time and without
* requiring the `Any` or `Reflect` trait bounds.
*
* ```
* # #![feature(specialization)]
* # #[macro_use]
* # extern crate specialize;
* # fn main() { }
* fn generic_function<T: ?Sized>(value: &T) -> bool {
* if let Some(value_bool) = constrain!(ref value as bool) {
* *value_bool
* } else if constrain!(type T as i32) {
* true
* } else {
* false
* }
* }
* ```
*
* ## specialize! { }
*
* Provides a type-level `match` statement with specialization bounds.
*
* ```
* # #![feature(specialization)]
* # #[macro_use]
* # extern crate specialize;
* # fn main() { }
* use std::io::{Read, BufRead, Write, copy, sink};
*
* fn generic_function<T: Read>(read: &mut T) {
* specialize! {
* trait fn Trait::nonsensical[W: Write](&mut self, w: &mut W) -> bool where [W: Write];
*
* match impl['a, T: Read] for T where [T: Read] {
* where [T: BufRead] => self.fill_buf().and_then(|buf| w.write(buf)).is_ok(),
* impl[U: Into<u8> + Clone] where [T: BufRead + Iterator<Item=&'a U>, U: 'a] =>
* w.write(&self.cloned().map(Into::into).collect::<Vec<u8>>()).is_ok(),
* _ => copy(self, w).is_ok(),
* }
* }
*
* Trait::nonsensical(read, &mut sink());
* }
* ```
*
* ### Caveats
*
* 1. This is not an inline statement or expression, and is instead used to
* generate a trait and method pair. This means the prototype must be specified
* up-front, and no variables will be automatically captured from the outside
* scope.
* 2. Generic bounds and where clauses must be surrounded by `[]` rather than
* `<>` or similar due to macro parsing limitations.
* 3. The specialization "more specific" rules must be followed in order to
* prevent conflicting trait impls.
* 4. The various `where [B: Bounds...]` clauses may be omitted, and are mostly
* included here for syntax demonstration.
*
*/
#[macro_export]
#[doc(hidden)]
macro_rules! specialize {
(
trait fn $trait_id:ident :: $trait_fn_id:ident
$($unparsed:tt)*
) => {
specialize! {
@parse_fn_bounds
$trait_id $trait_fn_id
$($unparsed)*
}
};
(@parse_fn_bounds $trait_id:ident $trait_fn_id:ident (
$($trait_fn_args:tt)*
)
$($unparsed:tt)*
) => {
specialize! {
@parse_fn_ty
$trait_id $trait_fn_id () ($($trait_fn_args)*)
$($unparsed)*
}
};
(@parse_fn_bounds $trait_id:ident $trait_fn_id:ident [
$($trait_fn_bounds:tt)+
] (
$($trait_fn_args:tt)*
)
$($unparsed:tt)*
) => {
specialize! {
@parse_fn_ty
$trait_id $trait_fn_id ($($trait_fn_bounds)+) ($($trait_fn_args)*)
$($unparsed)*
}
};
(@parse_fn_ty $trait_id:ident $trait_fn_id:ident $trait_fn_bounds:tt $trait_fn_args:tt
;
$($unparsed:tt)*
) => {
specialize! {
@parse_impl
$trait_id
($trait_fn_id (()) $trait_fn_bounds () $trait_fn_args)
$($unparsed)*
}
};
(@parse_fn_ty $trait_id:ident $trait_fn_id:ident $trait_fn_bounds:tt $trait_fn_args:tt
-> $trait_fn_ty:ty;
$($unparsed:tt)*
) => {
specialize! {
@parse_impl
$trait_id
($trait_fn_id ($trait_fn_ty) $trait_fn_bounds () $trait_fn_args)
$($unparsed)*
}
};
(@parse_fn_ty $trait_id:ident $trait_fn_id:ident $trait_fn_bounds:tt $trait_fn_args:tt
-> $trait_fn_ty:ty where [$($trait_fn_where:tt)+];
$($unparsed:tt)*
) => {
specialize! {
@parse_impl
$trait_id
($trait_fn_id ($trait_fn_ty) $trait_fn_bounds (where $($trait_fn_where)+) $trait_fn_args)
$($unparsed)*
}
};
(@parse_fn_ty $trait_id:ident $trait_fn_id:ident $trait_fn_bounds:tt $trait_fn_args:tt
where [$($trait_fn_where:tt)+];
$($unparsed:tt)*
) => {
specialize! {
@parse_impl
$trait_id
($trait_fn_id (()) $trait_fn_bounds (where $($trait_fn_where)+) $trait_fn_args)
$($unparsed)*
}
};
(@parse_impl $trait_id:ident $trait_fn:tt
match impl[
$($trait_impl_bounds:tt)*
] for $trait_impl_id:ty where [
$($trait_impl_where:tt)+
] {
$($unparsed:tt)*
}
) => {
specialize! {
@parse
($trait_id ($trait_impl_id) ($($trait_impl_bounds)*) (, $($trait_impl_where)+))
$trait_fn
()
($($unparsed)*)
}
};
(@parse_impl $trait_id:ident $trait_fn:tt
match impl[
$($trait_impl_bounds:tt)*
] for $trait_impl_id:ty {
$($unparsed:tt)*
}
) => {
specialize! {
@parse
($trait_id ($trait_impl_id) ($($trait_impl_bounds)*) ())
$trait_fn
()
($($unparsed)*)
}
};
// Parse match arms
// TODO: support T: X => {} match syntax without trailing comma?
(@parse
$trait_impl:tt
$trait_fn:tt
($($clauses:tt)*)
(
where [
$($clause_where:tt)*
] => $clause_expr:expr,
$($unparsed:tt)*
)
) => {
specialize! { @parse
$trait_impl
$trait_fn
($($clauses)*
(() ($($clause_where)*) $clause_expr)
)
($($unparsed)*)
}
};
(@parse
$trait_impl:tt
$trait_fn:tt
($($clauses:tt)*)
(
impl [
$($clause_bounds:tt)*
] where [
$($clause_where:tt)*
] => $clause_expr:expr,
$($unparsed:tt)*
)
) => {
specialize! { @parse
$trait_impl
$trait_fn
($($clauses)*
(($($clause_bounds)*) ($($clause_where)*) $clause_expr)
)
($($unparsed)*)
}
};
// Match catchall
(@parse
$trait_impl:tt
$trait_fn:tt
($($clauses:tt)*)
(
_ => $clause_expr:expr $(,)*
)
) => {
specialize! { @parse
$trait_impl
$trait_fn
($($clauses)*
(() (u8: Copy) $clause_expr)
)
()
}
};
// Base case
(@parse
$trait_impl:tt
$trait_fn:tt
$clauses:tt
(/*unparsed*/)
) => {
specialize! { @itemize
$trait_impl
$trait_fn
()
$clauses
}
};
// Clause to trait impl
(@itemize
($trait_id:ident ($trait_impl_id:ty) ($($trait_impl_bounds:tt)*) ($($trait_impl_where:tt)*))
($trait_fn_id:ident ($trait_fn_ty:ty) ($($trait_fn_bounds:tt)*) ($($trait_fn_where:tt)*) ($($trait_fn_args:tt)*))
($($items:tt)*)
((($($clause_bounds:tt)*) ($($clause_where:tt)*) $clause_expr:expr) $($clauses:tt)*)
) => {
specialize! { @itemize
($trait_id ($trait_impl_id) ($($trait_impl_bounds)*) ($($trait_impl_where)*))
($trait_fn_id ($trait_fn_ty) ($($trait_fn_bounds)*) ($($trait_fn_where)*) ($($trait_fn_args)*))
($($items)*
impl<$($trait_impl_bounds)*, $($clause_bounds)*> $trait_id for $trait_impl_id where $($clause_where)* $($trait_impl_where)* {
#[allow(unused_mut, unused_variables)]
default fn $trait_fn_id<
$($trait_fn_bounds)*
>($($trait_fn_args)*) -> $trait_fn_ty
$($trait_fn_where)* {
$clause_expr
}
}
)
($($clauses)*)
}
};
// Base case
(@itemize
$trait_impl:tt
$trait_fn:tt
($($items:tt)*)
(/*clauses*/)
) => {
specialize! { @trait
$trait_impl
$trait_fn
}
specialize! { @items $($items)* }
};
(@trait
($trait_id:ident ($trait_impl_id:ty) ($($trait_impl_bounds:tt)*) ($($trait_impl_where:tt)*))
($trait_fn_id:ident ($trait_fn_ty:ty) ($($trait_fn_bounds:tt)*) ($($trait_fn_where:tt)*) ($($trait_fn_args:tt)*))
) => {
specialize! { @items
trait $trait_id {
#[allow(patterns_in_fns_without_body)]
fn $trait_fn_id<
$($trait_fn_bounds)*
>($($trait_fn_args)*) -> $trait_fn_ty
$($trait_fn_where)*;
}
}
};
/*(@
($trait_id:ident ($trait_impl_id:ty) ($($trait_impl_bounds:tt)*) ($($trait_impl_where:tt)*))
($trait_fn_id:ident ($trait_fn_ty:ty) ($($trait_fn_bounds:tt)*) ($($trait_fn_where:tt)*) ($($trait_fn_args:tt)*))
($($items:tt)*)
($($clauses:tt)*)
($($unparsed:tt)*)
) => {
specialize! { @
($trait_id ($trait_impl_id) ($($trait_impl_bounds)*) ($($trait_impl_where)*))
($trait_fn_id ($trait_fn_ty) ($($trait_fn_bounds)*) ($($trait_fn_where)*) ($($trait_fn_args)*))
($($items:tt)*)
($($clauses:tt)*)
($($unparsed:tt)*)
}
...
};*/
/*(@
$trait_impl:tt
$trait_fn:tt
$items:tt
$clauses:tt
$unparsed:tt
) => {
specialize! { @
$trait_impl
$trait_fn
$items
$clauses
$unparsed
}
};*/
// Convert tts to items
(@items $($i:item)*) => { $($i)* };
// Drops tokens into the void
(@drop $($tt:tt)*) => { };
}
#[macro_export]
#[doc(hidden)]
macro_rules! constrain {
(ref mut [$value_id:tt : $($bounds:tt)*] = $default_ty:ty) => {
{
constrain! { @trait __ConstrainBounds__ ($($bounds)*) ($default_ty) }
constrain! { @expr __ConstrainBounds__::as_mut($value_id) }
}
};
(ref [$value_id:tt : $($bounds:tt)*] = $default_ty:ty) => {
{
constrain! { @trait __ConstrainBounds__ ($($bounds)*) ($default_ty) }
constrain! { @expr __ConstrainBounds__::as_ref($value_id) }
}
};
(ref [$value_id:tt : $($bounds:tt)*] = $default_ty:ty) => {
{
constrain! { @trait __ConstrainBounds__ ($($bounds)*) ($default_ty) }
constrain! { @expr __ConstrainBounds__::as_ref($value_id) }
}
};
(type [$value_id:tt : $($bounds:tt)*]) => {
{
constrain! { @trait __ConstrainBounds__ ($($bounds)*) }
constrain! { @expr <$value_id as __ConstrainBounds__>::is() }
}
};
([$value_id:tt : $($bounds:tt)*] = $default_ty:ty) => {
{
constrain! { @trait __ConstrainBounds__ ($($bounds)*) ($default_ty) }
constrain! { @expr __ConstrainBounds__::move_($value_id) }
}
};
(ref mut $value_id:tt as $ty:ty) => {
{
constrain! { @trait_concrete __ConstrainEq__ ($ty) }
constrain! { @expr __ConstrainEq__::as_mut($value_id) }
}
};
(ref $value_id:tt as $ty:ty) => {
{
constrain! { @trait_concrete __ConstrainEq__ ($ty) }
constrain! { @expr __ConstrainEq__::as_ref($value_id) }
}
};
(type $ty:ty as $ty_eq:ty) => {
{
constrain! { @trait_concrete __ConstrainEq__ ($ty_eq) }
constrain! { @expr <$ty as __ConstrainEq__>::is() }
}
};
($value_id:tt as $ty:ty) => {
{
constrain! { @trait_concrete __ConstrainEq__ ($ty) }
constrain! { @expr __ConstrainEq__::move_($value_id) }
}
};
(@trait_concrete $trait_id:ident ($ty:ty)) => {
trait $trait_id {
fn is() -> bool;
fn move_(self) -> Option<$ty> where Self: Sized, $ty: Sized;
fn as_ref(&self) -> Option<&$ty>;
fn as_mut(&mut self) -> Option<&mut $ty>;
}
impl<T: ?Sized> $trait_id for T {
#[inline(always)]
default fn is() -> bool { false }
#[inline(always)]
default fn move_(self) -> Option<$ty> where Self: Sized, $ty: Sized { None }
#[inline(always)]
default fn as_ref(&self) -> Option<&$ty> { None }
#[inline(always)]
default fn as_mut(&mut self) -> Option<&mut $ty> { None }
}
impl $trait_id for $ty {
#[inline(always)]
default fn is() -> bool { true }
#[inline(always)]
fn move_(self) -> Option<$ty> where Self: Sized, $ty: Sized { Some(self) }
#[inline(always)]
fn as_ref(&self) -> Option<&$ty> { Some(self) }
#[inline(always)]
fn as_mut(&mut self) -> Option<&mut $ty> { Some(self) }
}
};
(@trait $trait_id:ident ($($bounds:tt)*) ($default_ty:ty)) => {
constrain! { @items
trait $trait_id {
type Out: ?Sized + $($bounds)*;
fn is() -> bool;
fn move_(self) -> Option<Self::Out> where Self: Sized, Self::Out: Sized;
fn as_ref(&self) -> Option<&Self::Out>;
fn as_mut(&mut self) -> Option<&mut Self::Out>;
}
impl<T: ?Sized + $($bounds)*> $trait_id for T {
type Out = T;
#[inline(always)]
fn is() -> bool { true }
#[inline(always)]
fn move_(self) -> Option<Self::Out> where Self: Sized, Self::Out: Sized { Some(self) }
#[inline(always)]
fn as_ref(&self) -> Option<&Self::Out> { Some(self) }
#[inline(always)]
fn as_mut(&mut self) -> Option<&mut Self::Out> { Some(self) }
}
}
impl<T: ?Sized> $trait_id for T {
default type Out = $default_ty;
#[inline(always)]
default fn is() -> bool { false }
#[inline(always)]
default fn move_(self) -> Option<Self::Out> where Self: Sized, Self::Out: Sized { None }
#[inline(always)]
default fn as_ref(&self) -> Option<&Self::Out> { None }
#[inline(always)]
default fn as_mut(&mut self) -> Option<&mut Self::Out> { None }
}
};
(@trait $trait_id:ident ($($bounds:tt)*)) => {
constrain! { @items
trait $trait_id {
fn is() -> bool;
}
impl<T: ?Sized + $($bounds)*> $trait_id for T {
#[inline(always)]
fn is() -> bool { true }
}
}
impl<T: ?Sized> $trait_id for T {
#[inline(always)]
default fn is() -> bool { false }
}
};
(@items $($i:item)*) => { $($i)* };
(@expr $i:expr) => { $i };
}
#[cfg(test)]
mod test {
#[test]
fn by_type() {
fn is_default<T: ?Sized>() -> bool {
specialize! {
trait fn IsDefault::is_default() -> bool;
match impl[T: ?Sized] for T {
// Silly extraneous bounds for testing
where [T: Default + Default, T: Default] => true,
where [T: Default + Copy] => true,
where [T: Default + Copy + ::std::ops::Deref, T::Target: Copy] => true,
_ => false,
}
}
T::is_default()
}
assert_eq!(true, is_default::<()>());
assert_eq!(false, is_default::<[()]>());
assert_eq!(false, is_default::<&'static ()>());
}
#[test]
fn by_value() {
fn is_default<T: ?Sized>(t: &T) -> bool {
specialize! {
trait fn IsDefault::is_default(&self, true_: bool) -> bool;
match impl[T: ?Sized] for T {
where [T: Default] => true && true_,
where [T: Default + PartialEq] => *self == <Self as Default>::default() && true_,
_ => false && true_,
}
}
t.is_default(true)
}
assert_eq!(true, is_default(&()));
assert_eq!(true, is_default(&0u8));
assert_eq!(false, is_default(&1u8));
assert_eq!(false, is_default(&[()][..]));
}
#[test]
fn fn_bounds() {
use std::io::{self, Write, sink};
use std::fmt::Display;
fn write_test<T: ?Sized>(v: &T) -> io::Result<()> {
specialize! {
trait fn WriteTest::write_test[W: Write](&self, mut w: W) -> io::Result<()>;
match impl[T: ?Sized] for T {
where [T: Display] => writeln!(w, "{}", self),
_ => Err(io::Error::new(io::ErrorKind::Other, "unimplemented")),
}
}
v.write_test(sink())
}
assert!(write_test(&0u8).is_ok());
assert!(write_test(&()).is_err());
}
#[test]
fn constrain_ref() {
use std::fmt::Display;
fn is_display<T: ?Sized>(t: &T) -> bool {
if let Some(display) = constrain!(ref [t: Display] = u8) {
println!("{}", display);
true
} else {
false
}
}
assert_eq!(is_display(&()), false);
assert_eq!(is_display(&0u32), true);
}
#[test]
fn constrain_mut() {
use std::io::{Write, Stdout, sink};
fn try_write<T: ?Sized>(t: &mut T) -> bool {
if let Some(write) = constrain!(ref mut [t: Write] = Stdout) {
writeln!(write, "hello!").is_ok()
} else {
false
}
}
assert_eq!(try_write(&mut ()), false);
assert_eq!(try_write(&mut sink()), true);
}
#[test]
fn constrain_eq() {
fn is_bool<T: ?Sized>() -> bool {
constrain!(type T as bool)
}
assert!(is_bool::<bool>());
assert!(!is_bool::<&bool>());
assert!(!is_bool::<u8>());
assert!(constrain!(type bool as bool));
}
#[test]
fn constrain_eq_value() {
fn is_bool<T: ?Sized>(v: &T) -> bool {
constrain!(ref v as bool).is_some()
}
assert!(is_bool(&true));
assert!(!is_bool(&0u8));
}
}
| true |
63e333f257e33ed22ea9fdf61d90e434ce9291b4
|
Rust
|
LEEDASILVA/rust
|
/reference.rs
|
UTF-8
| 759 | 4.21875 | 4 |
[] |
no_license
|
// another way to refere to variables
// for example: someone thats called Julia and you call Jul, you are
// refering to the same person but in different ways
fn main() {
let mut x = 10;
let xr = &x; // get a reference to x
println!("x is {} and xr is {}", x, xr);
// xr += 1; // does not work!
let a = &mut x; // mutable reference
*a += 1; // will work!
println!("a is {}", a);
// this will give error, you can define a mutable reference to x and
// at the same time borrow it, so a borrows x!
// println!("x is {}", x);
// to do this you can
// {
// let a = &mut x; // mutable reference
// *a += 1; // will work!
// }
// x will be 11!
// println!("x is {}", x);
}
| true |
c441e2020fb338983c8f4a88a6d81ce0619dd178
|
Rust
|
xnti/keci-mobile-api
|
/src/action/user.rs
|
UTF-8
| 5,820 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
use crate::model::basket::{Basket, BasketItem};
use crate::model::user::{Claims, User};
use crate::service::basket::BasketService;
use crate::service::user::UserService;
use crate::traits::service::Creator;
use bcrypt::hash;
use bcrypt::verify;
use bson::oid::ObjectId;
use bson::{from_bson, to_bson};
use jsonwebtoken::{encode, EncodingKey, Header};
use serde::Deserialize;
pub fn create_anon_with_basket(
user_service: UserService,
basket_service: BasketService,
product_id: String,
seller_id: String,
listing_id: String,
) -> Result<String, String> {
match user_service.create_anon() {
Ok(user_result) => match user_result.inserted_id {
bson::Bson::ObjectId(id) => {
let token = get_guest_user_token(id.to_string());
let cookie = format!("access_token={}", token);
let basket_item = BasketItem::new(
ObjectId::with_string(&product_id).expect("product_id: Invalid ObjectId string"),
ObjectId::with_string(&seller_id).expect("seller_id: Invalid ObjectId string"),
ObjectId::with_string(&listing_id).expect("listing_id: Invalid ObjectId string"),
1,
);
let basket = Basket::new(
ObjectId::with_string(&id.to_string()).expect("Invalid ObjectId string"),
vec![basket_item],
true,
);
match basket_service.create(&basket) {
Ok(_basket_result) => Ok(cookie),
Err(_e) => Err("Error while creating basket for anon user, {:?}".to_string()),
}
}
_ => Err("Error: inserted anon user id is not ObjectId".to_string()),
},
Err(_e) => Err("Error while creating anon user: {:?}".to_string()),
}
}
fn get_registered_user_token(id: String) -> String {
let claims = Claims {
sub: id,
user_type: String::from("registered"),
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(dotenv!("JWT_SECRET").as_ref()),
)
.unwrap();
token
}
fn get_guest_user_token(id: String) -> String {
let claims = Claims {
sub: id,
user_type: String::from("guest"),
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(dotenv!("JWT_SECRET").as_ref()),
)
.unwrap();
token
}
pub enum UserCreateResult {
UserAlreadyExists,
UserCreated(String),
GuestUserNotRegistered,
}
pub fn create(
user_service: UserService,
phone: String,
password: String,
user_id_option: Option<String>,
) -> Result<UserCreateResult, String> {
match user_service.get(&phone) {
Ok(user_result) => match user_result {
Some(_user) => Ok(UserCreateResult::UserAlreadyExists),
None => match user_id_option {
Some(user_id) => {
let hashed = hash(&password, 4).unwrap();
match user_service.register(&user_id, &phone, &hashed) {
Ok(user_result) => {
if user_result.modified_count == 1 {
let token = get_registered_user_token(user_id.to_string());
let cookie = format!("access_token={}", token);
Ok(UserCreateResult::UserCreated(cookie))
} else {
Ok(UserCreateResult::GuestUserNotRegistered)
}
}
Err(_e) => Err("Error while registering user".to_string()),
}
}
None => {
let hashed = hash(&password, 4).unwrap();
let user = User::new(&phone, &hashed);
match user_service.create(&user) {
Ok(user_result) => match user_result.inserted_id {
bson::Bson::ObjectId(id) => {
let token = get_registered_user_token(id.to_string());
let cookie = format!("access_token={}", token);
Ok(UserCreateResult::UserCreated(cookie))
}
_ => Err("Error: inserted user id is not type of ObjectId".to_string()),
},
Err(_e) => Err("Error while creating user".to_string()),
}
}
},
},
Err(_e) => Err("Error while getting user".to_string()),
}
}
pub enum LoginResult {
Verified(String),
UserNotExists,
NotVerified,
}
#[derive(Deserialize, Debug, Clone)]
struct UserJson {
_id: bson::oid::ObjectId,
phone: String,
password: String,
}
pub fn login(
user_service: UserService,
phone: String,
password: String,
user_id_option: Option<String>,
user_type_option: Option<String>,
) -> Result<LoginResult, String> {
match user_service.get(&phone) {
Ok(user_option) => match user_option {
Some(user_document) => {
let user_bson = to_bson(&user_document).unwrap();
let user = from_bson::<UserJson>(user_bson).unwrap();
let verify_result = verify(&password, &user.password);
match verify_result {
Ok(verified) => {
if verified == true {
match user_id_option {
Some(_guest_id) => {
if user_type_option.unwrap() == "guest" {
// TODO: merge basket
}
let token = get_registered_user_token(user._id.to_string());
let cookie = format!("access_token={}; path=/", token);
Ok(LoginResult::Verified(cookie))
}
None => {
let token = get_registered_user_token(user._id.to_string());
let cookie = format!("access_token={}; path=/", token);
Ok(LoginResult::Verified(cookie))
}
}
} else {
Ok(LoginResult::NotVerified)
}
}
Err(_e) => Err("Error while verifying".to_string()),
}
}
None => Ok(LoginResult::UserNotExists),
},
Err(_e) => Err("Error while getting user".to_string()),
}
}
| true |
ff16e5f0c498fe1543d685108ae3b0bc8addbb1c
|
Rust
|
blasrodri/matecito-example
|
/src/main.rs
|
UTF-8
| 1,243 | 3.109375 | 3 |
[] |
no_license
|
use actix_web::{web, get, post, App, HttpRequest, HttpServer};
use matecito::Matecito;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let data = web::Data::new(Matecito::<String, String>::new(10_000));
HttpServer::new(move || {
App::new()
// .route("/", web::get().to(greet))
// .route("/{name}", web::get().to(greet))
.app_data(data.clone())
.service(index)
.service(index_post)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
#[get("/")]
async fn index(req: HttpRequest, data: web::Data<Matecito<String, String>>) -> String {
let asd = req.query_string().to_string();
// let asd: Vec<_> = asd.split("=").collect();
let app_name = data.get(asd.clone()).unwrap_or("not found".to_string()); // <- get app_name
format!("Hello {}!\n", app_name) // <- response with app_name
}
#[post("/")]
async fn index_post(req: HttpRequest, data: web::Data<Matecito<String, String>>) -> String {
let asd = req.query_string().to_string();
let asd: Vec<_> = asd.split("=").collect();
if asd.len() == 2 {
let (key, value) = (asd[0].to_owned(), asd[1].to_owned());
data.put(key, value);
}
format!("Done!")
}
| true |
829b436a783e324bf762420cf89644abf2b3588f
|
Rust
|
JohnTitor/stdsimd
|
/crates/core_simd/src/masks/full_masks.rs
|
UTF-8
| 12,171 | 3.28125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! Masks that take up full SIMD vector registers.
/// The error type returned when converting an integer to a mask fails.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct TryFromMaskError(());
impl core::fmt::Display for TryFromMaskError {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(
f,
"mask vector must have all bits set or unset in each lane"
)
}
}
macro_rules! define_mask {
{ $(#[$attr:meta])* struct $name:ident<const $lanes:ident: usize>($type:ty); } => {
$(#[$attr])*
#[derive(Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(transparent)]
pub struct $name<const $lanes: usize>($type)
where
$type: crate::LanesAtMost64;
impl<const LANES: usize> Copy for $name<LANES>
where
$type: crate::LanesAtMost64,
{}
impl<const LANES: usize> Clone for $name<LANES>
where
$type: crate::LanesAtMost64,
{
#[inline]
fn clone(&self) -> Self {
*self
}
}
impl<const $lanes: usize> $name<$lanes>
where
$type: crate::LanesAtMost64,
{
/// Construct a mask by setting all lanes to the given value.
pub fn splat(value: bool) -> Self {
Self(<$type>::splat(
if value {
-1
} else {
0
}
))
}
/// Tests the value of the specified lane.
///
/// # Panics
/// Panics if `lane` is greater than or equal to the number of lanes in the vector.
#[inline]
pub fn test(&self, lane: usize) -> bool {
assert!(lane < LANES, "lane index out of range");
self.0[lane] == -1
}
/// Sets the value of the specified lane.
///
/// # Panics
/// Panics if `lane` is greater than or equal to the number of lanes in the vector.
#[inline]
pub fn set(&mut self, lane: usize, value: bool) {
assert!(lane < LANES, "lane index out of range");
self.0[lane] = if value {
-1
} else {
0
}
}
}
impl<const $lanes: usize> core::convert::From<bool> for $name<$lanes>
where
$type: crate::LanesAtMost64,
{
fn from(value: bool) -> Self {
Self::splat(value)
}
}
impl<const $lanes: usize> core::convert::TryFrom<$type> for $name<$lanes>
where
$type: crate::LanesAtMost64,
{
type Error = TryFromMaskError;
fn try_from(value: $type) -> Result<Self, Self::Error> {
if value.as_slice().iter().all(|x| *x == 0 || *x == -1) {
Ok(Self(value))
} else {
Err(TryFromMaskError(()))
}
}
}
impl<const $lanes: usize> core::convert::From<$name<$lanes>> for $type
where
$type: crate::LanesAtMost64,
{
fn from(value: $name<$lanes>) -> Self {
value.0
}
}
impl<const $lanes: usize> core::convert::From<crate::BitMask<$lanes>> for $name<$lanes>
where
$type: crate::LanesAtMost64,
crate::BitMask<$lanes>: crate::LanesAtMost64,
{
fn from(value: crate::BitMask<$lanes>) -> Self {
// TODO use an intrinsic to do this efficiently (with LLVM's sext instruction)
let mut mask = Self::splat(false);
for lane in 0..LANES {
mask.set(lane, value.test(lane));
}
mask
}
}
impl<const $lanes: usize> core::convert::From<$name<$lanes>> for crate::BitMask<$lanes>
where
$type: crate::LanesAtMost64,
crate::BitMask<$lanes>: crate::LanesAtMost64,
{
fn from(value: $name<$lanes>) -> Self {
// TODO use an intrinsic to do this efficiently (with LLVM's trunc instruction)
let mut mask = Self::splat(false);
for lane in 0..LANES {
mask.set(lane, value.test(lane));
}
mask
}
}
impl<const $lanes: usize> core::fmt::Debug for $name<$lanes>
where
$type: crate::LanesAtMost64,
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_list()
.entries((0..LANES).map(|lane| self.test(lane)))
.finish()
}
}
impl<const $lanes: usize> core::fmt::Binary for $name<$lanes>
where
$type: crate::LanesAtMost64,
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
core::fmt::Binary::fmt(&self.0, f)
}
}
impl<const $lanes: usize> core::fmt::Octal for $name<$lanes>
where
$type: crate::LanesAtMost64,
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
core::fmt::Octal::fmt(&self.0, f)
}
}
impl<const $lanes: usize> core::fmt::LowerHex for $name<$lanes>
where
$type: crate::LanesAtMost64,
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
core::fmt::LowerHex::fmt(&self.0, f)
}
}
impl<const $lanes: usize> core::fmt::UpperHex for $name<$lanes>
where
$type: crate::LanesAtMost64,
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
core::fmt::UpperHex::fmt(&self.0, f)
}
}
impl<const LANES: usize> core::ops::BitAnd for $name<LANES>
where
$type: crate::LanesAtMost64,
{
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl<const LANES: usize> core::ops::BitAnd<bool> for $name<LANES>
where
$type: crate::LanesAtMost64,
{
type Output = Self;
#[inline]
fn bitand(self, rhs: bool) -> Self {
self & Self::splat(rhs)
}
}
impl<const LANES: usize> core::ops::BitAnd<$name<LANES>> for bool
where
$type: crate::LanesAtMost64,
{
type Output = $name<LANES>;
#[inline]
fn bitand(self, rhs: $name<LANES>) -> $name<LANES> {
$name::<LANES>::splat(self) & rhs
}
}
impl<const LANES: usize> core::ops::BitOr for $name<LANES>
where
$type: crate::LanesAtMost64,
{
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl<const LANES: usize> core::ops::BitOr<bool> for $name<LANES>
where
$type: crate::LanesAtMost64,
{
type Output = Self;
#[inline]
fn bitor(self, rhs: bool) -> Self {
self | Self::splat(rhs)
}
}
impl<const LANES: usize> core::ops::BitOr<$name<LANES>> for bool
where
$type: crate::LanesAtMost64,
{
type Output = $name<LANES>;
#[inline]
fn bitor(self, rhs: $name<LANES>) -> $name<LANES> {
$name::<LANES>::splat(self) | rhs
}
}
impl<const LANES: usize> core::ops::BitXor for $name<LANES>
where
$type: crate::LanesAtMost64,
{
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self::Output {
Self(self.0 ^ rhs.0)
}
}
impl<const LANES: usize> core::ops::BitXor<bool> for $name<LANES>
where
$type: crate::LanesAtMost64,
{
type Output = Self;
#[inline]
fn bitxor(self, rhs: bool) -> Self::Output {
self ^ Self::splat(rhs)
}
}
impl<const LANES: usize> core::ops::BitXor<$name<LANES>> for bool
where
$type: crate::LanesAtMost64,
{
type Output = $name<LANES>;
#[inline]
fn bitxor(self, rhs: $name<LANES>) -> Self::Output {
$name::<LANES>::splat(self) ^ rhs
}
}
impl<const LANES: usize> core::ops::Not for $name<LANES>
where
$type: crate::LanesAtMost64,
{
type Output = $name<LANES>;
#[inline]
fn not(self) -> Self::Output {
Self(!self.0)
}
}
impl<const LANES: usize> core::ops::BitAndAssign for $name<LANES>
where
$type: crate::LanesAtMost64,
{
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
self.0 &= rhs.0;
}
}
impl<const LANES: usize> core::ops::BitAndAssign<bool> for $name<LANES>
where
$type: crate::LanesAtMost64,
{
#[inline]
fn bitand_assign(&mut self, rhs: bool) {
*self &= Self::splat(rhs);
}
}
impl<const LANES: usize> core::ops::BitOrAssign for $name<LANES>
where
$type: crate::LanesAtMost64,
{
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
self.0 |= rhs.0;
}
}
impl<const LANES: usize> core::ops::BitOrAssign<bool> for $name<LANES>
where
$type: crate::LanesAtMost64,
{
#[inline]
fn bitor_assign(&mut self, rhs: bool) {
*self |= Self::splat(rhs);
}
}
impl<const LANES: usize> core::ops::BitXorAssign for $name<LANES>
where
$type: crate::LanesAtMost64,
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
self.0 ^= rhs.0;
}
}
impl<const LANES: usize> core::ops::BitXorAssign<bool> for $name<LANES>
where
$type: crate::LanesAtMost64,
{
#[inline]
fn bitxor_assign(&mut self, rhs: bool) {
*self ^= Self::splat(rhs);
}
}
}
}
define_mask! {
/// A mask equivalent to [SimdI8](crate::SimdI8), where all bits in the lane must be either set
/// or unset.
struct SimdMask8<const LANES: usize>(crate::SimdI8<LANES>);
}
define_mask! {
/// A mask equivalent to [SimdI16](crate::SimdI16), where all bits in the lane must be either set
/// or unset.
struct SimdMask16<const LANES: usize>(crate::SimdI16<LANES>);
}
define_mask! {
/// A mask equivalent to [SimdI32](crate::SimdI32), where all bits in the lane must be either set
/// or unset.
struct SimdMask32<const LANES: usize>(crate::SimdI32<LANES>);
}
define_mask! {
/// A mask equivalent to [SimdI64](crate::SimdI64), where all bits in the lane must be either set
/// or unset.
struct SimdMask64<const LANES: usize>(crate::SimdI64<LANES>);
}
define_mask! {
/// A mask equivalent to [SimdI128](crate::SimdI128), where all bits in the lane must be either set
/// or unset.
struct SimdMask128<const LANES: usize>(crate::SimdI128<LANES>);
}
define_mask! {
/// A mask equivalent to [SimdIsize](crate::SimdIsize), where all bits in the lane must be either set
/// or unset.
struct SimdMaskSize<const LANES: usize>(crate::SimdIsize<LANES>);
}
| true |
273368f1366bc4a3d2718570ee54df9acc084092
|
Rust
|
MarcusTL12/AdventOfCode2016Rust
|
/src/day8.rs
|
UTF-8
| 2,680 | 3.265625 | 3 |
[] |
no_license
|
use std::{
fs::File,
io::{BufRead, BufReader},
};
use arrayvec::ArrayVec;
pub const PARTS: [fn(); 2] = [part1, part2];
fn render_screen(screen: &[Vec<bool>]) {
for row in screen {
for &cell in row {
print!("{}", if cell { '█' } else { ' ' });
}
println!();
}
}
fn get_screen() -> Vec<Vec<bool>> {
const ROWS: usize = 6;
const COLS: usize = 50;
//
let mut screen = vec![vec![false; COLS]; ROWS];
//
for l in BufReader::new(File::open("inputfiles/day8/input.txt").unwrap())
.lines()
.map(|l| l.unwrap())
{
match l.split(' ').collect::<ArrayVec<_, 5>>().as_slice() {
["rect", x] => {
if let [Ok(a), Ok(b)] = x
.split('x')
.map(|s| s.parse())
.collect::<ArrayVec<_, 2>>()
.as_slice()
{
for i in 0..*b {
for j in 0..*a {
screen[i][j] = true;
}
}
}
}
["rotate", dir, a, _, b] => match *dir {
"column" => {
let colnr: usize =
a.split('=').last().unwrap().parse().unwrap();
let amt = b.parse().unwrap();
//
for (i, v) in (0..ROWS)
.cycle()
.skip(amt)
.zip(0..ROWS)
.map(|(i, j)| (i, screen[j][colnr]))
.collect::<ArrayVec<_, ROWS>>()
{
screen[i][colnr] = v;
}
}
"row" => {
let rownr: usize =
a.split('=').last().unwrap().parse().unwrap();
let amt = b.parse().unwrap();
//
for (i, v) in (0..COLS)
.cycle()
.skip(amt)
.zip(0..COLS)
.map(|(i, j)| (i, screen[rownr][j]))
.collect::<ArrayVec<_, COLS>>()
{
screen[rownr][i] = v;
}
}
_ => panic!(),
},
_ => panic!(),
}
}
screen
}
fn part1() {
let ans = get_screen()
.into_iter()
.flat_map(|row| row.into_iter())
.filter(|&x| x)
.count();
//
println!("{}", ans);
}
fn part2() {
render_screen(&get_screen());
}
| true |
e385f5384a86d80c951d3f9bf5f73167ab3f3457
|
Rust
|
seppaleinen/hellorust
|
/src/main.rs
|
UTF-8
| 230 | 2.625 | 3 |
[] |
no_license
|
extern crate module;
///# Main
///1. Does nothing.
///2. Continue doing nothing.
///3. Print hello world
#[cfg(not(test))]
fn main() {
let result = module::yo("Hello".to_string());
println!("Hello, world! {:?}", result);
}
| true |
e41c258a96a02c28e2ee68772b3f4d8243cf6258
|
Rust
|
dante-signal31/test_common
|
/src/random/strings.rs
|
UTF-8
| 919 | 3.90625 | 4 |
[
"BSD-3-Clause"
] |
permissive
|
/// Random operations with strings.
use rand::prelude::*;
use rand::distributions::Alphanumeric;
/// Generate a random string of desired length.
///
/// # Parameters:
/// * len: Desired character length for generated string.
///
/// # Returns:
/// * Generated random string.
pub fn random_string(len: usize)-> String {
let generated_string: String = rand::thread_rng()
.sample_iter(Alphanumeric)
.take(len)
.collect();
generated_string
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_random_string() {
let desired_length: usize = 7;
let generated_string = random_string(desired_length);
let generated_length = generated_string.len();
assert_eq!(desired_length, generated_length,
"Generated random string has not desired length of {} but {} instead",
desired_length, generated_length);
}
}
| true |
216adfd2eae3a3e799c7446929472bfd4bd51a15
|
Rust
|
bouzuya/rust-atcoder
|
/atcoder-problems-virtual-contests/4aa0347f-2081-47ef-a459-e9ee82768539/src/bin/4.rs
|
UTF-8
| 786 | 3.078125 | 3 |
[] |
no_license
|
use proconio::input;
fn main() {
input! {
n: usize,
}
if n < 357 {
println!("0");
return;
}
let mut cs: Vec<usize> = vec![];
for len in 3..=n.to_string().len() {
let mut curr = vec![3, 5, 7];
for _ in 0..len - 1 {
let mut next = vec![];
for x in curr {
next.push(x * 10 + 3);
next.push(x * 10 + 5);
next.push(x * 10 + 7);
}
curr = next;
}
cs.extend(curr.iter());
}
let mut count = 0;
for c in cs {
let s = c.to_string();
if s.contains('3') && s.contains('5') && s.contains('7') && c <= n {
count += 1;
}
}
let ans = count;
println!("{}", ans);
}
| true |
9a8d7ea958865185d7b9ad47f7e329b492e7014b
|
Rust
|
Orca-bit/DataStructureAndAlgorithm
|
/src/dp/_123_best_time_to_buy_and_sell_stock_3.rs
|
UTF-8
| 873 | 3.59375 | 4 |
[] |
no_license
|
struct Solution;
impl Solution {
pub fn max_profit(prices: Vec<i32>) -> i32 {
let mut first_buy = i32::MIN;
let mut first_sell = 0;
let mut second_buy = i32::MIN;
let mut second_sell = 0;
for price in prices {
first_buy = first_buy.max(-price);
first_sell = first_sell.max(first_buy + price);
second_buy = second_buy.max(first_sell - price);
second_sell = second_sell.max(second_buy + price);
}
second_sell
}
}
#[test]
fn test() {
let prices = vec![3, 3, 5, 0, 0, 3, 1, 4];
let res = 6;
assert_eq!(Solution::max_profit(prices), res);
let prices = vec![1, 2, 3, 4, 5];
let res = 4;
assert_eq!(Solution::max_profit(prices), res);
let prices = vec![7, 6, 4, 3, 1];
let res = 0;
assert_eq!(Solution::max_profit(prices), res);
}
| true |
428d00f93e92320ddace8068730913bf1d72b140
|
Rust
|
Resonious/adventureformer
|
/af/src/assets/mod.rs
|
UTF-8
| 5,356 | 2.53125 | 3 |
[] |
no_license
|
extern crate gl;
extern crate glfw;
use gl::types::*;
use std::mem::{zeroed, size_of, transmute};
use render;
use render::{GLData, ImageAsset, Texcoords};
use std::ffi::CString;
use vecmath::*;
#[macro_use]
mod macros;
image_assets!(
ccbdy crattlecrute_body: SpriteType2Color2 [9][90;90] "assets/crattlecrute/body.png",
ccbft crattlecrute_back_foot: SpriteType2Color2 [9][90;90] "assets/crattlecrute/back-foot.png",
ccfft crattlecrute_front_foot: SpriteType2Color2 [9][90;90] "assets/crattlecrute/front-foot.png",
ceye1 eye_1: SpriteType3Color1 [1][4;5] "assets/eyes/standard-eye.png",
tstsp test_spin: SpriteType3Color1 [9][90;90] "assets/crattlecrute/body.png",
dirt1 dirt_1: SpriteType1 [1][16;16] "assets/terrain/dirt1.png"
);
shader_assets!(
// No rotation or color swapping - just frames and flipping.
SpriteType1:
[vertex]
layout (location = 1) in vec2(Vec2<GLfloat>) position; // in pixels
layout (location = 2) in int(GLint) frame;
layout (location = 3) in int(GLint) flipped; // actually a bool
("
void main()
{
vec2 pixel_screen_pos = (position - cam_pos) * 2.0;
gl_Position = vec4(
(vertex_pos * from_pixel(sprite_size) + from_pixel(pixel_screen_pos)) * scale,
0.0f, 1.0f
);
int index = flipped != 0 ? flipped_vertex_id() : gl_VertexID;
if (frame == -1)
texcoord = TEXCOORD_FROM_ID[index];
else
texcoord = frames[frame * 4 + index];
texcoord.y = 1.0 - texcoord.y;
}
")
[fragment]
("
void main()
{
color = texture(tex, texcoord);
}
")
// Frames, flipping, rotates around center, 2 colors can be swapped.
// Position refers to the center of the sprite.
SpriteType2Color2:
[vertex]
layout (location = 1) in vec2(Vec2<GLfloat>) position; // in pixels
layout (location = 2) in int(GLint) frame;
layout (location = 3) in int(GLint) flipped; // actually a bool
layout (location = 4) in float(GLfloat) angle;
layout (location = 5) in ivec2(Vec2<GLuint>) color_swap_1;
layout (location = 6) in ivec2(Vec2<GLuint>) color_swap_2;
("
out vec4 cswap1_from;
out vec4 cswap1_to;
out vec4 cswap2_from;
out vec4 cswap2_to;
void main()
{
vec2 pixel_screen_pos = (position - cam_pos) * 2.0;
float vert_angle = angle + ANGLE_OFFSETS[gl_VertexID];
vec2 vert = VERT_DIST * vec2(cos(vert_angle), sin(vert_angle));
gl_Position = vec4(
(vert * from_pixel(sprite_size) + from_pixel(pixel_screen_pos)) * scale,
0.0f, 1.0f
);
int index = flipped != 0 ? flipped_vertex_id() : gl_VertexID;
if (frame == -1)
texcoord = TEXCOORD_FROM_ID[index];
else
texcoord = frames[frame * 4 + index];
texcoord.y = 1.0 - texcoord.y;
cswap1_from = color_from(color_swap_1.x);
cswap1_to = color_from(color_swap_1.y);
cswap2_from = color_from(color_swap_2.x);
cswap2_to = color_from(color_swap_2.y);
}
")
[fragment]
("
in vec4 cswap1_from;
in vec4 cswap1_to;
in vec4 cswap2_from;
in vec4 cswap2_to;
void main()
{
color = texture(tex, texcoord);
if (approx(color, cswap1_from, 0.1))
color = cswap1_to;
else if (approx(color, cswap2_from, 0.1))
color = cswap2_to;
}
")
// Rotates around given focal point, 1 color swap.
SpriteType3Color1:
[vertex]
layout (location = 1) in vec2(Vec2<GLfloat>) position; // in pixels
layout (location = 2) in int(GLint) frame;
layout (location = 3) in int(GLint) flipped; // actually a bool
layout (location = 4) in float(GLfloat) angle;
layout (location = 5) in ivec2(Vec2<GLint>) focus; // in pixels
layout (location = 6) in ivec2(Vec2<GLuint>) color_swap;
("
out vec4 cswap_from;
out vec4 cswap_to;
void main()
{
vec2 pixel_screen_pos = (position - cam_pos) * 2.0;
vec2 effective_focus = flipped == 0 ?
vec2(focus) : vec2(sprite_size.x - float(focus.x), focus.y);
vec2 pixel_offset = vertex_pos * sprite_size - effective_focus * 2.0;
float pixel_angle = angle + atan(pixel_offset.y, pixel_offset.x);
vec2 direction = vec2(cos(pixel_angle), sin(pixel_angle));
float distance = sqrt(dot(pixel_offset, pixel_offset));
vec2 vert = from_pixel(distance * direction);
gl_Position = vec4(
(vert + from_pixel(pixel_screen_pos)) * scale,
0.0f, 1.0f
);
int index = flipped != 0 ? flipped_vertex_id() : gl_VertexID;
if (frame == -1)
texcoord = TEXCOORD_FROM_ID[index];
else
texcoord = frames[frame * 4 + index];
texcoord.y = 1.0 - texcoord.y;
cswap_from = color_from(color_swap.x);
cswap_to = color_from(color_swap.y);
}
")
[fragment]
("
in vec4 cswap_from;
in vec4 cswap_to;
void main()
{
color = texture(tex, texcoord);
if (approx(color, cswap_from, 0.1))
color = cswap_to;
}
")
);
| true |
5aa1fc0139b8abffed6af71261e25deef3fed144
|
Rust
|
clpi/dapi
|
/di-db/src/query.rs
|
UTF-8
| 14,596 | 2.6875 | 3 |
[] |
no_license
|
///query.rs
///Construct sqlx queries from a model and parameters of form
use chrono::{DateTime, Utc};
use divc::models::Model;
use sqlx::prelude::*;
use sqlx::postgres::{PgPool, PgConnection, PgDone};
use std::boxed::Box;
use divc::models::{User, Record, Item};
use serde::{Serialize, Deserialize};
//TODO let's try this another time perhaps...
//pub trait SQLQuery {}
//#[derive(Deserialize, Serialize)]
//pub struct SelectQuery where {
//pool: PgPool,
//alias: Option<String>,
//with: Vec<SelectQuery>,
//select: Vec<SelectClause>,
//#[serde(flatten)]
//from: Vec<FromClause>,
//cond: Vec<WhereClause>,
//group_by: Vec<SelectField>,
//having: Vec<Condition>,
//order_by: Vec<Order>,
//bind: Vec<String>,
//}
//#[derive(Deserialize, Serialize)]
//pub struct UpdateQuery where {
//pool: PgPool,
//update: Vec<SelectField>,
//set: Vec<SelectField>,
//cond: Vec<Condition>,
//query_string: String,
//}
//pub struct DeleteQuery where {
//pool: PgPool,
//delete: Vec<SelectField>,
//cond: Vec<Condition>,
//bind: Option<Vec<String>>,
//query_string: String,
//}
//impl SelectQuery {
//pub fn new(pool: PgPool, alias: Option<String>) -> Self {
//Self { pool, alias, ..Vec::new() }
//}
//pub fn from<T: Queryable>(mut self, model: T, alias: Option<String>) -> Self {
//let table = model.table();
//let from = FromClause::from_table(model.table());
//self.from.push(from);
//}
//pub fn select(mut self, table: String, column: &str, alias: Option<String>) -> Self {
//if self.get_tables().contains(model.table()) {
//let select = if Some(alias) {
//SelectClause::from_column(column.to_string(), alias);
//} else {
//SelectClause::from_column(column.to_string())
//};
//self.select.push(select);
//} else {
//println!("Field not found in any tables") ;
//}
//self
//}
//pub fn get_tables(self) -> Vec<String> {
//let tables: Vec<String> = self.from.into_iter()
//.map(|clause| Some(clause.table))
//.collect().into();
//tables
//}
//pub fn get_columns(self) -> Vec<String> {
//let cols: Vec<String> = self.select.into_iter()
//.map(|clause| Some(clause.column))
//.collect().into();
//cols
//}
//pub fn get_conditions(self) -> Vec<String> {
//let cond: Vec<String> = self.cond.into_iter()
//.map(|claues| Some(clause.fields))
//.collect().into();
//cols
//}
//pub fn select_all(mut self, modif: Option<SelectModifier>) -> Self {
//let field = SelectField::Wildcard(Wildcard::All);
//let modifier = match self.select.len() {
//0 => SelectModifier::Beginning,
//_ => modif.unwrap()
//};
//let sel_claus = SelectClause { modifier, table: None, column: None, alias: None };
//self.select.push(sel_claus);
//self
//}
//pub fn from<T: Queryable>(mut self, model: T) -> FromClause {
//let from_clause = FromClause { table: FromField::Table(model.table()), alias: None };
//from_clause
//}
//pub fn with(mut self, column: String, table: Option<Table>) -> WhereClause {
//let clause = match self.get_tables().len() {
//0 => WhereClause::new(),
//1 => {
//let table: String = self.get_tables().get(0);
//WhereClause::new().
//}
//}
//if self.cond.len() > 0 {
//let mut where_clause = WhereClause::from_modifier(self, WhereModifier::And);
//move |where_clause| {
//where_clause.with_column(column)
//}
//} else { WhereClause::new(self) }
//}
//pub fn and_where(mut self, column: Column) -> WhereClause {
//if self.cond.len() > 0 {
//let mut where_clause = WhereClause::from_modifier(self, WhereModifier::And);
//move |where_clause| {
//where_clause.with_column(column)
//}
//} else { WhereClause::new(self) }
//}
//pub fn and_not_where(mut self, column: Column) -> WhereClause {
//let mut where_clause = WhereClause::from_modifier(self, WhereModifier::Not);
//move |where_clause| {
//where_clause.with_column(column)
//}
//}
//pub fn or_where(self, column: Column) -> WhereClause {
//let mut where_clause = WhereClause::from_modifier(self, WhereModifier::Or);
//move |where_clause| {
//where_clause.with_column(column)
//}
//}
//pub fn where_modifier(self, modifier: WhereModifier) -> WhereClause {
//match self.cond.len() {
//0 => WhereClause::new(),
//_ => WhereClause::with_modifier(modifier),
//}
//}
//pub async fn query_as<T: Queryable>(mut self) -> sqlx::Result<T> {
//let mut query_str = String::from("SELECT ");
//self.get_columns().into_iter()
//.map(|col: String| {
//query_str.extend_one(col);
//query_str.push_str(", ");
//});
//query_str.strip_suffix(", ");
//query_str.push_str(" FROM ");
//self.get_tables().into_iter()
//.map(|table: String| {
//query_str.extend_one(table);
//query_str.push_str(", ");
//});
//query_str.strip_suffix(", ");
//query_str.push_str(" WHERE ");
////self.get_conditions().into_iter()
//let query = sqlx::query_as::<_, T>("SELECT $1 FROM $2 WHERE $3");
//self.bind.into_iter().map(*query.bind());
//let res = self.pool.execute(query).await?;
//Ok
//}
//}
//pub enum Existential {
//Exists(Column, SelectQuery),
//In(Column, SelectQuery),
//Between(Column, SelectQuery),
//Union(Column, SelectQuery),
//Except(Column, SelectQuery),
//Intercept(Column, SelectQuery),
//}
//pub enum TableField {
//Table(Table),
//Query(SelectQuery),
//Column(Column),
//}
//pub struct SelectClause {
//modifier: Option<SelectModifier>,
//table: Option<Table>,
//column: Option<Column>,
//alias: Option<String>,
//}
//impl SelectClause {
//pub fn from_model<T: Queryable>(model: T, alias: Option<String>, modifier: Option<SelectModifier>) {
//Self { modifier, table: model.table(), column: None, alias: None }
//}
//pub fn from_column(table: String, column: String, alias: Option<String>, modifier: Option<SelectModifier>) {
//Self { modifier, table: model.table(), column: String, alias: None }
//}
//}
//pub struct FromClause {
//table: FromField,
//alias: String,
//}
//pub struct WhereClause {
//modifier: Option<WhereModifier>,
//condition: Option<Condition>,
//column: Option<Column>,
//target: Option<WhereField>,
//query: Box<dyn SQLQuery>,
//}
//impl WhereClause {
//pub fn new(
//query: impl SQLQuery,
//modifier: Option<WhereModifier>,
//condition: Option<Condition>,
//column: Option<Column>,
//target: Option<WhereField>
//) -> Self {
//Self {
//query: Box::new(query),
//modifier: WhereModifier::Beginning,
//condition: if Some(condition) { condition } else { None },
//column: if Some(column) { column } else { None },
//target: if Some(target) { target } else { None },
//}
//}
//pub fn or(mut self, modif: WhereModifier) -> WhereClause{
//let new = Self {
//modifier: WhereModifier::Or, ..Self::new()
//};
//new
//}
//pub fn and(mut self, modif: WhereModifier) -> WhereClause{
//self.from_modifier(self.query, WhereModifier::And)
//}
//pub fn and_not(mut self, modif: WhereModifier) -> WhereClause{
//self.from_modifier(self.query, WhereModifier::AndNot)
//}
//pub fn from_modifier(query: impl SQLQuery, modifier: WhereModifier) {
//WhereClause {
//query: Box::new(query), modifier, ..Self::new()
//}
//}
//pub fn from_column(query: impl SQLQuery, column: Column) {
//WhereClause {
//query: Box::new(query), column: Some(column), ..Self::new()
//}
//}
//pub fn with_column(mut self, col: String, table: Option<String>) {
//self.column = Some(Column { col, table });
//self
//}
//pub fn equals_val<T: SQLPrimitive>(mut self, value: Option<T>, field: Option<T>) -> Self {
//self.condition = Condition::Equals(value);
//if let val = Some(value).to_sql_value() {
//self.target = WhereField::Primitive(val);
//} else {
//if let col = Some(field) {
//self.target = WhereField::Column(col);
//}
//}
//self
//}
//pub fn equals<T>(mut self, value: Option<T>, field: Option<T>) -> Self {
//self.condition = Condition::Equals(value);
//if let col = Some(field) {
//self.target = WhereField::Column(col);
//}
//self
//}
//pub fn does_not_equal<T: SQLPrimitive>(mut self, value: Option<T>, field: Option<Column>) -> Self {
//self.condition = Condition::DoesNotEquals(value);
//if let val = SSome(value).to_sql_value() {
//self.target = WhereField::Primitive(value.to_sql_value());
//} else {
//if let col = Some(field) {
//self.target = WhereField::Column(col);
//}
//}
//}
//pub fn with_modifier(mut self, modifier: WhereModifier) {
//self.modifier = modifier; self
//}
//pub fn with_olumn(mut self, column: Column) {
//self.column = column; self
//}
//}
//pub enum SelectModifier {
//Top,
//Distinct,
//}
//pub enum WhereModifier {
//Beginning,
//And,
//Or,
//AndNot,
//}
//pub enum Condition {
//Equals,
//LessThan,
//GreaterThan,
//EqualLessThan,
//EqualGreaterThan,
//DoesNotEqual,
//Like(Column, String),
//Similar(Column, String),
//IsNull(Column),
//IsNotNull(Column),
//Existential(Existential),
//}
//pub enum SQLGroupBy {
//}
//pub enum Order {
//Ascending(FromField),
//Descending(FromField),
//}
//pub enum SelectField {
//Wildcard(Wildcard),
//Column(Column),
//Query(SelectQuery),
//Aggregate { col: Column, aggregate: Aggregate },
//}
//pub enum WhereField {
//Column(Column),
//Date(DateTime<Utc>),
//Primitive(SQLValue),
//Bind(Bind),
//}
//pub enum Bind {
//BindInt(i32),
//BindString(String),
//BindBool(bool),
//BindDt(DateTime<Utc>),
//}
//#[derive(Debug, Serialize, Deserialize)]
//pub enum FromField {
//Table(Table),
//Column(Column),
//Query(SelectQuery),
//}
//pub enum Wildcard {
//All,
//OnePlus,
//ZeroOrOne,
//NonGreedyOnePlus,
//NonGreedyZeroPlus,
//NonGreedyZeroOrOne,
//Atomic { m: String },
//AtomimcM { m: String },
//AtomimcMToN { m: String, n: String },
//NGAtomic { m: String },
//NGAtomimcM { m: String },
//NGAtomimcMToN { m: String, m: String },
//}
//pub enum Aggregate {
//Avg(Column),
//Count(Column),
//Max(Column),
//Min(Column),
//StdDev(Column),
//Sum(Column),
//Variance(Column),
//Every(Column),
//Regr_R2(Column, Column),
//Corr(Column, Column),
//}
//pub enum SQLValue {
//Int(i32),
//Text(String),
//Timestamptz(DateTime<Utc>),
//Boolean(bool),
//Null,
//}
//pub trait SQLPrimitive {
//fn to_sql_value(self) -> SQLValue;
//}
//impl SQLPrimitive for i32 {
//fn to_sql_value(self) -> SQLValue { SQLValue::Int(self) }
//}
//impl SQLPrimitive for String {
//fn to_sql_value(self) -> SQLValue { SQLValue::String(self) }
//}
//impl SQLPrimitive for bool {
//fn to_sql_value(self) -> SQLValue { SQLValue::Boolean(self) }
//}
//pub struct Table(String);
//pub struct Column { table: Option<Table>, col: String }
//impl From<&dyn Model> for Table {
//fn from(model: &dyn Model) -> Self {
//Self(model.table())
//}
//}
//impl Column {
//pub fn new(col: String) -> Self { Self { table: None, col} }
//pub fn to_dot_string(self) -> String {
//format!("{:?}.{}", Some(self.table), col)
//}
//}
//pub struct Having {
//cond: Column,
//cond: Condition,
//field: Field,
//}
//pub enum Join {
//CrossJoin(Table, Table),
//InnerJoin(Table, Table),
//LeftOuterJoin(Table, Table),
//RightOuterJoin(Table, Table),
//FullOuterJoin(Table, Table),
//}
//pub trait Queryable: Model {
//fn table(self) -> String {
//match self {
//User => { String::from("Users") },
//Record => { String::from("Record") },
//_ => { String::from("") },
//}
//}
//fn id() -> i32 { 0 }
//}
//impl<T: Model> Queryable for T {
//}
//impl<T: Queryable> DbQuery<T> {
//pub async fn new(pool: PgPool) -> () {
//}
//pub async fn from(pool: PgPool, model: T) -> () {
//}
//pub async fn execute(self) -> sqlx::Result<u32> {
//let que = sqlx::query("");
//let res = que.execute(&self.pool).await?;
//Ok(res.rows_affected() as u32)
//}
//}
//impl DbQuery<User> {
//}
//impl DbQuery<Record> {
//}
//impl DbQuery<Item> {
//}
//impl DbQuery<Group> {
//}
//#[cfg(test)]
//mod tests {
//use super::*;
//#[test]
//fn can_add_from_clause() {
//let pool = crate::Db::new().await.unwrap();
//let user = User::new("test".to_string(), "test".to_string(), "test".to_string());
//let query = SelectQuery::new(pool)
//.from(user)
//.select(user.table(), "username")
//.with(|self| {
//WhereClause::new(self)
//.with_column("id")
//.equals("Records", "uid")
//.and_not()
//.with_column("")
//})
//}
//#[test]
//fn query_str_is_correct() {
//}
//#[test]
//fn table_from_model_works() {
//let user = User::new("test@test.com", "test", "pass");
//let user_table = user.table();
//let table: Table = Table::from(user);
//assert_eq!(user_table table)
//}
//}
| true |
2497b3ba673e85eb488fc77e4390d83911f489b3
|
Rust
|
jsdelivrbot/euler_criterion.rs
|
/src/language.rs
|
UTF-8
| 3,186 | 2.765625 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::fs::{File, PathExt, self};
use std::io::{Read, Write};
use std::path::Path;
use rustc_serialize::json;
use compiler::Compiler;
use interpreter::Interpreter;
#[derive(RustcDecodable)]
pub struct Language {
compiler: Option<Compiler>,
extension: String,
interpreter: Option<Interpreter>,
name: String,
}
impl Language {
pub fn compiler(&self) -> Option<&Compiler> {
self.compiler.as_ref()
}
pub fn extension(&self) -> &str {
self.extension.as_slice()
}
pub fn interpreter(&self) -> Option<&Interpreter> {
self.interpreter.as_ref()
}
pub fn name(&self) -> &str {
self.name.as_slice()
}
}
pub fn all() -> Vec<Language> {
let version_dir = Path::new("versions");
fs::create_dir_all(version_dir).ok().
expect("Couldn't create the versions directory");
fs::read_dir(&Path::new("languages")).
ok().
expect("languages directory not found").
map(|entry| entry.unwrap().path()).
filter(|file| file.is_file()).
map(|file| {
let file_ = file.display();
let mut string = String::new();
match File::open(&file).and_then(|mut f| f.read_to_string(&mut string)) {
Err(e) => panic!("`{}`: {}", file_, e),
Ok(_) => match json::decode::<Language>(string.as_slice()) {
Err(e) => panic!("`{}`: {}", file_, e),
Ok(mut language) => {
info!("Found {}", language.name);
match language.compiler {
Some(ref mut compiler) => {
compiler.fetch_version();
File::create(&version_dir.join(compiler.command())).
and_then(|mut f| {
f.write_all(compiler.version().as_bytes())
}).
ok().
expect("Couldn't write to versions directory");
},
None => {},
}
match language.interpreter {
Some(ref mut interpreter) => {
interpreter.fetch_version();
File::create(&version_dir.join(interpreter.command())).
and_then(|mut f| {
f.write_all(interpreter.version().as_bytes())
}).
ok().
expect("Couldn't write to versions directory");
},
None => {},
}
if language.compiler.is_none() && language.interpreter.is_none() {
panic!("{}: No compiler and no interpreter found", language.name)
}
language
},
}
}
}).
collect()
}
| true |
2002cdf5b09c5fc010e4e9fe917c9bce60c81d4a
|
Rust
|
imawhale/blog
|
/src/slug.rs
|
UTF-8
| 1,505 | 3.484375 | 3 |
[] |
no_license
|
use crate::common::*;
#[derive(Debug, Clone)]
pub(crate) struct Slug {
text: String,
}
impl Slug {
pub(crate) fn from_text(text: String) -> Result<Slug, Error> {
let mut dash = false;
for (i, c) in text.chars().enumerate() {
if c.is_ascii_lowercase() {
dash = false;
} else if c == '-' {
if i == 0 || dash {
return Err(Error::Slug { text });
}
dash = true;
} else {
return Err(Error::Slug { text });
}
}
if dash {
Err(Error::Slug { text })
} else {
Ok(Slug { text })
}
}
pub(crate) fn text(&self) -> &str {
&self.text
}
}
impl<S: AsRef<str>> PartialEq<S> for Slug {
fn eq(&self, s: &S) -> bool {
s.as_ref() == self.text
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn number() {
assert!(Slug::from_text("0".to_string()).is_err());
}
#[test]
fn uppercase() {
assert!(Slug::from_text("A".to_string()).is_err());
}
#[test]
fn double_dash() {
assert!(Slug::from_text("a--b".to_string()).is_err());
}
#[test]
fn trailing_dash() {
assert!(Slug::from_text("a-".to_string()).is_err());
}
#[test]
fn leading_dash() {
assert!(Slug::from_text("-a".to_string()).is_err());
}
#[test]
fn lowercase() -> Result<(), Error> {
Slug::from_text("abcdefghijklmnopqrstuvwxyz".to_string())?;
Ok(())
}
#[test]
fn dashes() -> Result<(), Error> {
Slug::from_text("a-b-c-d".to_string())?;
Ok(())
}
}
| true |
e2df7a4af5ada78577572bea836a18ec4295c4d1
|
Rust
|
hawkingrei/hackerrank
|
/rust/compare-the-triplets/src/main.rs
|
UTF-8
| 728 | 3.40625 | 3 |
[] |
no_license
|
use std::io;
fn get_input() -> String {
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed");
buffer
}
fn main() {
let numbersA: Vec<i32> = get_input().split_whitespace()
.map(|x| x.parse::<i32>().expect("parse error"))
.collect::<Vec<i32>>();
let numbersB: Vec<i32> = get_input().split_whitespace()
.map(|x| x.parse::<i32>().expect("parse error"))
.collect::<Vec<i32>>();
let mut totalA = 0;
let mut totalB = 0;
for index in 0..3{
if (numbersA[index] > numbersB[index]) {
totalA = totalA + 1;
}
if (numbersA[index] < numbersB[index]) {
totalB = totalB + 1;
}
}
println!("{} {}",totalA,totalB)
}
| true |
e76ab9beb8baa73781629797a35b3269fe6dbaec
|
Rust
|
AD1024/cdcl-rust
|
/src/clause.rs
|
UTF-8
| 3,331 | 2.984375 | 3 |
[] |
no_license
|
use crate::clause::AST::*;
use std::fmt::{Debug, Formatter, Display};
#[derive(Clone)]
#[derive(Debug)]
pub enum AST {
Var(String),
Not(BoxAST),
And(BoxAST, BoxAST),
Or(BoxAST, BoxAST),
Implies(BoxAST, BoxAST),
Iff(BoxAST, BoxAST)
}
type BoxAST = Box<AST>;
pub struct VariableStore {
count : i32
}
impl VariableStore {
pub fn new() -> Self {
VariableStore { count: 0 }
}
fn next_variable(&mut self) -> String {
let result = format!("$x_{}", self.count);
self.count += 1;
result
}
}
pub fn tseytin_transform(expr : &AST, store : &mut VariableStore) -> Vec<AST> {
match expr {
Var(_) => Vec::new(),
Not(e) => {
let new_var = store.next_variable();
let mut result =
vec![Iff(Box::new(Var(new_var)), Box::new((*expr).clone()))];
if let Var(_) = **e {
result
} else {
result.append(&mut tseytin_transform(e, store));
result
}
},
Or(e1, e2) |
Iff(e1, e2) |
Implies(e1, e2) |
And(e1, e2) => {
let new_var = store.next_variable();
let mut result =
vec![Iff(Box::new(Var(new_var)), Box::new((*expr).clone()))];
result.append(&mut tseytin_transform(e1.as_ref(), store));
result.append(&mut tseytin_transform(e2.as_ref(), store));
result
}
}
}
pub fn push_neg(expr : &AST) -> AST {
let f = |e : &BoxAST| Box::new(push_neg(e.as_ref()));
match expr {
Not(e) => {
match *(e.to_owned()) {
And(e1, e2) =>
Or(
Box::new(push_neg(&Not(e1))),
Box::new(push_neg(&Not(e2)))
),
Or(e1, e2) =>
And(
Box::new(push_neg(&Not(e1))),
Box::new(push_neg(&Not(e2)))
),
_ => panic!("{:#?} should not be here!", e)
}
},
And(e1, e2) => And(f(e1), f(e2)),
Or(e1, e2) => Or(f(e1), f(e2)),
_ => panic!("{:#?} should not be here!", expr)
}
}
pub fn to_cnf(expr : &AST) -> AST {
let f = |e : &BoxAST| Box::new(to_cnf(e.as_ref()));
match expr {
Var(_) => expr.clone(),
Not(e) => AST::Not(f(e)),
And(e1, e2) => And(f(e1), f(e2)),
Or(e1, e2) => Or(f(e1), f(e2)),
Implies(e1, e2) => Or(Box::new(Not(f(e1))), f(e2)),
Iff(e1, e2) =>
And(
Box::new(to_cnf(&(Implies(e1.clone(), e2.clone())))),
Box::new(to_cnf(&(Implies(e2.clone(), e1.clone())))))
}
}
pub fn vec_to_cnf(exprs : &Vec<AST>) -> Vec<AST> {
exprs.iter().map(to_cnf).collect()
}
pub fn break_and(exprs : &Vec<AST>) -> Vec<AST> {
let mut result : Vec<AST> = Vec::new();
for formula in exprs.iter() {
match formula.to_owned() {
AST::And(e1, e2) => {
result.push(*e1);
result.push(*e2);
},
_ => result.push(formula.to_owned())
}
}
result
}
| true |
27bcd6e8a24d5a1054bfeb383841de609c661cd2
|
Rust
|
blofroth/border
|
/border-tch-agent/src/util.rs
|
UTF-8
| 3,116 | 2.78125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! Utilities.
use crate::model::ModelBase;
use log::trace;
use serde::{Deserialize, Serialize};
mod mlp;
mod quantile_loss;
pub use mlp::{create_actor, create_critic, MLPConfig, MLP, MLP2};
pub use quantile_loss::quantile_huber_loss;
/// Interval between optimization steps.
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
pub enum OptInterval {
/// Optimization interval specified as interaction steps.
Steps(usize),
/// Optimization interval specified as episodes.
Episodes(usize),
}
impl OptInterval {
/// Constructs the counter for optimization.
pub fn counter(self) -> OptIntervalCounter {
OptIntervalCounter {
opt_interval: self,
count: 0,
}
}
}
/// The counter for optimization.
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
pub struct OptIntervalCounter {
opt_interval: OptInterval,
count: usize,
}
impl OptIntervalCounter {
/// Returns true if the optimization should be done.
pub fn do_optimize(&mut self, is_done: &[i8]) -> bool {
let is_done_any = is_done.iter().fold(0, |x, v| x + *v as i32) > 0;
match self.opt_interval {
OptInterval::Steps(interval) => {
self.count += 1;
if self.count == interval {
self.count = 0;
true
} else {
false
}
}
OptInterval::Episodes(interval) => {
if is_done_any {
self.count += 1;
if self.count == interval {
self.count = 0;
true
} else {
false
}
} else {
false
}
}
}
}
}
/// Critic loss type.
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
pub enum CriticLoss {
/// Mean squared error.
MSE,
/// Smooth L1 loss.
SmoothL1,
}
/// Apply soft update on a model.
///
/// Variables are identified by their names.
pub fn track<M: ModelBase>(dest: &mut M, src: &mut M, tau: f64) {
let src = &mut src.get_var_store().variables();
let dest = &mut dest.get_var_store().variables();
debug_assert_eq!(src.len(), dest.len());
let names = src.keys();
tch::no_grad(|| {
for name in names {
let src = src.get(name).unwrap();
let dest = dest.get_mut(name).unwrap();
dest.copy_(&(tau * src + (1.0 - tau) * &*dest));
}
});
trace!("soft update");
}
/// Concatenates slices.
pub fn concat_slices(s1: &[i64], s2: &[i64]) -> Vec<i64> {
let mut v = Vec::from(s1);
v.append(&mut Vec::from(s2));
v
}
/// Returns the dimension of output vectors, i.e., the number of discrete outputs.
pub trait OutDim {
/// Returns the dimension of output vectors, i.e., the number of discrete outputs.
fn get_out_dim(&self) -> i64;
/// Sets the output dimension.
fn set_out_dim(&mut self, v: i64);
}
| true |
23849d7abeeb24242e355592b29def7605b5314a
|
Rust
|
Rexagon/vrs
|
/src/rendering/validation.rs
|
UTF-8
| 4,373 | 2.546875 | 3 |
[] |
no_license
|
use super::prelude::*;
use super::Instance;
pub struct Validation {
is_enabled: bool,
debug_utils_ext: ash::extensions::ext::DebugUtils,
debug_utils_messenger: vk::DebugUtilsMessengerEXT,
}
impl Validation {
pub fn new(entry: &ash::Entry, instance: &Instance, is_enabled: bool) -> Result<Self> {
let debug_utils_ext = ash::extensions::ext::DebugUtils::new(entry, instance.handle());
let debug_utils_messenger = if is_enabled {
let debug_utils_messenger =
unsafe { debug_utils_ext.create_debug_utils_messenger(&debug_messenger_create_info(), None)? };
log::debug!("created debug utils messenger: {:?}", debug_utils_messenger);
debug_utils_messenger
} else {
vk::DebugUtilsMessengerEXT::null()
};
Ok(Self {
is_enabled,
debug_utils_ext,
debug_utils_messenger,
})
}
pub unsafe fn destroy(&self) {
if self.is_enabled {
self.debug_utils_ext
.destroy_debug_utils_messenger(self.debug_utils_messenger, None);
log::debug!("dropped debug utils messenger");
}
}
#[allow(unused)]
#[inline]
pub fn is_enabled(&self) -> bool {
self.is_enabled
}
#[allow(unused)]
#[inline]
pub fn ext(&self) -> &ash::extensions::ext::DebugUtils {
&self.debug_utils_ext
}
}
pub fn check_supported(entry: &ash::Entry) -> Result<()> {
let layer_properties = entry.enumerate_instance_layer_properties()?;
if layer_properties.is_empty() {
return Err(Error::msg("no available layers found"));
}
for required_layer_name in required_layers().iter() {
let mut is_layer_found = false;
for layer_property in layer_properties.iter() {
let layer_name = unsafe { CStr::from_ptr(layer_property.layer_name.as_ptr()) };
if required_layer_name.as_c_str() == layer_name {
is_layer_found = true;
break;
}
}
if !is_layer_found {
return Err(Error::msg(format!(
"required layer {:?} was not found",
required_layer_name
)));
}
}
Ok(())
}
pub fn debug_messenger_create_info() -> vk::DebugUtilsMessengerCreateInfoEXT {
vk::DebugUtilsMessengerCreateInfoEXT::builder()
.message_severity(
vk::DebugUtilsMessageSeverityFlagsEXT::WARNING
| vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE
| vk::DebugUtilsMessageSeverityFlagsEXT::INFO
| vk::DebugUtilsMessageSeverityFlagsEXT::ERROR,
)
.message_type(
vk::DebugUtilsMessageTypeFlagsEXT::GENERAL
| vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE
| vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION,
)
.pfn_user_callback(Some(vulkan_debug_utils_callback))
.build()
}
pub fn required_layers() -> &'static [CString] {
REQUIRED_LAYERS.get_or_init(|| vec![CString::new("VK_LAYER_KHRONOS_validation").unwrap()])
}
unsafe extern "system" fn vulkan_debug_utils_callback(
message_severity: vk::DebugUtilsMessageSeverityFlagsEXT,
message_type: vk::DebugUtilsMessageTypeFlagsEXT,
p_callback_data: *const vk::DebugUtilsMessengerCallbackDataEXT,
_p_user_data: *mut c_void,
) -> vk::Bool32 {
let message_type = match message_type {
vk::DebugUtilsMessageTypeFlagsEXT::GENERAL => "[GENERAL]",
vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE => "[PERFORMANCE]",
vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION => "[VALIDATION]",
_ => "[UNKNOWN]",
};
let message = CStr::from_ptr((*p_callback_data).p_message);
match message_severity {
vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE => log::debug!("{} {:?}", message_type, message),
vk::DebugUtilsMessageSeverityFlagsEXT::WARNING => log::warn!("{} {:?}", message_type, message),
vk::DebugUtilsMessageSeverityFlagsEXT::ERROR => log::warn!("{} {:?}", message_type, message),
vk::DebugUtilsMessageSeverityFlagsEXT::INFO => log::info!("{} {:?}", message_type, message),
_ => log::trace!("{} {:?}", message_type, message),
}
vk::FALSE
}
static REQUIRED_LAYERS: OnceCell<Vec<CString>> = OnceCell::new();
| true |
7814edf0f1ec7d440c5a32b8f60f4501b14cb946
|
Rust
|
jgdavey/advent_of_code_2020
|
/aoc09/src/main.rs
|
UTF-8
| 1,288 | 3.3125 | 3 |
[] |
no_license
|
use std::cmp::Ordering;
fn main() {
let input = std::fs::read_to_string("input.txt").unwrap();
let numbers: Vec<_> = input.lines().map(|s| s.parse::<isize>().unwrap()).collect();
let (idx, target) = numbers.iter().enumerate().skip(25).find(|&(i, target)| {
let previous = &numbers[(i - 25)..i];
let mut okay = false;
for (j, num) in previous.iter().enumerate() {
let difference = target - num;
if let Some(_) = previous[j+1..].iter().find(|&n| *n == difference) {
okay = true;
break;
}
}
!okay
}).unwrap();
println!("Target: {:?}", target);
for i in 0..idx {
let mut sum = 0;
for (j, num) in numbers[i..idx].iter().enumerate() {
sum += num;
match target.cmp(&sum) {
Ordering::Equal => {
let slice = &numbers[i..=(j+i)];
let min = slice.iter().min().unwrap();
let max = slice.iter().max().unwrap();
println!("Found: {} + {} = {}", min, max, min + max);
return;
},
Ordering::Less => break,
Ordering::Greater => continue
}
}
}
}
| true |
6c5d3650f46b309b31fd64f1f3041641554fd922
|
Rust
|
ldfdev/Exercises-from-the-book-Beginning-Rust-From-Novice-To-Expert
|
/Chapter 16/iterating_over_chars_in_str.rs
|
UTF-8
| 504 | 3.640625 | 4 |
[] |
no_license
|
fn display_by_iterating(slice: &str) {
// iterators for str type are accessed via chars() function
let mut iter = slice.chars();
loop {
match iter.next() {
Some(value) => {
print!("Curent value {}. Remaining {}\n", value, iter.as_str());
},
None => {
println!("");
break;
}
}
}
}
fn main() {
let words = "galactic sunset";
display_by_iterating(&words);
}
| true |
a024e2bda77d53a7434424bd7688fb42e174248e
|
Rust
|
k0nserv/advent-of-code-2017
|
/src/day13.rs
|
UTF-8
| 3,497 | 3.375 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use std::ops::Range;
#[derive(Debug)]
struct State {
levels: HashMap<u32, u32>,
scanner_locations: HashMap<u32, (u32, i32)>,
packect_location: i32,
severity: u32,
final_location: u32,
}
impl State {
fn parse(input: &str) -> Self {
let levels = input
.trim()
.lines()
.map(|line| {
let parts = line.trim().split(':').collect::<Vec<_>>();
(
parts[0].parse::<u32>().unwrap(),
parts[1].trim().parse::<u32>().unwrap(),
)
}).collect::<HashMap<_, _>>();
let scanner_locations = levels
.keys()
.map(|level| (*level, (0, 1)))
.collect::<HashMap<_, _>>();
let final_location: u32 = *levels.keys().max().unwrap_or(&0);
State {
levels,
scanner_locations,
packect_location: -1,
severity: 0,
final_location,
}
}
fn advance(&mut self) {
self.packect_location += 1;
let packect_location = self.packect_location as u32;
if let Some(location) = self.scanner_locations.get(&packect_location) {
if location.0 == 0 {
self.severity +=
packect_location * *self.levels.get(&packect_location).unwrap_or(&0);
}
}
for (level, range) in &self.levels {
let &(current_location, next_step) = self.scanner_locations.get(level).unwrap();
let new_location = ((current_location as i32) + next_step) as u32;
let new_next_step = if new_location == range - 1 || new_location == 0 {
-next_step
} else {
next_step
};
self.scanner_locations
.insert(*level, (new_location, new_next_step));
}
}
fn is_clear(delay: u32, range: u32) -> bool {
delay % ((range - 1) * 2) != 0
}
fn clear_with_delay(&self, delay: u32) -> bool {
self.levels
.iter()
.all(|(&level, &range)| Self::is_clear(delay + level, range))
}
fn at_end(&self) -> bool {
(self.packect_location as u32) == self.final_location
}
}
struct Counter {
value: u32,
}
impl Counter {
fn new(start_value: u32) -> Self {
Counter { value: start_value }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
let value = self.value;
self.value += 1;
Some(value)
}
}
pub fn solve(input: &str) -> u32 {
let mut state = State::parse(input);
while !state.at_end() {
state.advance();
}
state.severity
}
pub fn solve2(input: &str) -> u32 {
let mut state = State::parse(input);
let mut severity = 1;
let mut delay = 10;
Counter::new(10)
.find(|&value| state.clear_with_delay(value))
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::{solve, solve2};
#[test]
fn test_cases_star_one() {
let input = "
0: 3
1: 2
4: 4
6: 4
";
assert_eq!(solve(&input), 24);
}
#[test]
fn test_cases_star_two() {
let input = "
0: 3
1: 2
4: 4
6: 4
";
assert_eq!(solve2(&input), 10);
}
}
| true |
b73785dc8216ba23145b899f7d6da6d67d2d41fa
|
Rust
|
tykel/retrogram
|
/src/platform/gb.rs
|
UTF-8
| 11,019 | 2.71875 | 3 |
[] |
no_license
|
//! Platform implementation for Game Boy and it's attendant memory mapper chips
use std::io;
use crate::{reg, memory};
use crate::reg::New;
use crate::arch::sm83;
/// Any type which decodes the banked memory region (0x4000) of a Game Boy ROM
/// image.
trait Mapper {
fn decode_banked_addr(&self, ptr: &memory::Pointer<sm83::Pointer>) -> Option<usize>;
}
/// Mapper type which does not support banking.
///
/// This supports Game Boy games up to a maximum of 32KB.
struct LinearMapper {
}
impl LinearMapper {
fn new() -> Self {
LinearMapper {}
}
}
impl Mapper for LinearMapper {
fn decode_banked_addr(&self, ptr: &memory::Pointer<sm83::Pointer>) -> Option<usize> {
Some((ptr.as_pointer() & 0x3FFF + 0x4000) as usize)
}
}
struct MBC1Mapper {
}
impl MBC1Mapper {
fn new() -> Self {
MBC1Mapper {
}
}
}
impl Mapper for MBC1Mapper {
fn decode_banked_addr(&self, ptr: &memory::Pointer<sm83::Pointer>) -> Option<usize> {
match ptr.get_platform_context("R").into_concrete() {
Some(0x00) => None,
Some(0x20) => None,
Some(0x40) => None,
Some(0x60) => None,
Some(b) => Some(((*ptr.as_pointer() as usize) & 0x3FFF) + (b * 0x4000) as usize),
None => None
}
}
}
struct MBC2Mapper {
}
impl MBC2Mapper {
fn new() -> Self {
MBC2Mapper {
}
}
}
impl Mapper for MBC2Mapper {
fn decode_banked_addr(&self, ptr: &memory::Pointer<sm83::Pointer>) -> Option<usize> {
match ptr.get_platform_context("R").into_concrete() {
Some(b) => Some(((*ptr.as_pointer() as usize) & 0x3FFF) + ((b & 0xF) * 0x4000) as usize),
None => None
}
}
}
struct MBC3Mapper {
}
impl MBC3Mapper {
fn new() -> Self {
MBC3Mapper {
}
}
}
impl Mapper for MBC3Mapper {
fn decode_banked_addr(&self, ptr: &memory::Pointer<sm83::Pointer>) -> Option<usize> {
match ptr.get_platform_context("R").into_concrete() {
Some(b) => Some(((*ptr.as_pointer() as usize) & 0x3FFF) + (b * 0x4000) as usize),
None => None
}
}
}
struct MBC5Mapper {
}
impl MBC5Mapper {
fn new() -> Self {
MBC5Mapper {
}
}
}
impl Mapper for MBC5Mapper {
fn decode_banked_addr(&self, ptr: &memory::Pointer<sm83::Pointer>) -> Option<usize> {
match ptr.get_platform_context("R").into_concrete() {
Some(b) => Some(((*ptr.as_pointer() as usize) & 0x3FFF) + (b * 0x4000) as usize),
None => None
}
}
}
/// A program ROM image for Game Boy software.
///
/// With very few exceptions, all Game Boy ROM images service two memory
/// regions: a `HOME` memory region at `$0000` that is 16KB large, and a banked
/// memory region at `$4000` that is also 16KB large. As a consequence, Game Boy
/// ROM images are composed of 16KB chunks of memory that can mapped in or out
/// depending on a mapper-specific memory scheme.
struct GameBoyROMImage<M> where M: Mapper {
data: Vec<u8>,
mapper: M
}
impl<M> GameBoyROMImage<M> where M: Mapper {
pub fn new<F>(file: &mut F, mapper: M) -> io::Result<Self> where F: io::Read {
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Ok(GameBoyROMImage {
data: data,
mapper: mapper
})
}
}
impl<M> memory::Image for GameBoyROMImage<M> where M: Mapper {
type Pointer = sm83::Pointer;
type Offset = usize;
type Data = sm83::Data;
fn retrieve(&self, offset: Self::Offset, count: Self::Offset) -> Option<&[Self::Data]> {
Some(&self.data[offset as usize..(offset + count) as usize])
}
fn decode_addr(&self, ptr: &memory::Pointer<Self::Pointer>, base: Self::Pointer) -> Option<Self::Offset> {
if base == 0x0000 && *ptr.as_pointer() < 0x4000 {
Some(*ptr.as_pointer() as usize)
} else {
self.mapper.decode_banked_addr(ptr)
}
}
fn minimize_context(&self, ptr: memory::Pointer<Self::Pointer>) -> memory::Pointer<Self::Pointer> {
let my_ctxt = ptr.get_platform_context("R");
let mut stripped_ptr = memory::Pointer::from(ptr.as_pointer().clone());
if *stripped_ptr.as_pointer() > 0x4000 {
stripped_ptr.set_platform_context("R", my_ctxt);
}
stripped_ptr
}
fn insert_user_context(&self, mut ptr: memory::Pointer<Self::Pointer>, ctxts: &[&str]) -> memory::Pointer<Self::Pointer> {
if *ptr.as_pointer() > 0x4000 {
match ctxts.get(0) {
Some(ctxt) => match u64::from_str_radix(ctxt, 16) {
Ok(cval) => ptr.set_platform_context("R", reg::Symbolic::new(cval)),
_ => {}
},
_ => {}
}
}
ptr
}
}
pub enum PlatformVariant {
LinearMapper,
MBC1Mapper,
MBC2Mapper,
MBC3Mapper,
MBC5Mapper,
UnknownMapper,
}
impl Default for PlatformVariant {
fn default() -> Self {
PlatformVariant::UnknownMapper
}
}
pub fn create_context<V>(values: &Vec<V>) -> Option<memory::Pointer<sm83::Pointer>>
where V: Clone + PartialOrd + From<sm83::Pointer>,
sm83::Pointer: From<V>,
u64: From<V> {
let mut context = memory::Pointer::from(sm83::Pointer::from(values[values.len() - 1].clone()));
if values.len() > 1 {
if values[values.len() - 1] >= V::from(0xE000) {
} else if values[values.len() - 1] >= V::from(0xC000) {
context.set_platform_context("W", reg::Symbolic::new(u64::from(values[values.len() - 2].clone())));
} else if values[values.len() - 1] >= V::from(0xA000) {
context.set_platform_context("S", reg::Symbolic::new(u64::from(values[values.len() - 2].clone())));
} else if values[values.len() - 1] >= V::from(0x8000) {
context.set_platform_context("V", reg::Symbolic::new(u64::from(values[values.len() - 2].clone())));
} else if values[values.len() - 1] >= V::from(0x4000) {
context.set_platform_context("R", reg::Symbolic::new(u64::from(values[values.len() - 2].clone())));
}
}
if values.len() > 0 {
Some(context)
} else {
None
}
}
/// Construct a `Memory` corresponding to the execution environment of a given
/// Game Boy ROM image.
///
/// You may optionally specify a `PlatformVariant` to control which MBC behavior
/// is used to analyze the image. If unspecified, the ROM header will be used to
/// determine which MBC was intended to be used alongside this program.
pub fn construct_platform<F>(file: &mut F, mut pv: PlatformVariant) -> io::Result<sm83::Bus> where F: io::Read + io::Seek {
let mut bus = sm83::Bus::new();
pv = match pv {
PlatformVariant::UnknownMapper => {
let orig_pos = file.seek(io::SeekFrom::Current(0))?;
file.seek(io::SeekFrom::Start(0x147))?;
let mut romtype : [u8; 1] = [0];
file.read(&mut romtype)?;
file.seek(io::SeekFrom::Start(orig_pos))?;
match romtype {
[0x00] => PlatformVariant::LinearMapper, //ROM w/o RAM
[0x01] => PlatformVariant::MBC1Mapper, //MBC1 ROM
[0x02] => PlatformVariant::MBC1Mapper, //MBC1 ROM with RAM
[0x03] => PlatformVariant::MBC1Mapper, //MBC1 ROM with persistent RAM
[0x05] => PlatformVariant::MBC2Mapper, //MBC2 ROM; TODO: MBC2 has weird 4-bit SRAM and we should always return symbolic 4-bit values
[0x06] => PlatformVariant::MBC2Mapper, //MBC2 ROM w/ persistence
[0x08] => PlatformVariant::LinearMapper, //ROM with RAM
[0x09] => PlatformVariant::LinearMapper, //ROM with persistent RAM
[0x0B] => PlatformVariant::UnknownMapper, //MMM01, currently not supported
[0x0C] => PlatformVariant::UnknownMapper, //MMM01, currently not supported, with RAM
[0x0D] => PlatformVariant::UnknownMapper, //MMM01, currently not supported, with persistent RAM
[0x0F] => PlatformVariant::MBC3Mapper, //MBC3 with persistent clock
[0x10] => PlatformVariant::MBC3Mapper, //MBC3 with persistent clock and RAM
[0x11] => PlatformVariant::MBC3Mapper, //MBC3 ROM only
[0x12] => PlatformVariant::MBC3Mapper, //MBC3 with RAM
[0x13] => PlatformVariant::MBC3Mapper, //MBC3 with persistent RAM, no clock
[0x19] => PlatformVariant::MBC5Mapper, //MBC5 ROM only
[0x1A] => PlatformVariant::MBC5Mapper, //MBC5 with RAM
[0x1B] => PlatformVariant::MBC5Mapper, //MBC5 with persistent RAM
[0x1C] => PlatformVariant::MBC5Mapper, //MBC5 with rumble motor
[0x1D] => PlatformVariant::MBC5Mapper, //MBC5 with rumble motor and RAM
[0x1E] => PlatformVariant::MBC5Mapper, //MBC5 with rumble motor and persistent RAM
[0x20] => PlatformVariant::UnknownMapper, //MBC6 ROM only
[0x22] => PlatformVariant::UnknownMapper, //MBC7 with tilt sensor, rumble motor, and persistent EEPROM
[0xFC] => PlatformVariant::UnknownMapper, //Game Boy Camera with CCD video sensor
[0xFD] => PlatformVariant::UnknownMapper, //Bandai TAMA5 (capabilities unknown)
[0xFE] => PlatformVariant::UnknownMapper, //HuC3 (capabilities unknown)
[0xFF] => PlatformVariant::UnknownMapper, //HuC1 with cartridge infrared port and persistent RAM
_ => PlatformVariant::UnknownMapper
}
},
e => e
};
match pv {
PlatformVariant::LinearMapper => bus.install_rom_image(0x0000, 0x8000, Box::new(GameBoyROMImage::new(file, LinearMapper::new())?)),
PlatformVariant::MBC1Mapper => bus.install_rom_image(0x0000, 0x8000, Box::new(GameBoyROMImage::new(file, MBC1Mapper::new())?)),
PlatformVariant::MBC2Mapper => bus.install_rom_image(0x0000, 0x8000, Box::new(GameBoyROMImage::new(file, MBC2Mapper::new())?)),
PlatformVariant::MBC3Mapper => bus.install_rom_image(0x0000, 0x8000, Box::new(GameBoyROMImage::new(file, MBC3Mapper::new())?)),
PlatformVariant::MBC5Mapper => bus.install_rom_image(0x0000, 0x8000, Box::new(GameBoyROMImage::new(file, MBC5Mapper::new())?)),
PlatformVariant::UnknownMapper => panic!("Platform variant detection failed! Please manually specify the platform variant.")
}
bus.install_ram(0x8000, 0x2000); //VRAM
bus.install_ram(0xA000, 0x2000); //SRAM (todo: this should be modeled better...)
bus.install_ram(0xC000, 0x2000); //WRAM (todo: bankable WRAM)
bus.install_ram(0xFE00, 0x009F); //OAM
bus.install_io (0xFF00, 0x007F); //IO space
bus.install_ram(0xFF80, 0x007F); //HRAM
bus.install_io (0xFFFF, 0x0001); //Interrupt enable
bus.install_openbus(0xE000, 0x1000); //Echo RAM
Ok(bus)
}
| true |
60471f6bb40332e154588270fa3caa425e45b612
|
Rust
|
house-mouse/my-iot-rs
|
/src/core/thread.rs
|
UTF-8
| 597 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
use crate::prelude::*;
use std::time::Duration;
/// Spawns a service thread which just periodically invokes the `loop_` function.
/// This is a frequently repeated pattern in the services.
pub fn spawn_service_loop<F>(service_id: String, interval: Duration, loop_: F) -> Result
where
F: Fn() -> Result,
F: Send + 'static,
{
thread::Builder::new().name(service_id.clone()).spawn(move || loop {
if let Err(error) = loop_() {
error!("[{}] The iteration has failed: {}", service_id, error.to_string());
}
thread::sleep(interval);
})?;
Ok(())
}
| true |
79bb65e20e9865ad1de416fc70a0bcff79d93919
|
Rust
|
tene/silmaril
|
/src/effect/rainbow.rs
|
UTF-8
| 1,934 | 3.21875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use crate::{Color, Effect, PixelIndexable};
use core::marker::PhantomData;
use palette::Hue;
#[derive(Clone, Copy)]
pub enum Orientation {
Horizontal,
Vertical,
Spiral,
}
impl Orientation {
pub fn next(self) -> Self {
use Orientation::*;
match self {
Horizontal => Vertical,
Vertical => Spiral,
Spiral => Horizontal,
}
}
}
pub struct Rainbow<T: PixelIndexable> {
speed: f32,
step: f32,
orient: Orientation,
_pd: PhantomData<T>,
}
impl<T: PixelIndexable> Rainbow<T> {
pub fn new<F: Into<f32>>(speed: F, step: F) -> Self {
let orient = Orientation::Spiral;
let speed = speed.into();
let step = step.into();
Self {
speed,
step,
orient,
_pd: PhantomData,
}
}
pub fn default() -> Self {
Rainbow::new(10.0, 360.0)
}
}
impl<T: PixelIndexable> Effect<T> for Rainbow<T> {
fn tick(&mut self, color: &mut Color) {
*color = color.shift_hue(self.speed);
}
fn render(&self, color: Color, model: &mut T) {
for idx in model.iter_pixels() {
let (dir, height) = idx.as_spherical();
use Orientation::*;
*model.get_mut(idx) = match self.orient {
Horizontal => color.shift_hue(self.step * dir),
Vertical => color.shift_hue(self.step * height),
Spiral => color.shift_hue(self.step * height / 2.0 + self.step * dir),
};
}
}
fn rotate_cw(&mut self, _color: &mut Color) {
//self.color = self.color.shift_hue(self.speed);
self.speed *= 1.1;
}
fn rotate_ccw(&mut self, _color: &mut Color) {
//self.color = self.color.shift_hue(self.speed * -1.0);
self.speed *= 0.9;
}
fn click(&mut self, _color: &mut Color) {
self.orient = self.orient.next();
}
}
| true |
e8f3f9048b8f0215df05a46ee0b9e96b06cd7867
|
Rust
|
mdalbello/seqkit
|
/src/sam_count.rs
|
UTF-8
| 3,280 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
use crate::common::{parse_args, BamReader};
use std::str;
use std::thread;
use std::fs::{File, remove_file};
use std::process::{Command, Stdio};
use std::io::{BufReader, BufWriter, BufRead, Write};
const USAGE: &str = "
Usage:
sam count [options] <bam_file> <regions.bed>
Options:
--frac-inside=F Minimum overlap between read and region [default: 0.0]
--min-mapq=N Only count reads with MAPQ ≥ threshold [default: 0]
--single-end Count reads, rather than paired end fragments
";
pub fn main() {
let args = parse_args(USAGE);
let bam_path = args.get_str("<bam_file>").to_string();
let bed_path = args.get_str("<regions.bed>");
let min_mapq: u8 = args.get_str("--min-mapq").parse().unwrap_or_else(
|_| error!("--min-mapq must be an integer between 0 - 255."));
let single_end = args.get_bool("--single-end");
let bam = BamReader::open(&bam_path);
let mut chr_names: Vec<String> = Vec::new();
for name in bam.header().target_names() {
chr_names.push(str::from_utf8(name).unwrap().to_string());
}
let index_path = format!("{}.idx", bam_path);
let mut index_file = File::create(&index_path).unwrap();
for c in 0..chr_names.len() {
write!(&mut index_file, "{}\t{}\n", chr_names[c], bam.header().target_len(c as u32).unwrap());
}
let mut cmd = Command::new("bedtools");
cmd.arg("coverage"); cmd.arg("-sorted"); cmd.arg("-counts");
cmd.arg("-g"); cmd.arg(&index_path);
cmd.arg("-a"); cmd.arg(&bed_path);
cmd.arg("-b"); cmd.arg("stdin");
let bedtools = cmd.stdin(Stdio::piped()).stdout(Stdio::piped())
.spawn().expect("Could not start bedtools process.");
let mut bedtools_in = BufWriter::new(bedtools.stdin.unwrap());
let bedtools_out = BufReader::new(bedtools.stdout.unwrap());
if single_end == false {
// Analyze in paired end mode
thread::spawn(move || {
let mut bam = BamReader::open(&bam_path);
for read in bam {
if read.is_paired() == false { continue; }
if read.is_unmapped() || read.is_mate_unmapped() { continue; }
if read.is_duplicate() || read.is_secondary() { continue; }
if read.is_supplementary() { continue; }
if read.tid() != read.mtid() { continue; }
if read.mapq() < min_mapq { continue; }
// Only count each DNA fragment once.
if read.pos() > read.mpos() || (read.pos() == read.mpos() && read.is_first_in_template() == false) { continue; }
let frag_size = read.insert_size().abs();
if frag_size > 5000 { continue; }
write!(bedtools_in, "{}\t{}\t{}\n", chr_names[read.tid() as usize], read.pos(), read.pos() + frag_size);
}
});
} else {
// Analyze in single end mode
thread::spawn(move || {
let mut bam = BamReader::open(&bam_path);
for read in bam {
if read.is_unmapped() { continue; }
if read.is_duplicate() || read.is_secondary() { continue; }
if read.is_supplementary() { continue; }
if read.mapq() < min_mapq { continue; }
let end_pos = read.cigar().end_pos();
if (end_pos - read.pos()).abs() > 5000 { continue; }
write!(bedtools_in, "{}\t{}\t{}\n", chr_names[read.tid() as usize], read.pos(), end_pos);
}
});
}
for l in bedtools_out.lines() {
let line = l.unwrap();
println!("{}", line.split('\t').last().unwrap());
}
remove_file(index_path);
}
| true |
0162430db3f887ad1e49ec41bfdb9309d0f929da
|
Rust
|
filippixavier/AoC2019
|
/src/days/day14.rs
|
UTF-8
| 3,669 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
use std::error::Error;
use std::fs;
use std::path::Path;
use regex::Regex;
use std::collections::HashMap;
#[derive(Debug, Clone)]
struct Recipe {
qut_produced: u64,
composition: HashMap<String, u64>,
}
fn get_recipes(input: String) -> HashMap<String, Recipe> {
let reg = Regex::new(r"(\d+) (\w+)").unwrap();
let mut values: HashMap<String, Recipe> = HashMap::new();
let input = input.trim().split('\n');
for line in input {
let recipe = line.split("=>").collect::<Vec<_>>();
let going_in = reg.captures_iter(recipe[0]);
let going_out = reg.captures(recipe[1]).unwrap();
let out_name: String = going_out[2].to_string();
let mut composition: HashMap<String, u64> = HashMap::new();
for ins in going_in {
let qut = ins[1].parse::<u64>().unwrap();
let name = ins[2].to_string();
composition.insert(name, qut);
}
values.insert(
out_name,
Recipe {
qut_produced: going_out[1].parse::<u64>().unwrap(),
composition,
},
);
}
values
}
fn run_machine(recipes: &HashMap<String, Recipe>, fuel_to_produce: u64) -> u64 {
let mut status = recipes.get("FUEL").unwrap().composition.clone();
let mut left_overs: HashMap<String, u64> = HashMap::new();
let mut ore_count = 0;
for (_, qut) in status.iter_mut() {
*qut *= fuel_to_produce;
}
while !status.is_empty() {
let mut new_status = HashMap::new();
for (comp_name, qut_required) in status.iter() {
let recipe = recipes.get(comp_name).unwrap();
let compo_made = left_overs.entry(comp_name.clone()).or_insert(0);
let truly_needed = if *compo_made >= *qut_required {
*compo_made -= *qut_required;
0
} else {
let value = *qut_required - *compo_made;
*compo_made = 0;
value
};
let ratio = (truly_needed as f64 / recipe.qut_produced as f64).ceil() as u64;
*compo_made += ratio * recipe.qut_produced - truly_needed;
for (ingredient, qut) in recipe.composition.iter() {
if ingredient == "ORE" {
ore_count += qut * ratio;
} else {
let current_count = new_status.entry(ingredient.clone()).or_insert(0);
*current_count += qut * ratio;
}
}
}
status = new_status;
}
ore_count
}
pub fn first_star() -> Result<(), Box<dyn Error + 'static>> {
let recipes = get_recipes(fs::read_to_string(Path::new("./data/day14.txt"))?);
println!(
"Minimum quantity of ORE required: {}",
run_machine(&recipes, 1)
);
Ok(())
}
pub fn second_star() -> Result<(), Box<dyn Error + 'static>> {
let available_ore: u64 = 1_000_000_000_000;
let recipes = get_recipes(fs::read_to_string(Path::new("./data/day14.txt"))?);
let fuel_for_ore = run_machine(&recipes, 1);
let mut attempt = 0;
let mut left_overs_ore = available_ore;
loop {
let fuel_to_add = if left_overs_ore / fuel_for_ore == 0 {
1
} else {
left_overs_ore / fuel_for_ore
};
attempt += fuel_to_add;
let ore_consumed = run_machine(&recipes, attempt);
if ore_consumed < available_ore {
left_overs_ore = available_ore - ore_consumed;
} else {
attempt -= fuel_to_add;
break;
}
}
println!("Maximum fuel: {}", attempt);
Ok(())
}
| true |
9ae327bb3f62484aafd03758e6f0498483014557
|
Rust
|
mtXTJocj/rosetta_code
|
/code_generator/src/lib.rs
|
UTF-8
| 30,274 | 2.890625 | 3 |
[
"Unlicense"
] |
permissive
|
use std::collections::HashMap;
use std::string::ToString;
use instruction::*;
use lexical_analyzer::error::*;
use syntax_analyzer::ast_node::*;
mod instruction;
pub struct CodeGenerator<'a> {
data_addr: HashMap<&'a str, u32>,
string_pool: Vec<&'a str>,
pc: u32,
instructions: Vec<Instruction>,
}
impl<'a> CodeGenerator<'a> {
pub fn generate(ast: &'a ASTNode) -> Result<String> {
let mut generator = CodeGenerator {
data_addr: HashMap::new(),
string_pool: Vec::new(),
pc: 0,
instructions: Vec::new(),
};
generator.generate_body(ast)?;
generator
.instructions
.push(Instruction::new(InstructionKind::Halt, generator.pc));
let mut code = format!(
"Datasize: {} Strings: {}\n",
generator.data_addr.len(),
generator.string_pool.len()
);
if generator.string_pool.len() > 0 {
code += &generator
.string_pool
.iter()
.map(|s| format!("{:?}", s))
.collect::<Vec<String>>()
.join("\n");
code += "\n";
}
code += &generator
.instructions
.iter()
.map(|i| i.to_string())
.collect::<Vec<String>>()
.join("\n");
Ok(code)
}
fn generate_body(&mut self, ast: &'a ASTNode) -> Result<()> {
match ast.kind() {
NodeKind::Identifier(identifier) => self.generate_fetch(identifier),
NodeKind::Integer(value) => self.generate_integer(*value),
NodeKind::Sequence => self.generate_sequence(ast),
NodeKind::If => self.generate_if(ast),
NodeKind::Prtc => self.generate_prtc(ast),
NodeKind::Prts => self.generate_prts(ast),
NodeKind::Prti => self.generate_prti(ast),
NodeKind::While => self.generate_while(ast),
NodeKind::Assign => self.generate_assign(ast),
NodeKind::Negate | NodeKind::Not => self.generate_unary_op(ast),
NodeKind::Multiply
| NodeKind::Divide
| NodeKind::Mod
| NodeKind::Add
| NodeKind::Subtract
| NodeKind::Less
| NodeKind::LessEqual
| NodeKind::Greater
| NodeKind::GreaterEqual
| NodeKind::Equal
| NodeKind::NotEqual
| NodeKind::And
| NodeKind::Or => self.generate_binary_op(ast),
_ => Err(CompileError::new(
ErrorKind::CodeGenerationError,
"unknown instruction",
)),
}
}
fn generate_fetch(&mut self, identifier: &'a str) -> Result<()> {
match self.data_addr.get(identifier) {
Some(addr) => {
self.instructions
.push(Instruction::new(InstructionKind::Fetch(*addr), self.pc));
self.pc += 1 + 4;
Ok(())
}
None => Err(CompileError::new(
ErrorKind::CodeGenerationError,
format!("unknown identifier: {}", identifier),
)),
}
}
fn generate_integer(&mut self, value: i32) -> Result<()> {
self.instructions
.push(Instruction::new(InstructionKind::Push(value), self.pc));
self.pc += 1 + 4;
Ok(())
}
fn backpatch(&mut self, instruction_index: usize) {
let instruction = &mut self.instructions[instruction_index];
if let Instruction {
kind: InstructionKind::Jump(ref mut rel),
address,
}
| Instruction {
kind: InstructionKind::Jz(ref mut rel),
address,
} = instruction
{
*rel = (self.pc - (*address + 1)) as i32;
} else {
unreachable!();
}
}
fn generate_if(&mut self, ast: &'a ASTNode) -> Result<()> {
// condition
self.generate_body(ast.lhs().unwrap())?;
self.instructions
.push(Instruction::new(InstructionKind::Jz(0), self.pc));
self.pc += 1 + 4;
let jump_if_clause_idx = &self.instructions.len() - 1;
// if-clause
let body = ast.rhs().unwrap();
self.generate_body(body.lhs().unwrap())?;
// else-clause
match body.rhs() {
Some(else_clause) => {
self.instructions
.push(Instruction::new(InstructionKind::Jump(0), self.pc));
let jump_instruction_idx = self.instructions.len() - 1;
self.pc += 1 + 4;
self.backpatch(jump_if_clause_idx);
self.generate_body(else_clause)?;
self.backpatch(jump_instruction_idx);
}
None => {
self.backpatch(jump_if_clause_idx);
}
}
Ok(())
}
fn generate_while(&mut self, ast: &'a ASTNode) -> Result<()> {
// condition
let entry_address = self.pc;
self.generate_body(ast.lhs().unwrap())?;
self.instructions
.push(Instruction::new(InstructionKind::Jz(0), self.pc));
let entry_index = self.instructions.len() - 1;
self.pc += 1 + 4;
// body
self.generate_body(ast.rhs().unwrap())?;
self.instructions.push(Instruction::new(
InstructionKind::Jump(entry_address.wrapping_sub(self.pc + 1) as i32),
self.pc,
));
self.pc += 1 + 4;
self.backpatch(entry_index);
Ok(())
}
fn intern_string(&mut self, s: &'a str) -> u32 {
for (i, &st) in self.string_pool.iter().enumerate() {
if s == st {
return i as u32;
}
}
self.string_pool.push(s);
(self.string_pool.len() - 1) as u32
}
fn generate_prts(&mut self, ast: &'a ASTNode) -> Result<()> {
let string_node = ast.lhs().unwrap();
if let NodeKind::String(s) = string_node.kind() {
let addr = self.intern_string(s) as i32;
self.instructions
.push(Instruction::new(InstructionKind::Push(addr), self.pc));
self.pc += 1 + 4;
} else {
return Err(CompileError::new(
ErrorKind::CodeGenerationError,
"string expected",
));
}
self.instructions
.push(Instruction::new(InstructionKind::Prts, self.pc));
self.pc += 1;
Ok(())
}
fn generate_prtc(&mut self, ast: &'a ASTNode) -> Result<()> {
self.generate_body(ast.lhs().unwrap())?;
self.instructions
.push(Instruction::new(InstructionKind::Prtc, self.pc));
self.pc += 1;
Ok(())
}
fn generate_prti(&mut self, ast: &'a ASTNode) -> Result<()> {
self.generate_body(ast.lhs().unwrap())?;
self.instructions
.push(Instruction::new(InstructionKind::Prti, self.pc));
self.pc += 1;
Ok(())
}
fn generate_sequence(&mut self, ast: &'a ASTNode) -> Result<()> {
if let Some(lhs) = ast.lhs() {
self.generate_body(lhs)?;
}
if let Some(rhs) = ast.rhs() {
self.generate_body(rhs)?;
}
Ok(())
}
fn intern(&mut self, name: &'a str) -> u32 {
match self.data_addr.get(name) {
Some(addr) => *addr,
None => {
let addr = self.data_addr.len() as u32;
self.data_addr.insert(name, addr);
addr
}
}
}
fn generate_assign(&mut self, ast: &'a ASTNode) -> Result<()> {
let identifier_node = ast.lhs().unwrap();
self.generate_body(ast.rhs().unwrap())?;
if let NodeKind::Identifier(ref identifier) = identifier_node.kind() {
let addr = self.intern(identifier);
self.instructions
.push(Instruction::new(InstructionKind::Store(addr), self.pc));
self.pc += 1 + 4;
} else {
return Err(CompileError::new(
ErrorKind::CodeGenerationError,
"identifier is expected",
));
}
Ok(())
}
fn generate_unary_op(&mut self, ast: &'a ASTNode) -> Result<()> {
self.generate_body(ast.lhs().unwrap())?;
let instruction_kind = match ast.kind() {
NodeKind::Negate => InstructionKind::Neg,
NodeKind::Not => InstructionKind::Not,
_ => {
return Err(CompileError::new(
ErrorKind::CodeGenerationError,
"invalid unary operator",
))
}
};
self.instructions
.push(Instruction::new(instruction_kind, self.pc));
self.pc += 1;
Ok(())
}
fn generate_binary_op(&mut self, ast: &'a ASTNode) -> Result<()> {
self.generate_body(ast.lhs().unwrap())?;
self.generate_body(ast.rhs().unwrap())?;
let instruction_kind = match ast.kind() {
NodeKind::Multiply => InstructionKind::Mul,
NodeKind::Divide => InstructionKind::Div,
NodeKind::Mod => InstructionKind::Mod,
NodeKind::Add => InstructionKind::Add,
NodeKind::Subtract => InstructionKind::Sub,
NodeKind::Less => InstructionKind::Lt,
NodeKind::LessEqual => InstructionKind::Le,
NodeKind::Greater => InstructionKind::Gt,
NodeKind::GreaterEqual => InstructionKind::Ge,
NodeKind::Equal => InstructionKind::Eq,
NodeKind::NotEqual => InstructionKind::Ne,
NodeKind::And => InstructionKind::And,
NodeKind::Or => InstructionKind::Or,
_ => {
return Err(CompileError::new(
ErrorKind::CodeGenerationError,
"invalid binary operator",
))
}
};
self.instructions
.push(Instruction::new(instruction_kind, self.pc));
self.pc += 1;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_integer() {
let s = r#"Integer 1"#.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_add() {
// 1 + 2
let s = r#"Add
Integer 1
Integer 2
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_subtract() {
// 1 + 2
let s = r#"Subtract
Integer 1
Integer 2
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_negate() {
// -1
let s = r#"Negate
Integer 1
;
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_assign() {
// count = 1
let s = r#"Assign
Identifier count
Integer 1
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_identifier() {
// count = 1;
// count = count + 1;
let s = r#"Sequence
Sequence
;
Assign
Identifier count
Integer 1
Assign
Identifier count
Add
Identifier count
Integer 1
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_prti() {
// count = 1;
// print(count);
let s = r#"Sequence
Sequence
;
Assign
Identifier count
Integer 1
Sequence
;
Prti
Identifier count
;
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_prtc() {
// count = 1;
// putc(count);
let s = r#"Sequence
Sequence
;
Assign
Identifier count
Integer 1
Sequence
;
Prtc
Identifier count
;
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_prts() {
// print("abc", "cba", "abc");
let s = r#"Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "abc"
;
Prts
String "cba"
;
Prts
String "abc"
;
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_if() {
// if (1) {
// print(2);
// } else {
// print(3);
// }
let s = r#"Sequence
;
If
Integer 1
If
Sequence
;
Sequence
;
Prti
Integer 2
;
Sequence
;
Sequence
;
Prti
Integer 3
;
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
println!("{:?}", CodeGenerator::generate(&ast));
}
#[test]
fn test_hello_world() {
let s = r#"Sequence
;
Sequence
;
Prts
String "Hello, World!\n"
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 0 Strings: 1
"Hello, World!\n"
0 push 0
5 prts
6 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_phoenix_number() {
let s = r#"Sequence
Sequence
;
Assign
Identifier phoenix_number
Integer 142857
Sequence
Sequence
;
Prti
Identifier phoenix_number
;
Prts
String "\n"
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 1 Strings: 1
"\n"
0 push 142857
5 store [0]
10 fetch [0]
15 prti
16 push 0
21 prts
22 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_case_4() {
let s = r#"Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_count() {
let s = r#"Sequence
Sequence
;
Assign
Identifier count
Integer 1
While
Less
Identifier count
Integer 10
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "count is: "
;
Prti
Identifier count
;
Prts
String "\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 1 Strings: 2
"count is: "
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 10
20 lt
21 jz (43) 65
26 push 0
31 prts
32 fetch [0]
37 prti
38 push 1
43 prts
44 fetch [0]
49 push 1
54 add
55 store [0]
60 jmp (-51) 10
65 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_100_doors() {
let s = r#"Sequence
Sequence
;
Assign
Identifier i
Integer 1
While
LessEqual
Multiply
Identifier i
Identifier i
Integer 100
Sequence
Sequence
;
Sequence
Sequence
Sequence
;
Prts
String "door "
;
Prti
Multiply
Identifier i
Identifier i
;
Prts
String " is open\n"
;
Assign
Identifier i
Add
Identifier i
Integer 1"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 1 Strings: 2
"door "
" is open\n"
0 push 1
5 store [0]
10 fetch [0]
15 fetch [0]
20 mul
21 push 100
26 le
27 jz (49) 77
32 push 0
37 prts
38 fetch [0]
43 fetch [0]
48 mul
49 prti
50 push 1
55 prts
56 fetch [0]
61 push 1
66 add
67 store [0]
72 jmp (-63) 10
77 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_negative_tests() {
let s = r#"Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier a
Multiply
Negate
Integer 1
;
Divide
Multiply
Negate
Integer 1
;
Multiply
Integer 5
Integer 15
Integer 10
Sequence
Sequence
;
Prti
Identifier a
;
Prts
String "\n"
;
Assign
Identifier b
Negate
Identifier a
;
Sequence
Sequence
;
Prti
Identifier b
;
Prts
String "\n"
;
Sequence
Sequence
;
Prti
Negate
Identifier b
;
;
Prts
String "\n"
;
Sequence
Sequence
;
Prti
Negate
Integer 1
;
;
Prts
String "\n"
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 2 Strings: 1
"\n"
0 push 1
5 neg
6 push 1
11 neg
12 push 5
17 push 15
22 mul
23 mul
24 push 10
29 div
30 mul
31 store [0]
36 fetch [0]
41 prti
42 push 0
47 prts
48 fetch [0]
53 neg
54 store [1]
59 fetch [1]
64 prti
65 push 0
70 prts
71 fetch [1]
76 neg
77 prti
78 push 0
83 prts
84 push 1
89 neg
90 prti
91 push 0
96 prts
97 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_deep() {
let s = r#"Sequence
Sequence
Sequence
;
Sequence
Sequence
;
Prti
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Negate
Integer 5
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
Prts
String "\n"
;
Sequence
Sequence
;
Prti
Multiply
Add
Integer 3
Integer 2
Integer 2
;
Prts
String "\n"
;
If
Integer 1
If
Sequence
;
If
Integer 1
If
Sequence
;
If
Integer 1
If
Sequence
;
If
Integer 1
If
Sequence
;
If
Integer 1
If
Sequence
;
Sequence
Sequence
;
Prti
Integer 15
;
Prts
String "\n"
;
;
;
;
;
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 0 Strings: 1
"\n"
0 push 5
5 neg
6 neg
7 neg
8 neg
9 neg
10 neg
11 neg
12 neg
13 neg
14 neg
15 neg
16 neg
17 neg
18 neg
19 neg
20 neg
21 neg
22 neg
23 neg
24 neg
25 neg
26 neg
27 neg
28 neg
29 neg
30 neg
31 neg
32 neg
33 neg
34 neg
35 neg
36 neg
37 neg
38 prti
39 push 0
44 prts
45 push 3
50 push 2
55 add
56 push 2
61 mul
62 prti
63 push 0
68 prts
69 push 1
74 jz (56) 131
79 push 1
84 jz (46) 131
89 push 1
94 jz (36) 131
99 push 1
104 jz (26) 131
109 push 1
114 jz (16) 131
119 push 15
124 prti
125 push 0
130 prts
131 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_greatest_common_divisor() {
let s = r#"Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier a
Integer 1071
Assign
Identifier b
Integer 1029
While
NotEqual
Identifier b
Integer 0
Sequence
Sequence
Sequence
;
Assign
Identifier new_a
Identifier b
Assign
Identifier b
Mod
Identifier a
Identifier b
Assign
Identifier a
Identifier new_a
Sequence
;
Prti
Identifier a
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 3 Strings: 0
0 push 1071
5 store [0]
10 push 1029
15 store [1]
20 fetch [1]
25 push 0
30 ne
31 jz (45) 77
36 fetch [1]
41 store [2]
46 fetch [0]
51 fetch [1]
56 mod
57 store [1]
62 fetch [2]
67 store [0]
72 jmp (-53) 20
77 fetch [0]
82 prti
83 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_factorial() {
let s = r#"Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier n
Integer 12
Assign
Identifier result
Integer 1
Assign
Identifier i
Integer 1
While
LessEqual
Identifier i
Identifier n
Sequence
Sequence
;
Assign
Identifier result
Multiply
Identifier result
Identifier i
Assign
Identifier i
Add
Identifier i
Integer 1
Sequence
;
Prti
Identifier result
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 3 Strings: 0
0 push 12
5 store [0]
10 push 1
15 store [1]
20 push 1
25 store [2]
30 fetch [2]
35 fetch [0]
40 le
41 jz (41) 83
46 fetch [1]
51 fetch [2]
56 mul
57 store [1]
62 fetch [2]
67 push 1
72 add
73 store [2]
78 jmp (-49) 30
83 fetch [1]
88 prti
89 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_fibonacci_sequence() {
let s = r#"Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier n
Integer 44
Assign
Identifier i
Integer 1
Assign
Identifier a
Integer 0
Assign
Identifier b
Integer 1
While
Less
Identifier i
Identifier n
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier w
Add
Identifier a
Identifier b
Assign
Identifier a
Identifier b
Assign
Identifier b
Identifier w
Assign
Identifier i
Add
Identifier i
Integer 1
Sequence
Sequence
;
Prti
Identifier w
;
Prts
String "\n"
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 5 Strings: 1
"\n"
0 push 44
5 store [0]
10 push 1
15 store [1]
20 push 0
25 store [2]
30 push 1
35 store [3]
40 fetch [1]
45 fetch [0]
50 lt
51 jz (61) 113
56 fetch [2]
61 fetch [3]
66 add
67 store [4]
72 fetch [3]
77 store [2]
82 fetch [4]
87 store [3]
92 fetch [1]
97 push 1
102 add
103 store [1]
108 jmp (-69) 40
113 fetch [4]
118 prti
119 push 0
124 prts
125 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_fizzbuzz() {
let s = r#"Sequence
Sequence
;
Assign
Identifier i
Integer 1
While
LessEqual
Identifier i
Integer 100
Sequence
Sequence
Sequence
;
If
Not
Mod
Identifier i
Integer 15
;
If
Sequence
;
Prts
String "FizzBuzz"
;
If
Not
Mod
Identifier i
Integer 3
;
If
Sequence
;
Prts
String "Fizz"
;
If
Not
Mod
Identifier i
Integer 5
;
If
Sequence
;
Prts
String "Buzz"
;
Sequence
;
Prti
Identifier i
;
Sequence
;
Prts
String "\n"
;
Assign
Identifier i
Add
Identifier i
Integer 1"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 1 Strings: 4
"FizzBuzz"
"Fizz"
"Buzz"
"\n"
0 push 1
5 store [0]
10 fetch [0]
15 push 100
20 le
21 jz (121) 143
26 fetch [0]
31 push 15
36 mod
37 not
38 jz (15) 54
43 push 0
48 prts
49 jmp (66) 116
54 fetch [0]
59 push 3
64 mod
65 not
66 jz (15) 82
71 push 1
76 prts
77 jmp (38) 116
82 fetch [0]
87 push 5
92 mod
93 not
94 jz (15) 110
99 push 2
104 prts
105 jmp (10) 116
110 fetch [0]
115 prti
116 push 3
121 prts
122 fetch [0]
127 push 1
132 add
133 store [0]
138 jmp (-129) 10
143 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_99_bottles_of_beer() {
let s = r#"Sequence
Sequence
;
Assign
Identifier bottles
Integer 99
While
Greater
Identifier bottles
Integer 0
Sequence
Sequence
Sequence
Sequence
Sequence
;
Sequence
Sequence
;
Prti
Identifier bottles
;
Prts
String " bottles of beer on the wall\n"
;
Sequence
Sequence
;
Prti
Identifier bottles
;
Prts
String " bottles of beer\n"
;
Sequence
;
Prts
String "Take one down, pass it around\n"
;
Assign
Identifier bottles
Subtract
Identifier bottles
Integer 1
Sequence
Sequence
;
Prti
Identifier bottles
;
Prts
String " bottles of beer on the wall\n\n"
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 1 Strings: 4
" bottles of beer on the wall\n"
" bottles of beer\n"
"Take one down, pass it around\n"
" bottles of beer on the wall\n\n"
0 push 99
5 store [0]
10 fetch [0]
15 push 0
20 gt
21 jz (67) 89
26 fetch [0]
31 prti
32 push 0
37 prts
38 fetch [0]
43 prti
44 push 1
49 prts
50 push 2
55 prts
56 fetch [0]
61 push 1
66 sub
67 store [0]
72 fetch [0]
77 prti
78 push 3
83 prts
84 jmp (-75) 10
89 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_primes() {
let s = r#"Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier count
Integer 1
Assign
Identifier n
Integer 1
Assign
Identifier limit
Integer 100
While
Less
Identifier n
Identifier limit
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier k
Integer 3
Assign
Identifier p
Integer 1
Assign
Identifier n
Add
Identifier n
Integer 2
While
And
LessEqual
Multiply
Identifier k
Identifier k
Identifier n
Identifier p
Sequence
Sequence
;
Assign
Identifier p
NotEqual
Multiply
Divide
Identifier n
Identifier k
Identifier k
Identifier n
Assign
Identifier k
Add
Identifier k
Integer 2
If
Identifier p
If
Sequence
Sequence
;
Sequence
Sequence
;
Prti
Identifier n
;
Prts
String " is prime\n"
;
Assign
Identifier count
Add
Identifier count
Integer 1
;
Sequence
Sequence
Sequence
;
Prts
String "Total primes found: "
;
Prti
Identifier count
;
Prts
String "\n"
;"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 5 Strings: 3
" is prime\n"
"Total primes found: "
"\n"
0 push 1
5 store [0]
10 push 1
15 store [1]
20 push 100
25 store [2]
30 fetch [1]
35 fetch [2]
40 lt
41 jz (160) 202
46 push 3
51 store [3]
56 push 1
61 store [4]
66 fetch [1]
71 push 2
76 add
77 store [1]
82 fetch [3]
87 fetch [3]
92 mul
93 fetch [1]
98 le
99 fetch [4]
104 and
105 jz (53) 159
110 fetch [1]
115 fetch [3]
120 div
121 fetch [3]
126 mul
127 fetch [1]
132 ne
133 store [4]
138 fetch [3]
143 push 2
148 add
149 store [3]
154 jmp (-73) 82
159 fetch [4]
164 jz (32) 197
169 fetch [1]
174 prti
175 push 0
180 prts
181 fetch [0]
186 push 1
191 add
192 store [0]
197 jmp (-168) 30
202 push 1
207 prts
208 fetch [0]
213 prti
214 push 2
219 prts
220 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
#[test]
fn test_ascii_mandlebrot() {
let s = r#"Sequence
;
Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier left_edge
Negate
Integer 420
;
Assign
Identifier right_edge
Integer 300
Assign
Identifier top_edge
Integer 300
Assign
Identifier bottom_edge
Negate
Integer 300
;
Assign
Identifier x_step
Integer 7
Assign
Identifier y_step
Integer 15
Assign
Identifier max_iter
Integer 200
Assign
Identifier y0
Identifier top_edge
While
Greater
Identifier y0
Identifier bottom_edge
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier x0
Identifier left_edge
While
Less
Identifier x0
Identifier right_edge
Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier y
Integer 0
Assign
Identifier x
Integer 0
Assign
Identifier the_char
Integer 32
Assign
Identifier i
Integer 0
While
Less
Identifier i
Identifier max_iter
Sequence
Sequence
Sequence
Sequence
Sequence
Sequence
;
Assign
Identifier x_x
Divide
Multiply
Identifier x
Identifier x
Integer 200
Assign
Identifier y_y
Divide
Multiply
Identifier y
Identifier y
Integer 200
If
Greater
Add
Identifier x_x
Identifier y_y
Integer 800
If
Sequence
Sequence
Sequence
;
Assign
Identifier the_char
Add
Integer 48
Identifier i
If
Greater
Identifier i
Integer 9
If
Sequence
;
Assign
Identifier the_char
Integer 64
;
Assign
Identifier i
Identifier max_iter
;
Assign
Identifier y
Add
Divide
Multiply
Identifier x
Identifier y
Integer 100
Identifier y0
Assign
Identifier x
Add
Subtract
Identifier x_x
Identifier y_y
Identifier x0
Assign
Identifier i
Add
Identifier i
Integer 1
Prtc
Identifier the_char
;
Assign
Identifier x0
Add
Identifier x0
Identifier x_step
Prtc
Integer 10
;
Assign
Identifier y0
Subtract
Identifier y0
Identifier y_step"#
.to_string();
let ast = ASTReader::read_ast(s.lines());
assert_eq!(
r#"Datasize: 15 Strings: 0
0 push 420
5 neg
6 store [0]
11 push 300
16 store [1]
21 push 300
26 store [2]
31 push 300
36 neg
37 store [3]
42 push 7
47 store [4]
52 push 15
57 store [5]
62 push 200
67 store [6]
72 fetch [2]
77 store [7]
82 fetch [7]
87 fetch [3]
92 gt
93 jz (329) 423
98 fetch [0]
103 store [8]
108 fetch [8]
113 fetch [1]
118 lt
119 jz (276) 396
124 push 0
129 store [9]
134 push 0
139 store [10]
144 push 32
149 store [11]
154 push 0
159 store [12]
164 fetch [12]
169 fetch [6]
174 lt
175 jz (193) 369
180 fetch [10]
185 fetch [10]
190 mul
191 push 200
196 div
197 store [13]
202 fetch [9]
207 fetch [9]
212 mul
213 push 200
218 div
219 store [14]
224 fetch [13]
229 fetch [14]
234 add
235 push 800
240 gt
241 jz (56) 298
246 push 48
251 fetch [12]
256 add
257 store [11]
262 fetch [12]
267 push 9
272 gt
273 jz (14) 288
278 push 64
283 store [11]
288 fetch [6]
293 store [12]
298 fetch [10]
303 fetch [9]
308 mul
309 push 100
314 div
315 fetch [7]
320 add
321 store [9]
326 fetch [13]
331 fetch [14]
336 sub
337 fetch [8]
342 add
343 store [10]
348 fetch [12]
353 push 1
358 add
359 store [12]
364 jmp (-201) 164
369 fetch [11]
374 prtc
375 fetch [8]
380 fetch [4]
385 add
386 store [8]
391 jmp (-284) 108
396 push 10
401 prtc
402 fetch [7]
407 fetch [5]
412 sub
413 store [7]
418 jmp (-337) 82
423 halt"#,
CodeGenerator::generate(&ast).unwrap()
);
}
}
| true |
47371144fef83f10a09f2e5b1bc5bd27331a06d1
|
Rust
|
NicoVIII/galaxy-server-rust
|
/src/gamegen/mod.rs
|
UTF-8
| 24,675 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
use rand::Rng;
use std::cmp;
use std::convert::TryFrom;
use std::convert::TryInto;
mod print;
mod t;
fn add_border(space: &t::DotSpace, filler: t::Dot) -> t::DotSpace {
let x_size = space.len();
let y_size = space[0].len();
let mut new_space: t::DotSpace = Vec::new();
// Create border line
let mut occupied_line: t::DotSpaceColumn = Vec::new();
for _ in 0..(y_size + 2) {
occupied_line.push(filler);
}
// Create space
new_space.push(occupied_line.clone());
for x in 0..x_size {
let mut line: t::DotSpaceColumn = Vec::new();
line.push(filler);
for y in 0..y_size {
line.push(space[x][y]);
}
line.push(filler);
new_space.push(line);
}
new_space.push(occupied_line);
new_space
}
fn mark_as_occupied(space: &mut t::DotSpace, dot: &t::DotPos, filler: t::Dot) -> () {
let x_size = space.len();
let y_size = space[0].len();
let dot_x = i16::try_from(dot.0).unwrap();
let dot_y = i16::try_from(dot.1).unwrap();
// Is a dot on an edge or corner even more places are not available anymore
let x_diff = if dot_x % 2 == 1 { 2 } else { 1 };
let y_diff = if dot_y % 2 == 1 { 2 } else { 1 };
// Every place around the dot is not available anymore
for i in -x_diff..=x_diff {
for j in -y_diff..=y_diff {
let x = dot_x + i;
let y = dot_y + j;
let x = usize::try_from(x);
let y = usize::try_from(y);
match (x, y) {
(Ok(x), Ok(y)) => {
if x < x_size && y < y_size && space[x][y] == 0 {
space[x][y] = filler;
}
}
_ => (),
}
}
}
}
fn generate_next_dots_by_pattern(
space: &mut t::DotSpace,
pattern_list: &Vec<t::Pattern>,
) -> Option<Vec<t::DotPos>> {
// Prepare patterns and space by adding occupied border
let tmp_space = add_border(space, 1);
let mut result = None;
let x_size = tmp_space.len();
'outer: for x in 0..x_size {
let y_size = tmp_space[x].len();
for y in 0..y_size {
// Iterate through all patterns
for pattern in pattern_list {
let mut new_dot_list = Vec::new();
// Check if pattern matches
let px_size = pattern.len();
let py_size = pattern[0].len();
for px in 0..px_size {
for py in 0..py_size {
let x2 = x + px;
let y2 = y + py;
if x2 < x_size
&& y2 < y_size
&& (pattern[px][py] == 0
|| tmp_space[x2][y2] == 1 && pattern[px][py] == 1
|| tmp_space[x2][y2] == 0 && pattern[px][py] > 1)
{
if pattern[px][py] == 3 {
let pos = t::DotPos(x2 - 1, y2 - 1);
new_dot_list.push(pos);
}
} else {
continue 'outer;
}
}
}
// Found a matching pattern! Occupy space
{
let mut occupied_space = false;
for px in 0..px_size {
for py in 0..py_size {
let x2 = i32::try_from(x + px).unwrap() - 1;
let y2 = i32::try_from(y + py).unwrap() - 1;
let x2 = usize::try_from(x2);
let y2 = usize::try_from(y2);
match (x2, y2) {
(Ok(x2), Ok(y2)) => {
if x2 % 2 == 0
&& y2 % 2 == 0
&& x2 < x_size - 2
&& y2 < y_size - 2
&& pattern[px][py] > 1
{
let pos = t::DotPos(x2, y2);
mark_as_occupied(space, &pos, 1);
occupied_space = true;
}
}
_ => (),
}
}
}
if !occupied_space {
panic!("Did not occupy space!");
}
}
result = Some(new_dot_list);
break 'outer;
}
}
}
result
}
/// Calculates for a field in DotSpace a weight for the choosing algorithm
fn calculate_neighbor_weight(
space: &t::DotSpace,
x: usize,
y: usize,
x_size: usize,
y_size: usize,
neighbor_span: i16,
) -> u8 {
let mut result = 0;
let x = i16::try_from(x).expect("x is no valid i16");
let y = i16::try_from(y).expect("y is no valid i16");
'outer: for i in 1..neighbor_span {
for j in -i..i {
let x2 = x + j;
let y2_1 = y - (i - j.abs());
let y2_2 = y + (i - j.abs());
let x2 = usize::try_from(x2);
let y2_1 = usize::try_from(y2_1);
let y2_2 = usize::try_from(y2_2);
match (x2, y2_1, y2_2) {
(Ok(x2), Ok(y2_1), Ok(y2_2)) => {
if x2 >= x_size {
result = 1;
break 'outer;
}
// First y
if y2_1 >= y_size || space[x2][y2_1] == 1 {
result = 1;
break 'outer;
};
// Second y, if existing
if y2_1 != y2_2 && (y2_2 >= y_size || space[x2][y2_2] == 1) {
result = 1;
break 'outer;
}
}
_ => {
result = 1;
break 'outer;
}
}
}
}
result
}
fn get_random_dot_candidates(space: &t::DotSpace, min_distance_to_filled: u16) -> Vec<t::DotPos> {
// Determine possible candidates
let mut candidates = Vec::new();
let x_size = space.len();
for x in 0..x_size {
let y_size = space[x].len();
for y in 0..y_size {
// Calculate neighbor score
let min_distance_to_filled = i16::try_from(min_distance_to_filled)
.expect("min_distance_to_filled is no valid i16");
let penalty =
calculate_neighbor_weight(space, x, y, x_size, y_size, min_distance_to_filled);
let neighbor_score = 1 - penalty;
if space[x][y] == 0 && neighbor_score > 0 {
let dot_pos = t::DotPos(x.try_into().unwrap(), y.try_into().unwrap());
candidates.push(dot_pos);
}
}
}
candidates
}
/// Generates a random dot in the empty spots. Tries to use a weight function to
/// prefer spaces which allow bigger galaxies.
fn generate_random_dot_in_empty_spot(
space: &t::DotSpace,
rng: &mut rand::prelude::ThreadRng,
) -> t::DotPos {
let mut candidates = Vec::new();
let search_radius = 3;
for i in (0..=search_radius).rev() {
candidates = get_random_dot_candidates(space, i);
print::dot_space_candidates(space, &candidates);
if candidates.len() > 0 {
break;
}
}
if candidates.len() == 0 {
panic!("Found no candidates!");
}
// Choose one candidate randomly
let new_dot_index = rng.gen_range(0..candidates.len());
candidates.swap_remove(new_dot_index)
}
/// Takes a DotSpace with 2s where the current galaxy is generated and the
/// center of the galaxy and tries to add another field to this galaxy.
///
/// @return DotSpace after addition of field
fn add_field_to_galaxy(
space: &mut t::DotSpace,
dot: &t::DotPos,
rng: &mut rand::prelude::ThreadRng,
) -> bool {
// Determine possible candidates
let mut candidates = Vec::new();
let x_size = space.len();
for x in 0..x_size {
let y_size = space[x].len();
for y in 0..y_size {
// Check if field is adjacent
let left = x > 0 && space[x - 1][y] == 2;
let right = x + 1 < x_size && space[x + 1][y] == 2;
let top = y > 0 && space[x][y - 1] == 2;
let bottom = y + 1 < y_size && space[x][y + 1] == 2;
if space[x][y] == 0 && (left || right || top || bottom) {
// Check if corresponding field is free too
let x2 = i32::try_from(2 * dot.0).unwrap() - i32::try_from(x).unwrap();
let y2 = i32::try_from(2 * dot.1).unwrap() - i32::try_from(y).unwrap();
let x2 = usize::try_from(x2);
let y2 = usize::try_from(y2);
match (x2, y2) {
(Ok(x2), Ok(y2)) => {
if x2 < x_size && y2 < y_size && space[x2][y2] == 0 {
let x = x.try_into().unwrap();
let y = y.try_into().unwrap();
let penalty1 =
4 * calculate_neighbor_weight(space, x, y, x_size, y_size, 2) + 1;
let penalty2 =
4 * calculate_neighbor_weight(space, x2, y2, x_size, y_size, 2) + 1;
for _ in 0..cmp::max(penalty1, penalty2) {
candidates.push(t::DotPos(x, y));
}
}
}
_ => (),
}
}
}
}
print::dot_space_candidates(space, &candidates);
// Choose one candidate randomly
if candidates.len() > 0 {
let new_field_index = rng.gen_range(0..(candidates.len() - 1));
let winner = candidates.swap_remove(new_field_index);
mark_as_occupied(space, &winner, 2);
// Mark corresponding field as well
let x2 = i16::try_from(2 * dot.0).unwrap() - i16::try_from(winner.0).unwrap();
let y2 = i16::try_from(2 * dot.1).unwrap() - i16::try_from(winner.1).unwrap();
let x2 = usize::try_from(x2);
let y2 = usize::try_from(y2);
match (x2, y2) {
(Ok(x2), Ok(y2)) => {
if x2 < x_size && y2 < space[x2].len() {
mark_as_occupied(space, &t::DotPos(x2, y2), 2);
}
}
_ => (),
}
}
candidates.len() > 0
}
/// Takes a space and a dot and places the dot in the space.
/// For this dot a randomised galaxy is created and the space for that gets
/// occupied.
///
/// @return DotSpace after adding dot
fn generate_galaxy_from_dot(
space: &mut t::DotSpace,
dot: &t::DotPos,
rng: &mut rand::prelude::ThreadRng,
) -> () {
mark_as_occupied(space, dot, 2);
// Add fields to galaxy/
let mut field = 0;
let mid_of_bell = i32::try_from(space.len() * space[0].len()).unwrap() / 40 - 1;
let steepness = 10;
loop {
let result = add_field_to_galaxy(space, dot, rng);
field += 1;
// There are no fields to add anymore... :(
if !result {
break;
}
let denominator: i32 = f64::from(steepness + (field - mid_of_bell).pow(2))
.sqrt()
.round() as i32;
let probability = (-50 * (field - mid_of_bell)) / denominator + 50;
let dice = rng.gen_range(1..100);
if dice > probability {
break;
}
}
// Normalize entries in space
let x_size = space.len();
for x in 0..x_size {
let y_size = space[x].len();
for y in 0..y_size {
if space[x][y] == 2 {
space[x][y] = 1;
}
}
}
}
fn generate_next_dots(
space: &mut t::DotSpace,
pattern_list: &Vec<t::Pattern>,
rng: &mut rand::prelude::ThreadRng,
) -> Vec<t::DotPos> {
// First try pattern matching
let next_dots = generate_next_dots_by_pattern(space, pattern_list);
match next_dots {
Some(dots) => dots,
None => {
// If that doesn't work, generate random dot
let new_dot = generate_random_dot_in_empty_spot(&space, rng);
generate_galaxy_from_dot(space, &new_dot, rng);
vec![new_dot]
}
}
}
fn create_patterns() -> Vec<t::Pattern> {
// Patterns
// 0: content irrelevant
// 1: occupied
// 2: free
// 3: free / center of a new galaxy
let mut pattern_list = Vec::new();
// Most important pattern has to be first in pattern list
// □ □ □
// □ ▣ □
// □ □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □ □
// □ ▣ □
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 1, 0, 0]);
pattern.push(vec![1, 2, 2, 2, 1, 0, 0]);
pattern.push(vec![1, 2, 2, 2, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![1, 1, 1, 2, 2, 2, 1]);
pattern.push(vec![0, 0, 1, 2, 2, 2, 1]);
pattern.push(vec![0, 0, 1, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □ □
// □ ▣ □
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 0, 0, 1, 1, 1, 0]);
pattern.push(vec![0, 0, 1, 2, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 2, 1, 0, 0]);
pattern.push(vec![0, 1, 1, 1, 0, 0, 0]);
pattern_list.push(pattern);
}
// □ □ □
// ▣
// □ □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 2, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 2, 1, 1, 0]);
pattern.push(vec![0, 0, 1, 3, 1, 0, 0]);
pattern.push(vec![0, 1, 1, 2, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 2, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □ □
// □ ▣ □
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 0, 0, 0, 1, 0]);
pattern.push(vec![1, 2, 1, 0, 1, 2, 1]);
pattern.push(vec![1, 2, 1, 1, 1, 2, 1]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![1, 2, 1, 1, 1, 2, 1]);
pattern.push(vec![1, 2, 1, 0, 1, 2, 1]);
pattern.push(vec![0, 1, 0, 0, 0, 1, 0]);
pattern_list.push(pattern);
}
// □ □
// □ □
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 3, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □ □ □
// □ □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □ □
// ▣
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 0, 0, 1, 1, 1, 0]);
pattern.push(vec![0, 0, 1, 2, 2, 2, 1]);
pattern.push(vec![0, 0, 1, 2, 1, 1, 0]);
pattern.push(vec![0, 0, 1, 3, 1, 0, 0]);
pattern.push(vec![0, 1, 1, 2, 1, 0, 0]);
pattern.push(vec![1, 2, 2, 2, 1, 0, 0]);
pattern.push(vec![0, 1, 1, 1, 0, 0, 0]);
pattern_list.push(pattern);
}
// □ □
// ▣
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 0, 0, 0]);
pattern.push(vec![1, 2, 2, 2, 1, 0, 0]);
pattern.push(vec![0, 1, 1, 2, 1, 0, 0]);
pattern.push(vec![0, 0, 1, 3, 1, 0, 0]);
pattern.push(vec![0, 0, 1, 2, 1, 1, 0]);
pattern.push(vec![0, 0, 1, 2, 2, 2, 1]);
pattern.push(vec![0, 0, 1, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □
// □ ▣ □
// □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 0, 0, 0, 0, 0]);
pattern.push(vec![1, 2, 1, 0, 0, 0, 0]);
pattern.push(vec![1, 2, 1, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 1, 2, 1]);
pattern.push(vec![0, 0, 0, 0, 1, 2, 1]);
pattern.push(vec![0, 0, 0, 0, 0, 1, 0]);
pattern_list.push(pattern);
}
// □
// □ ▣ □
// □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 0, 0, 0, 0, 1, 0]);
pattern.push(vec![0, 0, 0, 0, 1, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 1, 2, 1]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![1, 2, 1, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 1, 0, 0, 0, 0]);
pattern.push(vec![0, 1, 0, 0, 0, 0, 0]);
pattern_list.push(pattern);
}
// □ □
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 0, 0, 1, 1, 1, 0]);
pattern.push(vec![0, 0, 1, 2, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 3, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 2, 1, 0, 0]);
pattern.push(vec![0, 1, 1, 1, 0, 0, 0]);
pattern_list.push(pattern);
}
// □ □
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 0, 0, 0]);
pattern.push(vec![1, 2, 2, 2, 1, 0, 0]);
pattern.push(vec![0, 1, 1, 3, 1, 1, 0]);
pattern.push(vec![0, 0, 1, 2, 2, 2, 1]);
pattern.push(vec![0, 0, 1, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □
// □ □
// □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 0, 0, 0]);
pattern.push(vec![1, 2, 0, 0, 0]);
pattern.push(vec![1, 2, 1, 1, 0]);
pattern.push(vec![1, 2, 3, 2, 1]);
pattern.push(vec![0, 1, 1, 2, 1]);
pattern.push(vec![0, 0, 0, 2, 1]);
pattern.push(vec![0, 0, 0, 1, 0]);
pattern_list.push(pattern);
}
// □
// □ □
// □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 0, 0, 0, 0, 1, 0]);
pattern.push(vec![0, 0, 0, 0, 1, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 1, 2, 1]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![1, 2, 1, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 1, 0, 0, 0, 0]);
pattern.push(vec![0, 1, 0, 0, 0, 0, 0]);
pattern_list.push(pattern);
}
// □ □
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 2, 1]);
pattern.push(vec![1, 2, 3, 2, 1]);
pattern.push(vec![1, 2, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □ ▣ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 2, 3, 2, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □
// ▣
// □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 0]);
pattern.push(vec![1, 2, 1]);
pattern.push(vec![1, 2, 1]);
pattern.push(vec![1, 3, 1]);
pattern.push(vec![1, 2, 1]);
pattern.push(vec![1, 2, 1]);
pattern.push(vec![0, 1, 0]);
pattern_list.push(pattern);
}
// □ □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 1, 1, 0]);
pattern.push(vec![1, 2, 3, 2, 1]);
pattern.push(vec![0, 1, 1, 1, 0]);
pattern_list.push(pattern);
}
// □
// □
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 0]);
pattern.push(vec![1, 2, 1]);
pattern.push(vec![1, 3, 1]);
pattern.push(vec![1, 2, 1]);
pattern.push(vec![0, 1, 0]);
pattern_list.push(pattern);
}
// ▣
{
let mut pattern = Vec::new();
pattern.push(vec![0, 1, 0]);
pattern.push(vec![1, 3, 1]);
pattern.push(vec![0, 1, 0]);
pattern_list.push(pattern);
}
pattern_list
}
/// Helper function which counts the empty spots in a DotSpace.
///
/// @return number of empty spots
fn count_empty_spots(space: &t::DotSpace) -> u32 {
let x_size = space.len();
let mut empty_spaces_total = 0;
// Determine which y values have empty places for the dots to go to
// Save y index and amount of empty spaces
for x in 0..x_size {
let y_size = space[x].len();
// Simply counts the empty spaces
for y in 0..y_size {
if space[x][y] == 0 {
empty_spaces_total += 1;
}
}
}
return empty_spaces_total;
}
/// Entrypoint into dot generation.
/// Takes the size of the field and generates dots in it which are then returned.
///
/// @return List of generated dots
pub fn generate_dots(x_size: usize, y_size: usize) -> Vec<t::DotPos> {
// Generate empty space
let mut space: t::DotSpace = Vec::new();
for _ in 0..x_size * 2 - 1 {
let mut column: t::DotSpaceColumn = Vec::new();
for _ in 0..y_size * 2 - 1 {
column.push(0);
}
space.push(column);
}
// Generate dots in space
let pattern_list = create_patterns();
let mut new_dot_list = Vec::new();
let mut rng = rand::thread_rng();
loop {
let next_dots = generate_next_dots(&mut space, &pattern_list, &mut rng);
for next_dot in next_dots {
new_dot_list.push(next_dot);
}
let empty_spaces = count_empty_spots(&space);
// Debugging statements
print::dot_space(&space);
if empty_spaces <= 0 {
break;
}
}
return new_dot_list;
}
#[cfg(test)]
mod tests {
use super::*;
use t::*;
fn generic_test(width: usize, height: usize) {
for _ in 0..10 {
let board = generate_dots(width, height);
// Amount of generated dots
assert!(board.len() > 0);
assert!(board.len() <= width * height);
// Test that generated dots make sense
let mut seen_dots = Vec::new();
for dot in board {
// Dots have to be unique
assert!(!seen_dots.contains(&dot));
// Dots have to be inside the board
assert!(dot.0 < width * 2);
assert!(dot.1 < height * 2);
// Dots can't have direct neighbors
if dot.0 > 0 {
assert!(!seen_dots.contains(&DotPos(dot.0 - 1, dot.1)))
}
if dot.1 > 0 {
assert!(!seen_dots.contains(&DotPos(dot.0, dot.1 - 1)))
}
if dot.0 < width * 2 {
assert!(!seen_dots.contains(&DotPos(dot.0 + 1, dot.1)))
}
if dot.0 < height * 2 {
assert!(!seen_dots.contains(&DotPos(dot.0, dot.1 + 1)))
}
// TODO: neighbor checks for on grid dots
seen_dots.push(dot);
}
}
}
#[test]
fn dynamic() {
for w in 1..=12 {
for h in 1..=12 {
generic_test(w, h);
}
}
}
}
| true |
ea05129911513ef472e43ee3640405d73be62db4
|
Rust
|
ReggieMarr/audio-oxide
|
/docs/reference_src/unused/callbacks.rs
|
UTF-8
| 4,894 | 2.75 | 3 |
[] |
no_license
|
use signal_processing::{Sample, AnalyzedSample};
use rustfft::{FFTplanner, FFT};
use num::complex::Complex;
#[derive(Copy, Clone, Debug)]
pub struct Vec4 {
pub vec: [f32; 4],
}
implement_vertex!(Vec4, vec);
struct input_parameters {
fft_size : usize,
buffer_size : usize,
use_analytic_filter : bool,
angle_lp : Box<FnMut(f32) -> f32>,
noise_lp : Box<FnMut(f32) -> f32>,
fft : Option<Arc<FFT<T>>>,
ifft : Option<Arc<FFT<T>>>
}
//break this up with more generic names
struct callback_scope_parameters {
time_ring_buffer : Vec<Complex<f32>>
analytic_buffer : Vec<Vec4>
}
//come up with a better name
pub struct CallbackHandler {
input : input_parameters,
scope_param : callback_scope_parameters,
}
struct AnalyticFilter {
}
impl EventHandler for Callback {
fn eventhandler(&self) {
let scope_parm = self.scope_param;
let input = self.input;
//This represents the amplitude of the signal represented as the distance from the origin on a unit circle
//Here we transform the signal from the time domain to the frequency domain.
//Note that humans can only hear sound with a frequency between 20Hz and 20_000Hz
fft.process(&mut time_ring_buffer[time_index..time_index + fft_size], &mut complex_freq_buffer[..]);
//the analytic array acts as a filter, removing the negative and dc portions
//of the signal as well as filtering out the nyquist portion of the signal
//Also applies the hamming window here
// By applying the inverse fourier transform we transform the signal from the frequency domain back into the
if use_analytic_filt {
for (x, y) in analytic.iter().zip(complex_freq_buffer.iter_mut()) {
*y = *x * *y;
}
}
// By applying the inverse fourier transform we transform the signal from the frequency domain back into the
// time domain. However now this signal can be represented as a series of points on a unit circle.
// ifft.process(&mut complex_freq_buffer[..], &mut complex_analytic_buffer[..]);
if false {
let test_freq = complex_freq_buffer.clone();
for (freq_idxpl freq) in test_freq.iter().take(fft_size/2).enumerate() {
let bin = SAMPLE_RATE as f32 / fft_size as f32;
// let freq_mag = f32::sqrt((freq.re as f32).exp2() + (freq.im as f32).exp2())/fft_size as f32;
let freq_val = bin*freq_idx as f32;
if freq_val > 200.0f32 && freq_val < 20_000.0f32 {
println!("{:?}, {:?}", freq_val as f32, (20.0f32*((2.0f32*freq.im/fft_size as f32).abs().log10())));
}
}
}
// let analyzed_audio_sample = Sample<'_,Complex<f32>,AnalyzedSample>::new();
//here we are filling the start of our array with the ned of the last one so that we have a continuous stream
if use_analytic_filt {
analytic_buffer[0] = analytic_buffer[buffer_size];
analytic_buffer[1] = analytic_buffer[buffer_size + 1];
analytic_buffer[2] = analytic_buffer[buffer_size + 2];
}
// time domain. However now this signal can be represented as a series of points on a unit circle.
// ifft.process(&mut complex_freq_buffer[..], &mut complex_analytic_buffer[..]);
let scale = fft_size as f32;
let freq_res = SAMPLE_RATE as f32 / scale;
// for (&x, y) in complex_analytic_buffer[fft_size - buffer_size..].iter().zip(analytic_buffer[3..].iter_mut()) {
//this takes 256 points from the complex_freq_buffer into the analytic_buffer
// for (&x, y) in complex_freq_buffer[(fft_size - buffer_size)..].iter().zip(analytic_buffer[3..].iter_mut()) {
let freq_iter = complex_freq_buffer.iter().zip(analytic_buffer.iter_mut());
for (freq_idx, (&x, y)) in freq_iter.enumerate() {
let diff = x - prev_input; // vector
prev_input = x;
let angle = get_angle(diff, prev_diff).abs().log2().max(-1.0e12); // angular velocity (with processing)
prev_diff = diff;
let output = angle_lp(angle);
let sample_freq = freq_res * freq_idx as f32;
*y = Vec4 { vec: [
// save the scaling for later
x.re,
x.im,
sample_freq, // smoothed angular velocity
noise_lp((angle - output).abs()), // average angular noise
]};
}
//what is rendered and why would dropped represent its inverse ?
let dropped = {
let mut buffer = buffers[buffer_index].lock().unwrap();
let rendered = buffer.rendered;
buffer.analytic.copy_from_slice(&analytic_buffer);
buffer.rendered = false;
!rendered
};
// for x in 0..num_buffers {
// println!("noise {:?}", analytic_buffer[x]);
// }
buffer_index = (buffer_index + 1) % num_buffers;
if dropped {
// what does sender do generally ?
sender.send(()).ok();
}
Continue
}
}
| true |
87423349194ddf7a6ea69b8cf0103856d972185f
|
Rust
|
hur/advent-of-code-2020
|
/day10/src/main.rs
|
UTF-8
| 1,552 | 3.421875 | 3 |
[] |
no_license
|
use std::io::{self, BufRead};
use std::collections::HashMap;
fn part1(data: &[u32]) {
// Diffs is a mapping of the magnitude of difference between two elements in data and the count
// of the difference
let mut diffs = HashMap::<u32,u32>::new();
let mut prev = 0u32;
for d in data.iter() {
let curr_diff = d - prev;
*diffs.entry(curr_diff).or_insert(0) += 1;
prev = *d;
}
println!("{:?}", diffs);
println!("Part 1: {}*{}={}", diffs.get(&1).unwrap(), diffs.get(&3).unwrap(), diffs.get(&1).unwrap() * diffs.get(&3).unwrap());
}
fn part2(data: &[u32]) {
// We describe the number of ways to chain _i_ adapters (steps[i]])
// as the sum of ways to chain the previous adapters that can be connected to it
// with steps[0] = 1
// and use this to build the final result from steps[0]
let n = data.len();
let mut steps: Vec<u64> = vec![0; n];
steps.insert(0, 1);
for i in 0..n {
let mut j = i + 1;
while j < n && data[j] <= data[i] + 3 {
steps[j] += steps[i];
j += 1;
}
}
println!("part 2: {}", steps[n- 1]);
}
fn main() {
// Data is a sorted vector of adapter joltages including
// the starting joltage 0 and the device joltage
let mut data: Vec<u32> = vec![0];
data.extend(io::stdin().lock().lines()
.map(|line| line.unwrap().parse::<u32>().unwrap()));
data.sort_unstable();
data.push(&data[data.len() - 1] + 3); // Add the device joltage
part1(&data);
part2(&data);
}
| true |
41aa496539b3efc866bce0e3767cd802428d1f43
|
Rust
|
itang/tests
|
/test-rusts/test_2018_mod_paths/src/paths.rs
|
UTF-8
| 1,026 | 3.15625 | 3 |
[] |
no_license
|
//see: https://rust-lang-nursery.github.io/edition-guide/rust-2018/module-system/path-clarity.html
// Rust 2018 (uniform paths variant)
//a path starting from an external crate name
use futures::Future;
use self::foo::Bar;
mod foo {
pub struct Bar;
}
// use a relative path from the current module
//a path starting from an external crate name
trait A {
fn my_poll();
}
fn f1() {}
enum SomeEnum {
V1(usize),
V2(String),
}
pub fn func() {
//a path starting from an external crate name
let five = std::sync::Arc::new(5);
let five = ::std::sync::Arc::new(10); // use ::name for an external crate name
use self::SomeEnum::*; //self::name for a local module or item
self::f1(); //or a path starting with [crate, super, or ]self
crate::hello::hello(); // or a path starting with crate [super, or self]
}
mod sub_paths {
fn foo() {
super::f1(); // or a path starting with [crate ], [super], or self
//my_poll(); //error
//self::my_poll(); //error
}
}
| true |
e2b477160b908a01aedb28a417a953efdf24dc2d
|
Rust
|
nicksrandall/serde_dynamo
|
/src/de/deserializer_seq.rs
|
UTF-8
| 2,855 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
use super::{AttributeValue, Deserializer, Error, Result};
use crate::de::deserializer_bytes::DeserializerBytes;
use crate::de::deserializer_number::DeserializerNumber;
use serde::de::{DeserializeSeed, IntoDeserializer, SeqAccess};
pub struct DeserializerSeq {
iter: std::vec::IntoIter<AttributeValue>,
}
impl DeserializerSeq {
pub fn from_vec(vec: Vec<AttributeValue>) -> Self {
Self {
iter: vec.into_iter(),
}
}
}
impl<'de, 'a> SeqAccess<'de> for DeserializerSeq {
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
if let Some(value) = self.iter.next() {
let de = Deserializer::from_attribute_value(value);
seed.deserialize(de).map(Some)
} else {
Ok(None)
}
}
}
pub struct DeserializerSeqStrings {
iter: std::vec::IntoIter<String>,
}
impl DeserializerSeqStrings {
pub fn from_vec(vec: Vec<String>) -> Self {
Self {
iter: vec.into_iter(),
}
}
}
impl<'de, 'a> SeqAccess<'de> for DeserializerSeqStrings {
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
if let Some(value) = self.iter.next() {
let de = value.into_deserializer();
seed.deserialize(de).map(Some)
} else {
Ok(None)
}
}
}
pub struct DeserializerSeqNumbers {
iter: std::vec::IntoIter<String>,
}
impl DeserializerSeqNumbers {
pub fn from_vec(vec: Vec<String>) -> Self {
Self {
iter: vec.into_iter(),
}
}
}
impl<'de, 'a> SeqAccess<'de> for DeserializerSeqNumbers {
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
if let Some(value) = self.iter.next() {
let de = DeserializerNumber::from_string(value);
seed.deserialize(de).map(Some)
} else {
Ok(None)
}
}
}
pub struct DeserializerSeqBytes<T> {
iter: std::vec::IntoIter<T>,
}
impl<T> DeserializerSeqBytes<T> {
pub fn from_vec(vec: Vec<T>) -> Self {
Self {
iter: vec.into_iter(),
}
}
}
impl<'de, 'a, B> SeqAccess<'de> for DeserializerSeqBytes<B>
where
B: AsRef<[u8]>,
{
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
if let Some(value) = self.iter.next() {
let de = DeserializerBytes::from_bytes(value);
seed.deserialize(de).map(Some)
} else {
Ok(None)
}
}
}
| true |
1f497a8ca9f04c1a047703c65a72662d632b1e63
|
Rust
|
sooda/advent-of-code
|
/19/9.rs
|
UTF-8
| 3,994 | 2.984375 | 3 |
[] |
no_license
|
use std::io::{self, BufRead};
fn step<'a, 'b, I: Iterator<Item = &'b i64>>(program: &'a mut [i64], ip: usize, base: i64, input: &mut I) -> Option<(usize, i64, Option<i64>)> {
let opcode = program[ip] % 100;
if opcode == 99 {
// short circuit this, the discontinuity is annoying
return None;
}
let mode0 = program[ip] / 100 % 10;
let mode1 = program[ip] / 1000 % 10;
let mode2 = program[ip] / 10000 % 10;
assert!(mode0 <= 2);
assert!(mode1 <= 2);
assert!(mode2 <= 2);
let immflags = (mode0 == 1, mode1 == 1, mode2 == 1);
let relflags = (mode0 == 2, mode1 == 2, mode2 == 2);
// indirection via closures instead of direct variables because indexing might go off with
// arbitrary values: only evaluate when it's known that indexing is okay. Need this to avoid
// repetition in the opcode decoding
let rel0 = if relflags.0 { base } else { 0 };
let rel1 = if relflags.1 { base } else { 0 };
let rel2 = if relflags.2 { base } else { 0 };
let imm0 = || program[ip + 1];
let imm1 = || program[ip + 2];
let val0 = || if immflags.0 { imm0() } else { program[(imm0() + rel0) as usize ] };
let val1 = || if immflags.1 { imm1() } else { program[(imm1() + rel1) as usize ] };
// program as input for lifetime; using imm0 here would cause more lifetime trouble
let mut0 = |program: &'a mut [i64]| {
assert!(!immflags.0); &mut program[(program[ip + 1] + rel0) as usize] };
let mut2 = |program: &'a mut [i64]| {
assert!(!immflags.2); &mut program[(program[ip + 3] + rel2) as usize] };
match opcode {
1 => {
*mut2(program) = val0() + val1();
Some((ip + 4, base, None))
},
2 => {
*mut2(program) = val0() * val1();
Some((ip + 4, base, None))
},
3 => {
*mut0(program) = *input.next().unwrap();
Some((ip + 2, base, None))
}
4 => {
Some((ip + 2, base, Some(val0())))
},
5 => {
if val0() != 0 {
Some((val1() as usize, base, None))
} else {
Some((ip + 3, base, None))
}
},
6 => {
if val0() == 0 {
Some((val1() as usize, base, None))
} else {
Some((ip + 3, base, None))
}
},
7 => {
*mut2(program) = if val0() < val1() { 1 } else { 0 };
Some((ip + 4, base, None))
},
8 => {
*mut2(program) = if val0() == val1() { 1 } else { 0 };
Some((ip + 4, base, None))
},
9 => {
Some((ip + 2, base + val0(), None))
},
_ => panic!("something went wrong at {}: {}", ip, program[ip])
}
}
fn execute(program: &[i64], inputs: &[i64]) -> Vec<i64> {
let mut program = program.to_vec();
// make the available memory "much larger than the initial program"
program.resize(program.len() + 1000, 0);
let mut ip = 0;
let mut output = Vec::new();
let mut input = inputs.iter();
let mut base = 0;
while let Some((newip, newbase, newout)) = step(&mut program, ip, base, &mut input) {
if newout.is_some() {
output.push(newout.unwrap());
}
ip = newip;
base = newbase;
}
output
}
fn main() {
assert_eq!(execute(&[109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99], &[]),
&[109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]);
assert!(execute(&[1102,34915192,34915192,7,4,7,99,0], &[])[0] / 1_000_000_000_000_000 < 10);
assert!(execute(&[1102,34915192,34915192,7,4,7,99,0], &[])[0] / 1_000_000_000_000_000 > 0);
let program: Vec<i64> = io::stdin().lock().lines().next().unwrap().unwrap()
.split(',').map(|n| n.parse().unwrap()).collect();
println!("{:?}", execute(&program, &[1])[0]);
println!("{:?}", execute(&program, &[2])[0]);
}
| true |
c0323bebb8495df6efb6e235614f279e03240995
|
Rust
|
Connicpu/boop
|
/src/main.rs
|
UTF-8
| 4,948 | 3.0625 | 3 |
[] |
no_license
|
use std::io::{Cursor, Write};
use async_std::net::UdpSocket;
pub mod tts;
#[async_std::main]
async fn main() {
let mut args = std::env::args().skip(1);
let result = match args.next().as_deref() {
Some("--help") | None => {
eprintln!("USAGE: boop [name] broadcast a boop packet to [name]");
eprintln!(" boop --everyone boop everyone (don't be annoying tho!)");
eprintln!(" boop --help get this message");
eprintln!(" boop --daemon [name] start the boop daemon, listening as [name]");
eprintln!(" boop --install [name] adds the boop daemon to startup as [name]");
Ok(())
}
Some("--daemon") => match args.next() {
Some(name) => daemon(name).await,
None => {
eprintln!("Daemon requires a listening name");
Ok(())
}
},
Some("--install") => match args.next() {
Some(name) => install(name),
None => {
eprintln!("Installation requires a listening name");
Ok(())
}
},
Some("--everyone") => boop(None).await,
Some(name) => boop(Some(name.to_string())).await,
};
if let Err(err) = result {
eprintln!("Failure in boop command: {}", err);
}
}
const PORT: u16 = 0xC_C_24; // C_C_Z
async fn get_my_name() -> anyhow::Result<String> {
let sock = UdpSocket::bind(("0.0.0.0", 0)).await?;
sock.send_to(b"get-name", ("127.0.0.1", PORT)).await?;
let mut buf = [0; 512];
let len = sock.recv(&mut buf).await?;
Ok(String::from_utf8_lossy(&buf[..len]).into_owned())
}
async fn boop(name: Option<String>) -> anyhow::Result<()> {
let my_name = get_my_name().await?;
let mut buf = [0; 512];
let buflen = {
let mut cursor = Cursor::new(&mut buf[..]);
if let Some(name) = name {
write!(&mut cursor, "boop {}->{}", my_name, name)?;
} else {
write!(&mut cursor, "boop {}", my_name)?;
}
cursor.position() as usize
};
let sock = UdpSocket::bind(("0.0.0.0", 0)).await?;
sock.set_broadcast(true)?;
sock.send_to(&buf[..buflen], ("192.168.1.255", PORT))
.await?;
Ok(())
}
async fn daemon(name: String) -> anyhow::Result<()> {
let mut buf = [0; 512];
let sock = UdpSocket::bind(("0.0.0.0", PORT)).await?;
sock.set_broadcast(true)?;
let mut speaker = tts::Speaker::new()?;
loop {
let (len, sender) = match sock.recv_from(&mut buf).await {
Err(err) => break Err(err.into()),
Ok((len, _)) if len < 6 => continue,
Ok(res) => res,
};
let cmd = match std::str::from_utf8(&buf[..len]) {
Ok(cmd) => cmd,
Err(_) => continue,
};
if cmd == "get-name" {
sock.send_to(name.as_bytes(), sender).await?;
} else if cmd.starts_with("boop ") {
let mut parts = cmd[5..].split("->");
let sender_name = parts.next().expect("Split always has at least 1 component");
let recipient = parts.next();
if recipient.is_some() && recipient != Some(name.as_ref()) {
continue;
}
let message = if recipient.is_none() {
format!("{} is booping everyone!!!", sender_name)
} else {
format!("{} is booping you!", sender_name)
};
speaker.speak_async(&message)?;
}
}
}
fn install(name: String) -> anyhow::Result<()> {
let posh = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.EXE";
let exe = std::env::current_exe()?;
let cmd = format!(
". '{path}' --daemon '{name}'",
path = exe.to_string_lossy(),
name = name
);
let args = format!("-windowstyle hidden -command \"{cmd}\"", cmd = cmd);
let appdata = std::env::var("APPDATA")?;
let startup = format!(
"{appdata}\\Microsoft\\Windows\\Start Menu\\Programs\\Startup",
appdata = appdata
);
let shortcut = format!("{startup}\\Boop.lnk", startup = startup);
let make_shortcut = format!(
"$ws = New-Object -ComObject WScript.Shell; \
$shortcut = $ws.CreateShortcut(\"{shortcut}\"); \
$shortcut.TargetPath = \"{posh}\"; \
$shortcut.WorkingDirectory = \"{exedir}\"; \
$shortcut.Arguments = \"{args}\"; \
$shortcut.Save();",
shortcut = shortcut,
posh = posh,
exedir = exe.parent().unwrap().to_string_lossy(),
args = args.replace("\"", "`\""),
);
std::process::Command::new(posh)
.arg("-Command")
.arg(&make_shortcut)
.spawn()?
.wait()?;
std::process::Command::new("cmd.exe")
.arg("/C")
.arg(&shortcut)
.spawn()?;
Ok(())
}
| true |
9ad7ac837a0c1a579dd4ab389655de029b7b10ac
|
Rust
|
athre0z/color-backtrace
|
/src/lib.rs
|
UTF-8
| 29,059 | 3.3125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! Colorful and clean backtraces on panic.
//!
//! This library aims to make panics a little less painful by nicely colorizing
//! them, skipping over frames of functions called after the panic was already
//! initiated and printing relevant source snippets. Frames of functions in your
//! application are colored in a different color (red) than those of
//! dependencies (green).
//!
//! ### Screenshot
//! 
//!
//! ### Features
//! - Colorize backtraces to be easier on the eyes
//! - Show source snippets if source files are found on disk
//! - Print frames of application code vs dependencies in different color
//! - Hide all the frames after the panic was already initiated
//! - Hide language runtime initialization frames
//!
//! ### Installing the panic handler
//!
//! In your main function, just insert the following snippet. That's it!
//! ```rust
//! color_backtrace::install();
//! ```
//!
//! If you want to customize some settings, you can instead do:
//! ```rust
//! use color_backtrace::{default_output_stream, BacktracePrinter};
//! BacktracePrinter::new().message("Custom message!").install(default_output_stream());
//! ```
//!
//! ### Controlling verbosity
//! The default verbosity is configured via the `RUST_BACKTRACE` environment
//! variable. An unset `RUST_BACKTRACE` corresponds to
//! [minimal](Verbosity::Minimal), `RUST_BACKTRACE=1` to
//! [medium](Verbosity::Medium) and `RUST_BACKTRACE=full` to
//! [full](Verbosity::Full) verbosity levels.
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader, ErrorKind, IsTerminal as _};
use std::panic::PanicInfo;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use termcolor::{Ansi, Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
// Re-export termcolor so users don't have to depend on it themselves.
pub use termcolor;
// ============================================================================================== //
// [Result / Error types] //
// ============================================================================================== //
type IOResult<T = ()> = Result<T, std::io::Error>;
// ============================================================================================== //
// [Verbosity management] //
// ============================================================================================== //
/// Defines how verbose the backtrace is supposed to be.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Verbosity {
/// Print a small message including the panic payload and the panic location.
Minimal,
/// Everything in `Minimal` and additionally print a backtrace.
Medium,
/// Everything in `Medium` plus source snippets for all backtrace locations.
Full,
}
impl Verbosity {
/// Get the verbosity level from `RUST_BACKTRACE` env variable.
pub fn from_env() -> Self {
Self::convert_env(env::var("RUST_BACKTRACE").ok())
}
/// Get the verbosity level from `RUST_LIB_BACKTRACE` env variable,
/// falling back to the `RUST_BACKTRACE`.
pub fn lib_from_env() -> Self {
Self::convert_env(
env::var("RUST_LIB_BACKTRACE")
.or_else(|_| env::var("RUST_BACKTRACE"))
.ok(),
)
}
fn convert_env(env: Option<String>) -> Self {
match env {
Some(ref x) if x == "full" => Verbosity::Full,
Some(_) => Verbosity::Medium,
None => Verbosity::Minimal,
}
}
}
// ============================================================================================== //
// [Panic handler and install logic] //
// ============================================================================================== //
/// Install a `BacktracePrinter` handler with `::default()` settings.
///
/// This currently is a convenience shortcut for writing
///
/// ```rust
/// use color_backtrace::{BacktracePrinter, default_output_stream};
/// BacktracePrinter::default().install(default_output_stream())
/// ```
pub fn install() {
BacktracePrinter::default().install(default_output_stream());
}
/// Create the default output stream.
///
/// If stderr is attached to a tty, this is a colorized stderr, else it's
/// a plain (colorless) stderr.
pub fn default_output_stream() -> Box<StandardStream> {
Box::new(StandardStream::stderr(if std::io::stderr().is_terminal() {
ColorChoice::Always
} else {
ColorChoice::Never
}))
}
#[deprecated(
since = "0.4.0",
note = "Use `BacktracePrinter::into_panic_handler()` instead."
)]
pub fn create_panic_handler(
printer: BacktracePrinter,
) -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
let out_stream_mutex = Mutex::new(default_output_stream());
Box::new(move |pi| {
let mut lock = out_stream_mutex.lock().unwrap();
if let Err(e) = printer.print_panic_info(pi, &mut *lock) {
// Panicking while handling a panic would send us into a deadlock,
// so we just print the error to stderr instead.
eprintln!("Error while printing panic: {:?}", e);
}
})
}
#[deprecated(since = "0.4.0", note = "Use `BacktracePrinter::install()` instead.")]
pub fn install_with_settings(printer: BacktracePrinter) {
std::panic::set_hook(printer.into_panic_handler(default_output_stream()))
}
// ============================================================================================== //
// [Backtrace frame] //
// ============================================================================================== //
pub type FilterCallback = dyn Fn(&mut Vec<&Frame>) + Send + Sync + 'static;
#[derive(Debug)]
pub struct Frame {
pub n: usize,
pub name: Option<String>,
pub lineno: Option<u32>,
pub filename: Option<PathBuf>,
pub ip: usize,
_private_ctor: (),
}
impl Frame {
/// Heuristically determine whether the frame is likely to be part of a
/// dependency.
///
/// If it fails to detect some patterns in your code base, feel free to drop
/// an issue / a pull request!
fn is_dependency_code(&self) -> bool {
const SYM_PREFIXES: &[&str] = &[
"std::",
"core::",
"backtrace::backtrace::",
"_rust_begin_unwind",
"color_traceback::",
"__rust_",
"___rust_",
"__pthread",
"_main",
"main",
"__scrt_common_main_seh",
"BaseThreadInitThunk",
"_start",
"__libc_start_main",
"start_thread",
];
// Inspect name.
if let Some(ref name) = self.name {
if SYM_PREFIXES.iter().any(|x| name.starts_with(x)) {
return true;
}
}
const FILE_PREFIXES: &[&str] = &[
"/rustc/",
"src/libstd/",
"src/libpanic_unwind/",
"src/libtest/",
];
// Inspect filename.
if let Some(ref filename) = self.filename {
let filename = filename.to_string_lossy();
if FILE_PREFIXES.iter().any(|x| filename.starts_with(x))
|| filename.contains("/.cargo/registry/src/")
{
return true;
}
}
false
}
/// Heuristically determine whether a frame is likely to be a post panic
/// frame.
///
/// Post panic frames are frames of a functions called after the actual panic
/// is already in progress and don't contain any useful information for a
/// reader of the backtrace.
fn is_post_panic_code(&self) -> bool {
const SYM_PREFIXES: &[&str] = &[
"_rust_begin_unwind",
"rust_begin_unwind",
"core::result::unwrap_failed",
"core::option::expect_none_failed",
"core::panicking::panic_fmt",
"color_backtrace::create_panic_handler",
"std::panicking::begin_panic",
"begin_panic_fmt",
"backtrace::capture",
];
match self.name.as_ref() {
Some(name) => SYM_PREFIXES.iter().any(|x| name.starts_with(x)),
None => false,
}
}
/// Heuristically determine whether a frame is likely to be part of language
/// runtime.
fn is_runtime_init_code(&self) -> bool {
const SYM_PREFIXES: &[&str] = &[
"std::rt::lang_start::",
"test::run_test::run_test_inner::",
"std::sys_common::backtrace::__rust_begin_short_backtrace",
];
let (name, file) = match (self.name.as_ref(), self.filename.as_ref()) {
(Some(name), Some(filename)) => (name, filename.to_string_lossy()),
_ => return false,
};
if SYM_PREFIXES.iter().any(|x| name.starts_with(x)) {
return true;
}
// For Linux, this is the best rule for skipping test init I found.
if name == "{{closure}}" && file == "src/libtest/lib.rs" {
return true;
}
false
}
fn print_source_if_avail(&self, mut out: impl WriteColor, s: &BacktracePrinter) -> IOResult {
let (lineno, filename) = match (self.lineno, self.filename.as_ref()) {
(Some(a), Some(b)) => (a, b),
// Without a line number and file name, we can't sensibly proceed.
_ => return Ok(()),
};
let file = match File::open(filename) {
Ok(file) => file,
Err(ref e) if e.kind() == ErrorKind::NotFound => return Ok(()),
e @ Err(_) => e?,
};
// Extract relevant lines.
let reader = BufReader::new(file);
let start_line = lineno - 2.min(lineno - 1);
let surrounding_src = reader.lines().skip(start_line as usize - 1).take(5);
for (line, cur_line_no) in surrounding_src.zip(start_line..) {
if cur_line_no == lineno {
// Print actual source line with brighter color.
out.set_color(&s.colors.selected_src_ln)?;
writeln!(out, "{:>8} > {}", cur_line_no, line?)?;
out.reset()?;
} else {
writeln!(out, "{:>8} │ {}", cur_line_no, line?)?;
}
}
Ok(())
}
/// Get the module's name by walking /proc/self/maps
#[cfg(all(
feature = "resolve-modules",
unix,
not(any(target_os = "macos", target_os = "ios"))
))]
fn module_info(&self) -> Option<(String, usize)> {
use regex::Regex;
use std::path::Path;
let re = Regex::new(
r"(?x)
^
(?P<start>[0-9a-f]{8,16})
-
(?P<end>[0-9a-f]{8,16})
\s
(?P<perm>[-rwxp]{4})
\s
(?P<offset>[0-9a-f]{8})
\s
[0-9a-f]+:[0-9a-f]+
\s
[0-9]+
\s+
(?P<path>.*)
$
",
)
.unwrap();
let mapsfile = File::open("/proc/self/maps").expect("Unable to open /proc/self/maps");
for line in BufReader::new(mapsfile).lines() {
let line = line.unwrap();
if let Some(caps) = re.captures(&line) {
let (start, end, path) = (
usize::from_str_radix(caps.name("start").unwrap().as_str(), 16).unwrap(),
usize::from_str_radix(caps.name("end").unwrap().as_str(), 16).unwrap(),
caps.name("path").unwrap().as_str().to_string(),
);
if self.ip >= start && self.ip < end {
return if let Some(filename) = Path::new(&path).file_name() {
Some((filename.to_str().unwrap().to_string(), start))
} else {
None
};
}
}
}
None
}
#[cfg(not(all(
feature = "resolve-modules",
unix,
not(any(target_os = "macos", target_os = "ios"))
)))]
fn module_info(&self) -> Option<(String, usize)> {
None
}
fn print(&self, i: usize, out: &mut impl WriteColor, s: &BacktracePrinter) -> IOResult {
let is_dependency_code = self.is_dependency_code();
// Print frame index.
write!(out, "{:>2}: ", i)?;
if s.should_print_addresses() {
if let Some((module_name, module_base)) = self.module_info() {
write!(out, "{}:0x{:08x} - ", module_name, self.ip - module_base)?;
} else {
write!(out, "0x{:016x} - ", self.ip)?;
}
}
// Does the function have a hash suffix?
// (dodging a dep on the regex crate here)
let name = self
.name
.as_ref()
.map(|s| s.as_str())
.unwrap_or("<unknown>");
let has_hash_suffix = name.len() > 19
&& &name[name.len() - 19..name.len() - 16] == "::h"
&& name[name.len() - 16..].chars().all(|x| x.is_digit(16));
// Print function name.
out.set_color(if is_dependency_code {
&s.colors.dependency_code
} else {
&s.colors.crate_code
})?;
if has_hash_suffix {
write!(out, "{}", &name[..name.len() - 19])?;
if s.strip_function_hash {
writeln!(out)?;
} else {
out.set_color(if is_dependency_code {
&s.colors.dependency_code_hash
} else {
&s.colors.crate_code_hash
})?;
writeln!(out, "{}", &name[name.len() - 19..])?;
}
} else {
writeln!(out, "{}", name)?;
}
out.reset()?;
// Print source location, if known.
if let Some(ref file) = self.filename {
let filestr = file.to_str().unwrap_or("<bad utf8>");
let lineno = self
.lineno
.map_or("<unknown line>".to_owned(), |x| x.to_string());
writeln!(out, " at {}:{}", filestr, lineno)?;
} else {
writeln!(out, " at <unknown source file>")?;
}
// Maybe print source.
if s.current_verbosity() >= Verbosity::Full {
self.print_source_if_avail(out, s)?;
}
Ok(())
}
}
/// The default frame filter. Heuristically determines whether a frame is likely to be an
/// uninteresting frame. This filters out post panic frames and runtime init frames and dependency
/// code.
pub fn default_frame_filter(frames: &mut Vec<&Frame>) {
let top_cutoff = frames
.iter()
.rposition(|x| x.is_post_panic_code())
.map(|x| x + 2) // indices are 1 based
.unwrap_or(0);
let bottom_cutoff = frames
.iter()
.position(|x| x.is_runtime_init_code())
.unwrap_or_else(|| frames.len());
let rng = top_cutoff..=bottom_cutoff;
frames.retain(|x| rng.contains(&x.n))
}
// ============================================================================================== //
// [BacktracePrinter] //
// ============================================================================================== //
/// Color scheme definition.
#[derive(Debug, Clone)]
pub struct ColorScheme {
pub frames_omitted_msg: ColorSpec,
pub header: ColorSpec,
pub msg_loc_prefix: ColorSpec,
pub src_loc: ColorSpec,
pub src_loc_separator: ColorSpec,
pub env_var: ColorSpec,
pub dependency_code: ColorSpec,
pub dependency_code_hash: ColorSpec,
pub crate_code: ColorSpec,
pub crate_code_hash: ColorSpec,
pub selected_src_ln: ColorSpec,
}
impl ColorScheme {
/// Helper to create a new `ColorSpec` & set a few properties in one wash.
fn cs(fg: Option<Color>, intense: bool, bold: bool) -> ColorSpec {
let mut cs = ColorSpec::new();
cs.set_fg(fg);
cs.set_bold(bold);
cs.set_intense(intense);
cs
}
/// The classic `color-backtrace` scheme, as shown in the screenshots.
pub fn classic() -> Self {
Self {
frames_omitted_msg: Self::cs(Some(Color::Cyan), true, false),
header: Self::cs(Some(Color::Red), false, false),
msg_loc_prefix: Self::cs(Some(Color::Cyan), false, false),
src_loc: Self::cs(Some(Color::Magenta), false, false),
src_loc_separator: Self::cs(Some(Color::White), false, false),
env_var: Self::cs(None, false, true),
dependency_code: Self::cs(Some(Color::Green), false, false),
dependency_code_hash: Self::cs(Some(Color::Black), true, false),
crate_code: Self::cs(Some(Color::Red), true, false),
crate_code_hash: Self::cs(Some(Color::Black), true, false),
selected_src_ln: Self::cs(None, false, true),
}
}
}
impl Default for ColorScheme {
fn default() -> Self {
Self::classic()
}
}
#[deprecated(since = "0.4.0", note = "Use `BacktracePrinter` instead.")]
pub type Settings = BacktracePrinter;
/// Pretty-printer for backtraces and [`PanicInfo`](PanicInfo) structs.
#[derive(Clone)]
pub struct BacktracePrinter {
message: String,
verbosity: Verbosity,
lib_verbosity: Verbosity,
strip_function_hash: bool,
is_panic_handler: bool,
colors: ColorScheme,
filters: Vec<Arc<FilterCallback>>,
should_print_addresses: bool,
}
impl Default for BacktracePrinter {
fn default() -> Self {
Self {
verbosity: Verbosity::from_env(),
lib_verbosity: Verbosity::lib_from_env(),
message: "The application panicked (crashed).".to_owned(),
strip_function_hash: false,
colors: ColorScheme::classic(),
is_panic_handler: false,
filters: vec![Arc::new(default_frame_filter)],
should_print_addresses: false,
}
}
}
impl std::fmt::Debug for BacktracePrinter {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
fmt.debug_struct("Settings")
.field("message", &self.message)
.field("verbosity", &self.verbosity)
.field("lib_verbosity", &self.lib_verbosity)
.field("strip_function_hash", &self.strip_function_hash)
.field("is_panic_handler", &self.is_panic_handler)
.field("print_addresses", &self.should_print_addresses)
.field("colors", &self.colors)
.finish()
}
}
/// Builder functions.
impl BacktracePrinter {
/// Alias for `BacktracePrinter::default`.
pub fn new() -> Self {
Self::default()
}
/// Alter the color scheme.
///
/// Defaults to `ColorScheme::classic()`.
pub fn color_scheme(mut self, colors: ColorScheme) -> Self {
self.colors = colors;
self
}
/// Controls the "greeting" message of the panic.
///
/// Defaults to `"The application panicked (crashed)"`.
pub fn message(mut self, message: impl Into<String>) -> Self {
self.message = message.into();
self
}
/// Controls the verbosity level used when installed as panic handler.
///
/// Defaults to `Verbosity::from_env()`.
pub fn verbosity(mut self, v: Verbosity) -> Self {
self.verbosity = v;
self
}
/// Controls the lib verbosity level used when formatting user provided traces.
///
/// Defaults to `Verbosity::lib_from_env()`.
pub fn lib_verbosity(mut self, v: Verbosity) -> Self {
self.lib_verbosity = v;
self
}
/// Controls whether the hash part of functions is stripped.
///
/// Defaults to `false`.
pub fn strip_function_hash(mut self, strip: bool) -> Self {
self.strip_function_hash = strip;
self
}
/// Controls whether addresses (or module offsets if available) should be printed.
///
/// Defaults to `false`.
pub fn print_addresses(mut self, val: bool) -> Self {
self.should_print_addresses = val;
self
}
/// Add a custom filter to the set of frame filters
///
/// Filters are run in the order they are added.
///
/// # Example
///
/// ```rust
/// use color_backtrace::{default_output_stream, BacktracePrinter};
///
/// BacktracePrinter::new()
/// .add_frame_filter(Box::new(|frames| {
/// frames.retain(|x| matches!(&x.name, Some(n) if !n.starts_with("blabla")))
/// }))
/// .install(default_output_stream());
/// ```
pub fn add_frame_filter(mut self, filter: Box<FilterCallback>) -> Self {
self.filters.push(filter.into());
self
}
/// Clears all filters associated with this printer, including the default filter
pub fn clear_frame_filters(mut self) -> Self {
self.filters.clear();
self
}
}
/// Routines for putting the panic printer to use.
impl BacktracePrinter {
/// Install the `color_backtrace` handler with default settings.
///
/// Output streams can be created via `default_output_stream()` or
/// using any other stream that implements
/// [`termcolor::WriteColor`](termcolor::WriteColor).
pub fn install(self, out: impl WriteColor + Sync + Send + 'static) {
std::panic::set_hook(self.into_panic_handler(out))
}
/// Create a `color_backtrace` panic handler from this panic printer.
///
/// This can be used if you want to combine the handler with other handlers.
pub fn into_panic_handler(
mut self,
out: impl WriteColor + Sync + Send + 'static,
) -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
self.is_panic_handler = true;
let out_stream_mutex = Mutex::new(out);
Box::new(move |pi| {
let mut lock = out_stream_mutex.lock().unwrap();
if let Err(e) = self.print_panic_info(pi, &mut *lock) {
// Panicking while handling a panic would send us into a deadlock,
// so we just print the error to stderr instead.
eprintln!("Error while printing panic: {:?}", e);
}
})
}
/// Pretty-prints a [`backtrace::Backtrace`](backtrace::Backtrace) to an output stream.
pub fn print_trace(&self, trace: &backtrace::Backtrace, out: &mut impl WriteColor) -> IOResult {
writeln!(out, "{:━^80}", " BACKTRACE ")?;
// Collect frame info.
let frames: Vec<_> = trace
.frames()
.iter()
.flat_map(|frame| frame.symbols().iter().map(move |sym| (frame.ip(), sym)))
.zip(1usize..)
.map(|((ip, sym), n)| Frame {
name: sym.name().map(|x| x.to_string()),
lineno: sym.lineno(),
filename: sym.filename().map(|x| x.into()),
n,
ip: ip as usize,
_private_ctor: (),
})
.collect();
let mut filtered_frames = frames.iter().collect();
match env::var("COLORBT_SHOW_HIDDEN").ok().as_deref() {
Some("1") | Some("on") | Some("y") => (),
_ => {
for filter in &self.filters {
filter(&mut filtered_frames);
}
}
}
if filtered_frames.is_empty() {
// TODO: Would probably look better centered.
return writeln!(out, "<empty backtrace>");
}
// Don't let filters mess with the order.
filtered_frames.sort_by_key(|x| x.n);
macro_rules! print_hidden {
($n:expr) => {
out.set_color(&self.colors.frames_omitted_msg)?;
let n = $n;
let text = format!(
"{decorator} {n} frame{plural} hidden {decorator}",
n = n,
plural = if n == 1 { "" } else { "s" },
decorator = "⋮",
);
writeln!(out, "{:^80}", text)?;
out.reset()?;
};
}
let mut last_n = 0;
for frame in &filtered_frames {
let frame_delta = frame.n - last_n - 1;
if frame_delta != 0 {
print_hidden!(frame_delta);
}
frame.print(frame.n, out, self)?;
last_n = frame.n;
}
let last_filtered_n = filtered_frames.last().unwrap().n;
let last_unfiltered_n = frames.last().unwrap().n;
if last_filtered_n < last_unfiltered_n {
print_hidden!(last_unfiltered_n - last_filtered_n);
}
Ok(())
}
/// Pretty-print a backtrace to a `String`, using VT100 color codes.
pub fn format_trace_to_string(&self, trace: &backtrace::Backtrace) -> IOResult<String> {
// TODO: should we implicitly enable VT100 support on Windows here?
let mut ansi = Ansi::new(vec![]);
self.print_trace(trace, &mut ansi)?;
Ok(String::from_utf8(ansi.into_inner()).unwrap())
}
/// Pretty-prints a [`PanicInfo`](PanicInfo) struct to an output stream.
pub fn print_panic_info(&self, pi: &PanicInfo, out: &mut impl WriteColor) -> IOResult {
out.set_color(&self.colors.header)?;
writeln!(out, "{}", self.message)?;
out.reset()?;
// Print panic message.
let payload = pi
.payload()
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| pi.payload().downcast_ref::<&str>().cloned())
.unwrap_or("<non string panic payload>");
write!(out, "Message: ")?;
out.set_color(&self.colors.msg_loc_prefix)?;
writeln!(out, "{}", payload)?;
out.reset()?;
// If known, print panic location.
write!(out, "Location: ")?;
if let Some(loc) = pi.location() {
out.set_color(&self.colors.src_loc)?;
write!(out, "{}", loc.file())?;
out.set_color(&self.colors.src_loc_separator)?;
write!(out, ":")?;
out.set_color(&self.colors.src_loc)?;
writeln!(out, "{}", loc.line())?;
out.reset()?;
} else {
writeln!(out, "<unknown>")?;
}
// Print some info on how to increase verbosity.
if self.current_verbosity() == Verbosity::Minimal {
write!(out, "\nBacktrace omitted.\n\nRun with ")?;
out.set_color(&self.colors.env_var)?;
write!(out, "RUST_BACKTRACE=1")?;
out.reset()?;
writeln!(out, " environment variable to display it.")?;
} else {
// This text only makes sense if frames are displayed.
write!(out, "\nRun with ")?;
out.set_color(&self.colors.env_var)?;
write!(out, "COLORBT_SHOW_HIDDEN=1")?;
out.reset()?;
writeln!(out, " environment variable to disable frame filtering.")?;
}
if self.current_verbosity() <= Verbosity::Medium {
write!(out, "Run with ")?;
out.set_color(&self.colors.env_var)?;
write!(out, "RUST_BACKTRACE=full")?;
out.reset()?;
writeln!(out, " to include source snippets.")?;
}
if self.current_verbosity() >= Verbosity::Medium {
self.print_trace(&backtrace::Backtrace::new(), out)?;
}
Ok(())
}
fn current_verbosity(&self) -> Verbosity {
if self.is_panic_handler {
self.verbosity
} else {
self.lib_verbosity
}
}
fn should_print_addresses(&self) -> bool {
self.should_print_addresses
}
}
// ============================================================================================== //
// [Deprecated routines for backward compat] //
// ============================================================================================== //
#[deprecated(since = "0.4.0", note = "Use `BacktracePrinter::print_trace` instead`")]
pub fn print_backtrace(trace: &backtrace::Backtrace, s: &mut BacktracePrinter) -> IOResult {
s.print_trace(trace, &mut default_output_stream())
}
#[deprecated(
since = "0.4.0",
note = "Use `BacktracePrinter::print_panic_info` instead`"
)]
pub fn print_panic_info(pi: &PanicInfo, s: &mut BacktracePrinter) -> IOResult {
s.print_panic_info(pi, &mut default_output_stream())
}
// ============================================================================================== //
| true |
0ea10b8d38f349210768075b647b8350bb3d1299
|
Rust
|
LaplaceKorea/sml-compiler
|
/crates/sml-util/src/interner.rs
|
UTF-8
| 4,270 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
use std::pin::Pin;
macro_rules! globals {
(@step $idx:expr, ) => {
pub const S_TOTAL_GLOBALS: usize = $idx;
};
(@step $idx:expr, $it:ident, $($rest:ident,)*) => {
pub const $it: Symbol = Symbol::Builtin($idx as u32);
globals!(@step $idx+1usize, $($rest,)*);
};
($($name:ident),+) => {
globals!(@step 0usize, $($name,)*);
};
}
globals!(
S_ABSTYPE,
S_AND,
S_ANDALSO,
S_AS,
S_CASE,
S_DATATYPE,
S_DO,
S_ELSE,
S_END,
S_EXCEPTION,
S_FN,
S_FUN,
S_FUNCTOR,
S_HANDLE,
S_IF,
S_IN,
S_INFIX,
S_INFIXR,
S_LET,
S_LOCAL,
S_NONFIX,
S_OF,
S_OP,
S_OPEN,
S_ORELSE,
S_PRIM,
S_RAISE,
S_REC,
S_THEN,
S_TYPE,
S_VAL,
S_WITH,
S_WITHTYPE,
S_WHILE,
S_SIG,
S_SIGNATURE,
S_STRUCT,
S_STRUCTURE,
S_DOT,
S_FLEX,
S_ARROW,
S_DARROW,
S_COLON,
S_BAR,
S_EQUAL,
S_OPAQUE,
S_MUL,
S_DIV,
S_PLUS,
S_MINUS,
S_INT,
S_CHAR,
S_STRING,
S_REF,
S_LIST,
S_BOOL,
S_EXN,
S_NIL,
S_CONS,
S_TRUE,
S_FALSE,
S_UNIT,
S_MATCH,
S_BIND
);
const BUILTIN_STRS: [&'static str; S_TOTAL_GLOBALS as usize] = [
"abstype",
"and",
"andalso",
"as",
"case",
"datatype",
"do",
"else",
"end",
"exception",
"fn",
"fun",
"functor",
"handle",
"if",
"in",
"infix",
"infixr",
"let",
"local",
"nonfix",
"of",
"op",
"open",
"orelse",
"primitive",
"raise",
"rec",
"then",
"type",
"val",
"with",
"withtype",
"while",
"sig",
"signature",
"struct",
"structure",
".",
"...",
"->",
"=>",
":",
"|",
"=",
":>",
"*",
"\\",
"+",
"-",
"int",
"char",
"string",
"ref",
"list",
"bool",
"exn",
"nil",
"::",
"true",
"false",
"unit",
"Match",
"Bind",
];
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum Symbol {
Builtin(u32),
Interned(u32),
Gensym(u32),
Tuple(u32),
}
impl Symbol {
pub const fn dummy() -> Self {
Symbol::Gensym(std::u32::MAX)
}
pub const fn gensym(n: u32) -> Symbol {
Symbol::Gensym(n)
}
pub fn builtin(self) -> bool {
match self {
Symbol::Builtin(_) => true,
_ => false,
}
}
pub const fn tuple_field(idx: u32) -> Symbol {
Symbol::Tuple(idx)
}
}
#[derive(Clone, PartialEq)]
pub struct Interner {
symbols: HashMap<&'static str, Symbol>,
strings: Vec<Pin<Box<str>>>,
}
impl Interner {
pub fn with_capacity(n: usize) -> Interner {
let mut i = Interner {
symbols: HashMap::with_capacity(n),
strings: Vec::with_capacity(n),
};
for (idx, builtin) in BUILTIN_STRS.iter().enumerate() {
i.symbols.insert(builtin, Symbol::Builtin(idx as u32));
}
i
}
pub fn intern(&mut self, s: &str) -> Symbol {
if let Some(sym) = self.symbols.get(s.as_ref() as &str) {
return *sym;
}
let sym = Symbol::Interned(self.strings.len() as u32);
let pinned = Pin::new(String::into_boxed_str(s.into()));
let ptr: &'static str = unsafe { std::mem::transmute(Pin::get_ref(pinned.as_ref())) };
self.strings.push(pinned);
self.symbols.insert(ptr, sym);
sym
}
pub fn get(&self, symbol: Symbol) -> Option<&str> {
match symbol {
Symbol::Interned(n) => self
.strings
.get(n as usize)
.map(|s| Pin::get_ref(s.as_ref())),
Symbol::Builtin(n) => BUILTIN_STRS.get(n as usize).copied(),
_ => None,
}
}
}
impl std::fmt::Debug for Symbol {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Symbol::Builtin(n) => f.write_str(&BUILTIN_STRS[*n as usize]),
Symbol::Tuple(n) => write!(f, "{}", n),
Symbol::Gensym(n) => write!(f, "${}", n),
_ => f.write_str("symbol"),
}
}
}
| true |
76c328e57b17da1bf8fadaa3a348173b0fdc19d6
|
Rust
|
pkafma-aon/LeetCode-Rust
|
/src/rotate_list.rs
|
UTF-8
| 3,852 | 3.71875 | 4 |
[
"WTFPL"
] |
permissive
|
impl Solution {
pub fn rotate_right(head: Option<Box<ListNode>>, mut k: i32) -> Option<Box<ListNode>> {
if head.is_none() {
return head;
}
let mut cur = &head;
let mut length = 0;
while let Some(next) = cur {
cur = &next.next;
length += 1;
}
// C 语言里很容易想到的一个高效做法是在这里将链表首尾相连, 然后再在第 length - k 个节点处分开
// 然而在 Rust 里就题目所给的结构而言(个人认为)似乎做不到:
// 如果存在这样一个链表, 那链表每一个节点的所有权都归属上一个节点的 .next 成员
// 那么根本无法访问这个链表, 因为栈上没有变量拥有任何节点的所有权, 就更不可能有引用了
// 换言之, 这样的玩意儿是应该立刻被 drop 掉的
k %= length;
if k != 0 {
// 找到新的头结点
let tail = cur;
cur = &head;
for _ in 0..(length - k) {
cur = &cur.as_ref().unwrap().next;
}
// 问: 能干掉 unsafe 吗
// 答: 不能
unsafe {
let cur = cur as *const _ as *mut Option<Box<ListNode>>;
let tail = tail as *const _ as *mut Option<Box<ListNode>>;
let mid = std::ptr::replace(cur, None);
std::ptr::replace(tail, head);
mid
}
} else {
head
}
}
pub fn rotate_right_safe(mut head: Option<Box<ListNode>>, mut k: i32) -> Option<Box<ListNode>> {
if head.is_none() {
return head;
}
let mut cur = &mut head;
let mut length = 0;
while let Some(next) = cur {
cur = &mut next.next;
length += 1;
}
k %= length;
if k != 0 {
// 找到新的头结点
cur = &mut head;
for _ in 0..(length - k) {
cur = &mut cur.as_mut().unwrap().next;
}
let mut mid = std::mem::replace(cur, None);
// 再次找到尾节点
let mut tail = &mut mid;
while let Some(next) = tail {
tail = &mut next.next;
}
// 首尾相连
let _ = std::mem::replace(tail, head);
mid
} else {
head
}
}
}
use crate::ListNode;
pub struct Solution;
#[cfg(test)]
mod tests {
use super::Solution;
use crate::linkedlist;
#[test]
fn test() {
assert_eq!(
Solution::rotate_right(linkedlist![1, 2, 3, 4, 5], 2),
linkedlist![4, 5, 1, 2, 3]
);
assert_eq!(
Solution::rotate_right(linkedlist![0, 1, 2], 4),
linkedlist![2, 0, 1]
);
assert_eq!(
Solution::rotate_right(linkedlist![], 0),
linkedlist![]
);
}
#[test]
fn test_safe() {
assert_eq!(
Solution::rotate_right_safe(linkedlist![1, 2, 3, 4, 5], 2),
linkedlist![4, 5, 1, 2, 3]
);
assert_eq!(
Solution::rotate_right_safe(linkedlist![0, 1, 2], 4),
linkedlist![2, 0, 1]
);
assert_eq!(
Solution::rotate_right_safe(linkedlist![], 0),
linkedlist![]
);
}
}
#[cfg(test)]
mod bench {
extern crate test;
use crate::linkedlist;
use super::Solution;
use self::test::Bencher;
#[bench]
fn _unsafe(b: &mut Bencher) {
b.iter(|| Solution::rotate_right(linkedlist![1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5));
}
#[bench]
fn safe(b: &mut Bencher) {
b.iter(|| Solution::rotate_right_safe(linkedlist![1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5));
}
}
| true |
c27451e17f9c9889316032b3653b4cde84674871
|
Rust
|
siku2/russ
|
/russ-internal-macro/src/derive/css_value/css_field.rs
|
UTF-8
| 8,623 | 2.8125 | 3 |
[] |
no_license
|
use super::args::{self, Args, FromArgs};
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned, ToTokens};
use syn::{Attribute, ExprPath, Field, Ident, LitStr, Path, Type};
pub struct FieldAttr {
attr: Attribute,
pub prefix: Option<LitStr>,
pub suffix: Option<LitStr>,
pub write_fn: Option<LitStr>,
pub option: bool,
pub iter: bool,
pub iter_option: bool,
pub iter_separator: Option<LitStr>,
}
impl FieldAttr {
/// Assumes `io::Write` is in scope.
fn gen_write_str(s: &str) -> TokenStream {
quote! {
f.write_str(#s)?;
}
}
fn gen_write_separator(attr: &Option<Self>) -> TokenStream {
let iter_separator = attr
.as_ref()
.and_then(|attr| attr.iter_separator.as_ref())
.map_or_else(|| ",".to_string(), LitStr::value);
Self::gen_write_str(&iter_separator)
}
fn gen_write_prefix(attr: &Option<Self>) -> Option<TokenStream> {
attr.as_ref()
.and_then(|attr| attr.prefix.as_ref())
.map(|v| Self::gen_write_str(&v.value()))
}
fn gen_write_suffix(attr: &Option<Self>) -> Option<TokenStream> {
attr.as_ref()
.and_then(|attr| attr.suffix.as_ref())
.map(|v| Self::gen_write_str(&v.value()))
}
}
impl FromArgs for FieldAttr {
fn attr_path() -> &'static str {
"field"
}
fn from_args(attr: Attribute, args: &Args) -> syn::Result<Self> {
Ok(Self {
attr,
prefix: args.get_kwarg_str("prefix")?,
suffix: args.get_kwarg_str("suffix")?,
write_fn: args.get_kwarg_str("write_fn")?,
option: args.has_flag("option"),
iter: args.has_flag("iter"),
iter_option: args.has_flag("iter_option"),
iter_separator: args.get_kwarg_str("iter_separator")?,
})
}
}
impl ToTokens for FieldAttr {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.attr.to_tokens(tokens)
}
}
fn path_is_eq_to(path: &Path, name: &str) -> bool {
if let Some(last) = path.segments.last() {
last.ident == name
} else {
false
}
}
fn type_is_eq_to(ty: &Type, name: &str) -> bool {
match ty {
Type::Path(ty) => path_is_eq_to(&ty.path, name),
_ => false,
}
}
// TODO empty vectors can cause problems
pub struct CssField {
pub bind_ident: Ident,
pub attr: Option<FieldAttr>,
is_option: bool,
is_iter: bool,
}
impl CssField {
pub fn from_field(bind_ident: Ident, field: &Field) -> syn::Result<Self> {
let is_option;
let is_iter;
let attr: Option<FieldAttr> = args::parse_single_from_attrs(&field.attrs).transpose()?;
if let Some(attr) = &attr {
is_option = attr.option;
is_iter = attr.iter;
} else {
is_option = type_is_eq_to(&field.ty, "Option");
is_iter = type_is_eq_to(&field.ty, "Vec");
}
Ok(Self {
bind_ident,
attr,
is_option,
is_iter,
})
}
/// Assumes `io::Write` is in scope.
fn _gen_write_inner_value(&self, value_ident: &Ident) -> syn::Result<TokenStream> {
let Self {
bind_ident, attr, ..
} = self;
if let Some(FieldAttr {
write_fn: Some(write_fn),
..
}) = attr
{
let fn_path: ExprPath = write_fn.parse()?;
return Ok(quote! {
#fn_path(f, #value_ident)?;
});
}
if self.is_iter {
let write_separator = FieldAttr::gen_write_separator(attr);
Ok(quote_spanned! {bind_ident.span()=>
let mut __v_iter = ::std::iter::IntoIterator::into_iter(#value_ident);
if let ::std::option::Option::Some(__v) = __v_iter.next() {
::russ_internal::WriteValue::write_value(__v, f)?;
}
for __v in __v_iter {
#write_separator
::russ_internal::WriteValue::write_value(__v, f)?;
}
})
} else if matches!(
attr,
Some(FieldAttr {
iter_option: true, ..
})
) {
let write_separator = FieldAttr::gen_write_separator(attr);
Ok(quote_spanned! {bind_ident.span()=>
let mut __v_iter = ::std::iter::IntoIterator::into_iter(#value_ident);
for __maybe_v in &mut __v_iter {
if let ::std::option::Option::Some(__v) = __maybe_v {
::russ_internal::WriteValue::write_value(__v, f)?;
break;
}
}
for __maybe_v in __v_iter {
if let ::std::option::Option::Some(__v) = __maybe_v {
#write_separator
::russ_internal::WriteValue::write_value(__v, f)?;
}
}
})
} else {
Ok(quote_spanned! {bind_ident.span()=>
::russ_internal::WriteValue::write_value(#value_ident, f)?;
})
}
}
/// Assumes `io::Write` is in scope.
fn gen_write_value(&self, value_ident: &Ident) -> syn::Result<TokenStream> {
let write_value = self._gen_write_inner_value(value_ident)?;
let write_prefix = FieldAttr::gen_write_prefix(&self.attr);
let write_suffix = FieldAttr::gen_write_suffix(&self.attr);
Ok(quote! {
#write_prefix
#write_value
#write_suffix
})
}
/// Assumes `io::Write` is in scope.
fn gen_write_with_before_write(&self, tokens: &TokenStream) -> syn::Result<TokenStream> {
let Self {
bind_ident,
is_option,
is_iter,
..
} = self;
assert!(
!(*is_option && *is_iter),
"can't be `is_iter` and `option` at the same time"
);
if *is_option {
let ident = Ident::new("__v", bind_ident.span());
let write_value = self.gen_write_value(&ident)?;
// using a semicolon at the end of the if statement to suppress `clippy::suspicious_else_formatting`
Ok(quote_spanned! {bind_ident.span()=>
if let ::std::option::Option::Some(#ident) = #bind_ident {
#tokens
#write_value
};
})
} else if *is_iter {
let write_value = self.gen_write_value(bind_ident)?;
Ok(quote_spanned! {bind_ident.span()=>
if !(#bind_ident).is_empty() {
#tokens
#write_value
};
})
} else {
let write_value = self.gen_write_value(bind_ident)?;
Ok(quote_spanned! {bind_ident.span()=>
#tokens
#write_value
})
}
}
/// Assumes `io::Write` is in scope.
pub fn gen_write(&self) -> syn::Result<TokenStream> {
self.gen_write_with_before_write("e! {})
}
}
/// Assumes `io::Write` is in scope.
pub fn gen_join_fields(fields: &[CssField], separator: &str) -> syn::Result<TokenStream> {
gen_join_fields_with_write_separator(
fields,
quote! {
f.write_str(#separator)?;
},
)
}
/// Assumes `io::Write` is in scope.
pub fn gen_join_fields_with_write_separator(
fields: &[CssField],
write_separator: impl ToTokens,
) -> syn::Result<TokenStream> {
if fields.iter().all(|field| !field.is_option) {
let write_value_vec = fields
.iter()
.map(|field| field.gen_write_value(&field.bind_ident))
.collect::<Result<Vec<_>, _>>()?;
let tokens = if let Some((first, others)) = write_value_vec.split_first() {
quote! {
#first
#(
#write_separator
#others
)*
}
} else {
quote! {}
};
return Ok(tokens);
}
let before_write = quote! {
if __wrote_first {
#write_separator
} else {
__wrote_first = true;
};
};
let write_values = fields
.iter()
.map(|field| field.gen_write_with_before_write(&before_write))
.collect::<Result<TokenStream, _>>()?;
Ok(quote! {
let mut __wrote_first = false;
#write_values
})
}
| true |
c207b0b463d3d45a211e5e82d4c9110c28483168
|
Rust
|
Nauscar/determinate
|
/src/lib.rs
|
UTF-8
| 3,199 | 2.515625 | 3 |
[] |
no_license
|
use proc_macro::TokenStream;
use quote::quote;
use syn::fold::Fold;
use syn::parse::{Parse, ParseStream, Result};
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{parse_macro_input, parse_quote, ItemFn, Pat};
struct Determinate;
impl Parse for Determinate {
fn parse(_input: ParseStream) -> Result<Self> {
Ok(Determinate {})
}
}
impl Fold for Determinate {
fn fold_item_fn(&mut self, input: ItemFn) -> ItemFn {
let ItemFn {
attrs,
vis,
sig,
block,
} = input;
let inputs = &sig.inputs;
let output = &sig.output;
let stmts = block.stmts.to_owned();
let output_type = match output {
syn::ReturnType::Default => None,
syn::ReturnType::Type(_, output_type) => Some(output_type),
};
let future_type = match output_type {
Some(output_type) => quote! {dyn Future<Output = #output_type>},
None => quote! { dyn Future<Output = ()> },
};
let mut input_idents = Punctuated::<Box<Pat>, Comma>::new();
for input in inputs.iter() {
match input {
syn::FnArg::Typed(pat_type) => input_idents.push(pat_type.pat.clone()),
syn::FnArg::Receiver(_) => continue,
}
}
let mut block = block;
block.stmts = parse_quote! {
use std::pin::Pin;
use futures::{executor::block_on, future::join_all, Future};
let f = |#inputs| #output { #(#stmts)* };
let wrapper = |f: fn(#inputs) #output| -> Pin<Box<#future_type>> {
Box::pin(async move { f(#input_idents) })
};
let mut futures = vec![];
for _ in 0..num_cpus::get() {
futures.push(wrapper(f));
}
let future = async { join_all(futures).await };
let values = block_on(future);
assert!(values.iter().all(|&item| item == values[0]));
values[0]
};
ItemFn {
attrs,
vis,
sig,
block,
}
}
}
#[proc_macro_attribute]
pub fn determinate(attr: TokenStream, item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as ItemFn);
let mut determinate = parse_macro_input!(attr as Determinate);
let output = determinate.fold_item_fn(input);
TokenStream::from(quote!(#output))
}
#[proc_macro_attribute]
pub fn indeterminate(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as ItemFn);
let ItemFn {
attrs,
vis,
sig,
block,
} = input;
let stmts = &block.stmts;
let output = &sig.output;
let output_type = match output {
syn::ReturnType::Default => None,
syn::ReturnType::Type(_, output_type) => Some(output_type),
};
TokenStream::from(quote! {
#(#attrs)* #vis #sig {
use once_cell::sync::Lazy;
static RESULT: Lazy<#output_type> = Lazy::new(|| { #(#stmts)* });
*RESULT
}
})
}
| true |
9462c307861c71dec476ef813c097d032ca91132
|
Rust
|
kunalb/AoC2020
|
/src/bin/day6.rs
|
UTF-8
| 1,240 | 3.34375 | 3 |
[] |
no_license
|
use std::collections::HashSet;
use std::env;
use std::error::Error;
use std::io::{self, Read};
fn process<F>(buffer: &str, f: F) -> usize
where
F: Fn(&str) -> usize,
{
buffer.split("\n\n").map(f).fold(0, |a, b| a + b)
}
fn solve1(buffer: &str) -> usize {
process(buffer, |x| {
x.chars()
.filter(|&x| x != '\n')
.collect::<HashSet<char>>()
.len()
})
}
fn solve2(buffer: &str) -> usize {
process(buffer, |x| {
x.lines()
.map(|x| x.chars().collect::<HashSet<char>>())
.fold(('a'..='z').collect::<HashSet<char>>(), |x, y| {
x.intersection(&y).copied().collect::<HashSet<char>>()
})
.len()
})
}
fn main() -> Result<(), Box<dyn Error>> {
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer)?;
let args: Vec<String> = env::args().collect();
if args.len() > 1 && args[1] == "2" {
println!("{}", solve2(&buffer));
} else {
println!("{}", solve1(&buffer));
}
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test2() {
let input = "abc
a
b
c
ab
ac
a
a
a
a
b";
assert_eq!(solve2(&input), 6);
}
}
| true |
ea77e8347a7f98005f12f061b68dd8af4fa2795e
|
Rust
|
Censkh/Maxwell
|
/src/compiler/transform/plugin.rs
|
UTF-8
| 760 | 2.703125 | 3 |
[] |
no_license
|
use super::super::{Chunk};
use super::super::ast::statement::StatementNode;
use super::super::ast::expression::ExpressionNode;
use std::result::Result;
use std::error::Error;
use std::hash::{Hash,Hasher};
pub trait Plugin {
fn handle(&self, pass: &mut PluginPass) -> Result<String, Box<Error>>;
fn get_name(&self) -> &str;
}
impl Hash for Plugin {
fn hash<H: Hasher>(&self, state: &mut H) {
self.get_name().hash(state);
}
}
impl Eq for Plugin {}
impl PartialEq for Plugin {
fn eq(&self, other: &Plugin) -> bool {
return self.get_name().eq(other.get_name());
}
}
pub enum PluginPass<'a> {
EmitChunk(&'a mut Chunk),
StatementNodeEmit(&'a mut StatementNode),
ExpressionNodeEmit(&'a mut ExpressionNode)
}
| true |
1d7c9da32b35d85aaf8f97e9b9ea80b22f5ca66c
|
Rust
|
shobhitchittora/learn-rust
|
/variables/src/main.rs
|
UTF-8
| 1,038 | 3.984375 | 4 |
[] |
no_license
|
fn main() {
// Mutability
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
// Constants
const MY_CONST: u32 = 100_00;
println!("MY_CONT = {}", MY_CONST);
// Shadowing
let spaces = " ";
let spaces = spaces.len();
println!("Len = {}", spaces);
control_flow();
}
/**
* Data Types
*
* Scalar -->
* 1. Integers - u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, isize, usize
* 2. Floating-point - f32, f64
* 3. Boolean - bool
* 4. Char - 'A' (Unicode Scalar values)
*
* Compound -->
* 1. Tuples - let tup: (i32, u64, char) = (1, 123, 'a');
* 2. Arrays - let arr: [i32; 5] = [1, 2, 3, 4, 5];
*/
fn control_flow() {
let number = 3;
let res = if number != 0 { number } else { 0 };
assert_eq!(number, 3);
println!("res = {}", res);
let a = [1, 2, 3];
for elem in a.iter() {
println!("{}", elem);
}
for number in 4..10 {
println!("{}!", number);
}
}
| true |
5e9b8c2eac061345206947695411ee8e381d6b19
|
Rust
|
input-output-hk/vit-kedqr
|
/src/lib.rs
|
UTF-8
| 4,660 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
use chain_crypto::{Ed25519Extended, SecretKey, SecretKeyError};
use image::{DynamicImage, ImageBuffer, Luma};
use qrcode::{
render::{svg, unicode},
EcLevel, QrCode,
};
use std::fmt;
use std::fs::File;
use std::io::{self, prelude::*};
use std::path::Path;
use symmetric_cipher::{decrypt, encrypt, Error as SymmetricCipherError};
use thiserror::Error;
pub struct KeyQrCode {
inner: QrCode,
}
#[derive(Error, Debug)]
pub enum KeyQrCodeError {
#[error("encryption-decryption protocol error")]
SymmetricCipher(#[from] SymmetricCipherError),
#[error("io error")]
Io(#[from] io::Error),
#[error("invalid secret key")]
SecretKey(#[from] SecretKeyError),
#[error("couldn't decode QR code")]
QrDecodeError(#[from] QrDecodeError),
#[error("failed to decode hex")]
HexDecodeError(#[from] hex::FromHexError),
}
#[derive(Error, Debug)]
pub enum QrDecodeError {
#[error("couldn't decode QR code")]
DecodeError(#[from] quircs::DecodeError),
#[error("couldn't extract QR code")]
ExtractError(#[from] quircs::ExtractError),
#[error("QR code payload is not valid uf8")]
NonUtf8Payload,
}
impl KeyQrCode {
pub fn generate(key: SecretKey<Ed25519Extended>, password: &[u8]) -> Self {
let secret = key.leak_secret();
let rng = rand::thread_rng();
// this won't fail because we already know it's an ed25519extended key,
// so it is safe to unwrap
let enc = encrypt(password, secret.as_ref(), rng).unwrap();
// Using binary would make the QR codes more compact and probably less
// prone to scanning errors.
let enc_hex = hex::encode(enc);
let inner = QrCode::with_error_correction_level(&enc_hex, EcLevel::H).unwrap();
KeyQrCode { inner }
}
pub fn write_svg(&self, path: impl AsRef<Path>) -> Result<(), KeyQrCodeError> {
let mut out = File::create(path)?;
let svg_file = self
.inner
.render()
.quiet_zone(true)
.dark_color(svg::Color("#000000"))
.light_color(svg::Color("#ffffff"))
.build();
out.write_all(svg_file.as_bytes())?;
out.flush()?;
Ok(())
}
pub fn to_img(&self) -> ImageBuffer<Luma<u8>, Vec<u8>> {
let qr = &self.inner;
let img = qr.render::<Luma<u8>>()
.build();
img
}
pub fn decode(
img: DynamicImage,
password: &[u8],
) -> Result<Vec<SecretKey<Ed25519Extended>>, KeyQrCodeError> {
let mut decoder = quircs::Quirc::default();
let img = img.into_luma8();
let codes = decoder.identify(img.width() as usize, img.height() as usize, &img);
codes
.map(|code| -> Result<_, KeyQrCodeError> {
let decoded = code
.map_err(QrDecodeError::ExtractError)
.and_then(|c| c.decode().map_err(QrDecodeError::DecodeError))?;
// TODO: I actually don't know if this can fail
let h = std::str::from_utf8(&decoded.payload)
.map_err(|_| QrDecodeError::NonUtf8Payload)?;
let encrypted_bytes = hex::decode(h)?;
let key = decrypt(password, &encrypted_bytes)?;
Ok(SecretKey::from_binary(&key)?)
})
.collect()
}
}
impl fmt::Display for KeyQrCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let qr_img = self
.inner
.render::<unicode::Dense1x2>()
.quiet_zone(true)
.dark_color(unicode::Dense1x2::Light)
.light_color(unicode::Dense1x2::Dark)
.build();
write!(f, "{}", qr_img)
}
}
#[cfg(test)]
mod tests {
use super::*;
// TODO: Improve into an integration test using a temporary directory.
// Leaving here as an example.
#[test]
fn generate_svg() {
const PASSWORD: &[u8] = &[1, 2, 3, 4];
let sk = SecretKey::generate(rand::thread_rng());
let qr = KeyQrCode::generate(sk, PASSWORD);
qr.write_svg("qr-code.svg").unwrap();
}
#[test]
fn encode_decode() {
const PASSWORD: &[u8] = &[1, 2, 3, 4];
let sk = SecretKey::generate(rand::thread_rng());
let qr = KeyQrCode::generate(sk.clone(), PASSWORD);
let img = qr.to_img();
// img.save("qr.png").unwrap();
assert_eq!(
sk.leak_secret().as_ref(),
KeyQrCode::decode(DynamicImage::ImageLuma8(img), PASSWORD).unwrap()[0]
.clone()
.leak_secret()
.as_ref()
);
}
}
| true |
fed32eea1a569395a5d8762d36196ef00152e286
|
Rust
|
MPTGits/QuestGiverRustGame
|
/target/debug/build/wayland-protocols-ac1a20a560d181a7/out/wlr-foreign-toplevel-management-v1_c_client_api.rs
|
UTF-8
| 35,011 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#[doc = "list and control opened apps\n\nThe purpose of this protocol is to enable the creation of taskbars\nand docks by providing them with a list of opened applications and\nletting them request certain actions on them, like maximizing, etc.\n\nAfter a client binds the zwlr_foreign_toplevel_manager_v1, each opened\ntoplevel window will be sent via the toplevel event"]
pub mod zwlr_foreign_toplevel_manager_v1 {
use super::sys::client::*;
use super::sys::common::{wl_argument, wl_array, wl_interface};
use super::{
AnonymousObject, Argument, ArgumentType, Interface, Message, MessageDesc, MessageGroup,
NewProxy, Object, ObjectMetadata, Proxy,
};
pub enum Request {
#[doc = "stop sending events\n\nIndicates the client no longer wishes to receive events for new toplevels.\nHowever the compositor may emit further toplevel_created events, until\nthe finished event is emitted.\n\nThe client must not send any more requests after this one."]
Stop,
}
impl super::MessageGroup for Request {
const MESSAGES: &'static [super::MessageDesc] = &[super::MessageDesc {
name: "stop",
since: 1,
signature: &[],
}];
type Map = super::ProxyMap;
fn is_destructor(&self) -> bool {
match *self {
_ => false,
}
}
fn opcode(&self) -> u16 {
match *self {
Request::Stop => 0,
}
}
fn child<Meta: ObjectMetadata>(
opcode: u16,
version: u32,
meta: &Meta,
) -> Option<Object<Meta>> {
match opcode {
_ => None,
}
}
fn from_raw(msg: Message, map: &mut Self::Map) -> Result<Self, ()> {
panic!("Request::from_raw can not be used Client-side.")
}
fn into_raw(self, sender_id: u32) -> Message {
match self {
Request::Stop => Message {
sender_id: sender_id,
opcode: 0,
args: vec![],
},
}
}
unsafe fn from_raw_c(
obj: *mut ::std::os::raw::c_void,
opcode: u32,
args: *const wl_argument,
) -> Result<Request, ()> {
panic!("Request::from_raw_c can not be used Client-side.")
}
fn as_raw_c_in<F, T>(self, f: F) -> T
where
F: FnOnce(u32, &mut [wl_argument]) -> T,
{
match self {
Request::Stop => {
let mut _args_array: [wl_argument; 0] = unsafe { ::std::mem::zeroed() };
f(0, &mut _args_array)
}
}
}
}
pub enum Event {
#[doc = "a toplevel has been created\n\nThis event is emitted whenever a new toplevel window is created. It\nis emitted for all toplevels, regardless of the app that has created\nthem.\n\nAll initial details of the toplevel(title, app_id, states, etc.) will\nbe sent immediately after this event via the corresponding events in\nzwlr_foreign_toplevel_handle_v1."]
Toplevel {
toplevel: NewProxy<super::zwlr_foreign_toplevel_handle_v1::ZwlrForeignToplevelHandleV1>,
},
#[doc = "the compositor has finished with the toplevel manager\n\nThis event indicates that the compositor is done sending events to the\nzwlr_foreign_toplevel_manager_v1. The server will destroy the object\nimmediately after sending this request, so it will become invalid and\nthe client should free any resources associated with it."]
Finished,
}
impl super::MessageGroup for Event {
const MESSAGES: &'static [super::MessageDesc] = &[
super::MessageDesc {
name: "toplevel",
since: 1,
signature: &[super::ArgumentType::NewId],
},
super::MessageDesc {
name: "finished",
since: 1,
signature: &[],
},
];
type Map = super::ProxyMap;
fn is_destructor(&self) -> bool {
match *self {
_ => false,
}
}
fn opcode(&self) -> u16 {
match *self {
Event::Toplevel { .. } => 0,
Event::Finished => 1,
}
}
fn child<Meta: ObjectMetadata>(
opcode: u16,
version: u32,
meta: &Meta,
) -> Option<Object<Meta>> {
match opcode {
0 => Some(Object::from_interface::<
super::zwlr_foreign_toplevel_handle_v1::ZwlrForeignToplevelHandleV1,
>(version, meta.child())),
_ => None,
}
}
fn from_raw(msg: Message, map: &mut Self::Map) -> Result<Self, ()> {
match msg.opcode {
0 => {
let mut args = msg.args.into_iter();
Ok(Event::Toplevel {
toplevel: {
if let Some(Argument::NewId(val)) = args.next() {
map.get_new(val).ok_or(())?
} else {
return Err(());
}
},
})
}
1 => Ok(Event::Finished),
_ => Err(()),
}
}
fn into_raw(self, sender_id: u32) -> Message {
panic!("Event::into_raw can not be used Client-side.")
}
unsafe fn from_raw_c(
obj: *mut ::std::os::raw::c_void,
opcode: u32,
args: *const wl_argument,
) -> Result<Event, ()> {
match opcode {
0 => {
let _args = ::std::slice::from_raw_parts(args, 1);
Ok(Event::Toplevel {
toplevel: NewProxy::<
super::zwlr_foreign_toplevel_handle_v1::ZwlrForeignToplevelHandleV1,
>::from_c_ptr(_args[0].o as *mut _),
})
}
1 => Ok(Event::Finished),
_ => return Err(()),
}
}
fn as_raw_c_in<F, T>(self, f: F) -> T
where
F: FnOnce(u32, &mut [wl_argument]) -> T,
{
panic!("Event::as_raw_c_in can not be used Client-side.")
}
}
pub struct ZwlrForeignToplevelManagerV1;
impl Interface for ZwlrForeignToplevelManagerV1 {
type Request = Request;
type Event = Event;
const NAME: &'static str = "zwlr_foreign_toplevel_manager_v1";
const VERSION: u32 = 1;
fn c_interface() -> *const wl_interface {
unsafe { &super::super::c_interfaces::zwlr_foreign_toplevel_manager_v1_interface }
}
}
pub trait RequestsTrait {
#[doc = "stop sending events\n\nIndicates the client no longer wishes to receive events for new toplevels.\nHowever the compositor may emit further toplevel_created events, until\nthe finished event is emitted.\n\nThe client must not send any more requests after this one."]
fn stop(&self) -> ();
}
impl RequestsTrait for Proxy<ZwlrForeignToplevelManagerV1> {
fn stop(&self) -> () {
let msg = Request::Stop;
self.send(msg);
}
}
#[doc = r" The minimal object version supporting this request"]
pub const REQ_STOP_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_TOPLEVEL_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_FINISHED_SINCE: u16 = 1u16;
}
#[doc = "an opened toplevel\n\nA zwlr_foreign_toplevel_handle_v1 object represents an opened toplevel\nwindow. Each app may have multiple opened toplevels.\n\nEach toplevel has a list of outputs it is visible on, conveyed to the\nclient with the output_enter and output_leave events."]
pub mod zwlr_foreign_toplevel_handle_v1 {
use super::sys::client::*;
use super::sys::common::{wl_argument, wl_array, wl_interface};
use super::{
AnonymousObject, Argument, ArgumentType, Interface, Message, MessageDesc, MessageGroup,
NewProxy, Object, ObjectMetadata, Proxy,
};
#[doc = "types of states on the toplevel\n\nThe different states that a toplevel can have. These have the same meaning\nas the states with the same names defined in xdg-toplevel"]
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum State {
#[doc = "the toplevel is maximized"]
Maximized = 0,
#[doc = "the toplevel is minimized"]
Minimized = 1,
#[doc = "the toplevel is active"]
Activated = 2,
}
impl State {
pub fn from_raw(n: u32) -> Option<State> {
match n {
0 => Some(State::Maximized),
1 => Some(State::Minimized),
2 => Some(State::Activated),
_ => Option::None,
}
}
pub fn to_raw(&self) -> u32 {
*self as u32
}
}
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Error {
#[doc = "the provided rectangle is invalid"]
InvalidRectangle = 0,
}
impl Error {
pub fn from_raw(n: u32) -> Option<Error> {
match n {
0 => Some(Error::InvalidRectangle),
_ => Option::None,
}
}
pub fn to_raw(&self) -> u32 {
*self as u32
}
}
pub enum Request {
#[doc = "requests that the toplevel be maximized\n\nRequests that the toplevel be maximized. If the maximized state actually\nchanges, this will be indicated by the state event."]
SetMaximized,
#[doc = "requests that the toplevel be unmaximized\n\nRequests that the toplevel be unmaximized. If the maximized state actually\nchanges, this will be indicated by the state event."]
UnsetMaximized,
#[doc = "requests that the toplevel be minimized\n\nRequests that the toplevel be minimized. If the minimized state actually\nchanges, this will be indicated by the state event."]
SetMinimized,
#[doc = "requests that the toplevel be unminimized\n\nRequests that the toplevel be unminimized. If the minimized state actually\nchanges, this will be indicated by the state event."]
UnsetMinimized,
#[doc = "activate the toplevel\n\nRequest that this toplevel be activated on the given seat.\nThere is no guarantee the toplevel will be actually activated."]
Activate { seat: Proxy<super::wl_seat::WlSeat> },
#[doc = "request that the toplevel be closed\n\nSend a request to the toplevel to close itself. The compositor would\ntypically use a shell-specific method to carry out this request, for\nexample by sending the xdg_toplevel.close event. However, this gives\nno guarantees the toplevel will actually be destroyed. If and when\nthis happens, the zwlr_foreign_toplevel_handle_v1.closed event will\nbe emitted."]
Close,
#[doc = "the rectangle which represents the toplevel\n\nThe rectangle of the surface specified in this request corresponds to\nthe place where the app using this protocol represents the given toplevel.\nIt can be used by the compositor as a hint for some operations, e.g\nminimizing. The client is however not required to set this, in which\ncase the compositor is free to decide some default value.\n\nIf the client specifies more than one rectangle, only the last one is\nconsidered.\n\nThe dimensions are given in surface-local coordinates.\nSetting width=height=0 removes the already-set rectangle."]
SetRectangle {
surface: Proxy<super::wl_surface::WlSurface>,
x: i32,
y: i32,
width: i32,
height: i32,
},
#[doc = "destroy the zwlr_foreign_toplevel_handle_v1 object\n\nDestroys the zwlr_foreign_toplevel_handle_v1 object.\n\nThis request should be called either when the client does not want to\nuse the toplevel anymore or after the closed event to finalize the\ndestruction of the object.\n\nThis is a destructor, once sent this object cannot be used any longer."]
Destroy,
}
impl super::MessageGroup for Request {
const MESSAGES: &'static [super::MessageDesc] = &[
super::MessageDesc {
name: "set_maximized",
since: 1,
signature: &[],
},
super::MessageDesc {
name: "unset_maximized",
since: 1,
signature: &[],
},
super::MessageDesc {
name: "set_minimized",
since: 1,
signature: &[],
},
super::MessageDesc {
name: "unset_minimized",
since: 1,
signature: &[],
},
super::MessageDesc {
name: "activate",
since: 1,
signature: &[super::ArgumentType::Object],
},
super::MessageDesc {
name: "close",
since: 1,
signature: &[],
},
super::MessageDesc {
name: "set_rectangle",
since: 1,
signature: &[
super::ArgumentType::Object,
super::ArgumentType::Int,
super::ArgumentType::Int,
super::ArgumentType::Int,
super::ArgumentType::Int,
],
},
super::MessageDesc {
name: "destroy",
since: 1,
signature: &[],
},
];
type Map = super::ProxyMap;
fn is_destructor(&self) -> bool {
match *self {
Request::Destroy => true,
_ => false,
}
}
fn opcode(&self) -> u16 {
match *self {
Request::SetMaximized => 0,
Request::UnsetMaximized => 1,
Request::SetMinimized => 2,
Request::UnsetMinimized => 3,
Request::Activate { .. } => 4,
Request::Close => 5,
Request::SetRectangle { .. } => 6,
Request::Destroy => 7,
}
}
fn child<Meta: ObjectMetadata>(
opcode: u16,
version: u32,
meta: &Meta,
) -> Option<Object<Meta>> {
match opcode {
_ => None,
}
}
fn from_raw(msg: Message, map: &mut Self::Map) -> Result<Self, ()> {
panic!("Request::from_raw can not be used Client-side.")
}
fn into_raw(self, sender_id: u32) -> Message {
match self {
Request::SetMaximized => Message {
sender_id: sender_id,
opcode: 0,
args: vec![],
},
Request::UnsetMaximized => Message {
sender_id: sender_id,
opcode: 1,
args: vec![],
},
Request::SetMinimized => Message {
sender_id: sender_id,
opcode: 2,
args: vec![],
},
Request::UnsetMinimized => Message {
sender_id: sender_id,
opcode: 3,
args: vec![],
},
Request::Activate { seat } => Message {
sender_id: sender_id,
opcode: 4,
args: vec![Argument::Object(seat.id())],
},
Request::Close => Message {
sender_id: sender_id,
opcode: 5,
args: vec![],
},
Request::SetRectangle {
surface,
x,
y,
width,
height,
} => Message {
sender_id: sender_id,
opcode: 6,
args: vec![
Argument::Object(surface.id()),
Argument::Int(x),
Argument::Int(y),
Argument::Int(width),
Argument::Int(height),
],
},
Request::Destroy => Message {
sender_id: sender_id,
opcode: 7,
args: vec![],
},
}
}
unsafe fn from_raw_c(
obj: *mut ::std::os::raw::c_void,
opcode: u32,
args: *const wl_argument,
) -> Result<Request, ()> {
panic!("Request::from_raw_c can not be used Client-side.")
}
fn as_raw_c_in<F, T>(self, f: F) -> T
where
F: FnOnce(u32, &mut [wl_argument]) -> T,
{
match self {
Request::SetMaximized => {
let mut _args_array: [wl_argument; 0] = unsafe { ::std::mem::zeroed() };
f(0, &mut _args_array)
}
Request::UnsetMaximized => {
let mut _args_array: [wl_argument; 0] = unsafe { ::std::mem::zeroed() };
f(1, &mut _args_array)
}
Request::SetMinimized => {
let mut _args_array: [wl_argument; 0] = unsafe { ::std::mem::zeroed() };
f(2, &mut _args_array)
}
Request::UnsetMinimized => {
let mut _args_array: [wl_argument; 0] = unsafe { ::std::mem::zeroed() };
f(3, &mut _args_array)
}
Request::Activate { seat } => {
let mut _args_array: [wl_argument; 1] = unsafe { ::std::mem::zeroed() };
_args_array[0].o = seat.c_ptr() as *mut _;
f(4, &mut _args_array)
}
Request::Close => {
let mut _args_array: [wl_argument; 0] = unsafe { ::std::mem::zeroed() };
f(5, &mut _args_array)
}
Request::SetRectangle {
surface,
x,
y,
width,
height,
} => {
let mut _args_array: [wl_argument; 5] = unsafe { ::std::mem::zeroed() };
_args_array[0].o = surface.c_ptr() as *mut _;
_args_array[1].i = x;
_args_array[2].i = y;
_args_array[3].i = width;
_args_array[4].i = height;
f(6, &mut _args_array)
}
Request::Destroy => {
let mut _args_array: [wl_argument; 0] = unsafe { ::std::mem::zeroed() };
f(7, &mut _args_array)
}
}
}
}
pub enum Event {
#[doc = "title change\n\nThis event is emitted whenever the title of the toplevel changes."]
Title { title: String },
#[doc = "app-id change\n\nThis event is emitted whenever the app-id of the toplevel changes."]
AppId { app_id: String },
#[doc = "toplevel entered an output\n\nThis event is emitted whenever the toplevel becomes visible on\nthe given output. A toplevel may be visible on multiple outputs."]
OutputEnter {
output: Proxy<super::wl_output::WlOutput>,
},
#[doc = "toplevel left an output\n\nThis event is emitted whenever the toplevel stops being visible on\nthe given output. It is guaranteed that an entered-output event\nwith the same output has been emitted before this event."]
OutputLeave {
output: Proxy<super::wl_output::WlOutput>,
},
#[doc = "the toplevel state changed\n\nThis event is emitted immediately after the zlw_foreign_toplevel_handle_v1\nis created and each time the toplevel state changes, either because of a\ncompositor action or because of a request in this protocol."]
State { state: Vec<u8> },
#[doc = "all information about the toplevel has been sent\n\nThis event is sent after all changes in the toplevel state have been\nsent.\n\nThis allows changes to the zwlr_foreign_toplevel_handle_v1 properties\nto be seen as atomic, even if they happen via multiple events."]
Done,
#[doc = "this toplevel has been destroyed\n\nThis event means the toplevel has been destroyed. It is guaranteed there\nwon't be any more events for this zwlr_foreign_toplevel_handle_v1. The\ntoplevel itself becomes inert so any requests will be ignored except the\ndestroy request."]
Closed,
}
impl super::MessageGroup for Event {
const MESSAGES: &'static [super::MessageDesc] = &[
super::MessageDesc {
name: "title",
since: 1,
signature: &[super::ArgumentType::Str],
},
super::MessageDesc {
name: "app_id",
since: 1,
signature: &[super::ArgumentType::Str],
},
super::MessageDesc {
name: "output_enter",
since: 1,
signature: &[super::ArgumentType::Object],
},
super::MessageDesc {
name: "output_leave",
since: 1,
signature: &[super::ArgumentType::Object],
},
super::MessageDesc {
name: "state",
since: 1,
signature: &[super::ArgumentType::Array],
},
super::MessageDesc {
name: "done",
since: 1,
signature: &[],
},
super::MessageDesc {
name: "closed",
since: 1,
signature: &[],
},
];
type Map = super::ProxyMap;
fn is_destructor(&self) -> bool {
match *self {
_ => false,
}
}
fn opcode(&self) -> u16 {
match *self {
Event::Title { .. } => 0,
Event::AppId { .. } => 1,
Event::OutputEnter { .. } => 2,
Event::OutputLeave { .. } => 3,
Event::State { .. } => 4,
Event::Done => 5,
Event::Closed => 6,
}
}
fn child<Meta: ObjectMetadata>(
opcode: u16,
version: u32,
meta: &Meta,
) -> Option<Object<Meta>> {
match opcode {
_ => None,
}
}
fn from_raw(msg: Message, map: &mut Self::Map) -> Result<Self, ()> {
match msg.opcode {
0 => {
let mut args = msg.args.into_iter();
Ok(Event::Title {
title: {
if let Some(Argument::Str(val)) = args.next() {
let s = String::from_utf8(val.into_bytes()).unwrap_or_else(|e| {
String::from_utf8_lossy(&e.into_bytes()).into()
});
s
} else {
return Err(());
}
},
})
}
1 => {
let mut args = msg.args.into_iter();
Ok(Event::AppId {
app_id: {
if let Some(Argument::Str(val)) = args.next() {
let s = String::from_utf8(val.into_bytes()).unwrap_or_else(|e| {
String::from_utf8_lossy(&e.into_bytes()).into()
});
s
} else {
return Err(());
}
},
})
}
2 => {
let mut args = msg.args.into_iter();
Ok(Event::OutputEnter {
output: {
if let Some(Argument::Object(val)) = args.next() {
map.get(val).ok_or(())?
} else {
return Err(());
}
},
})
}
3 => {
let mut args = msg.args.into_iter();
Ok(Event::OutputLeave {
output: {
if let Some(Argument::Object(val)) = args.next() {
map.get(val).ok_or(())?
} else {
return Err(());
}
},
})
}
4 => {
let mut args = msg.args.into_iter();
Ok(Event::State {
state: {
if let Some(Argument::Array(val)) = args.next() {
val
} else {
return Err(());
}
},
})
}
5 => Ok(Event::Done),
6 => Ok(Event::Closed),
_ => Err(()),
}
}
fn into_raw(self, sender_id: u32) -> Message {
panic!("Event::into_raw can not be used Client-side.")
}
unsafe fn from_raw_c(
obj: *mut ::std::os::raw::c_void,
opcode: u32,
args: *const wl_argument,
) -> Result<Event, ()> {
match opcode {
0 => {
let _args = ::std::slice::from_raw_parts(args, 1);
Ok(Event::Title {
title: ::std::ffi::CStr::from_ptr(_args[0].s)
.to_string_lossy()
.into_owned(),
})
}
1 => {
let _args = ::std::slice::from_raw_parts(args, 1);
Ok(Event::AppId {
app_id: ::std::ffi::CStr::from_ptr(_args[0].s)
.to_string_lossy()
.into_owned(),
})
}
2 => {
let _args = ::std::slice::from_raw_parts(args, 1);
Ok(Event::OutputEnter {
output: Proxy::<super::wl_output::WlOutput>::from_c_ptr(
_args[0].o as *mut _,
),
})
}
3 => {
let _args = ::std::slice::from_raw_parts(args, 1);
Ok(Event::OutputLeave {
output: Proxy::<super::wl_output::WlOutput>::from_c_ptr(
_args[0].o as *mut _,
),
})
}
4 => {
let _args = ::std::slice::from_raw_parts(args, 1);
Ok(Event::State {
state: {
let array = &*_args[0].a;
::std::slice::from_raw_parts(array.data as *const u8, array.size)
.to_owned()
},
})
}
5 => Ok(Event::Done),
6 => Ok(Event::Closed),
_ => return Err(()),
}
}
fn as_raw_c_in<F, T>(self, f: F) -> T
where
F: FnOnce(u32, &mut [wl_argument]) -> T,
{
panic!("Event::as_raw_c_in can not be used Client-side.")
}
}
pub struct ZwlrForeignToplevelHandleV1;
impl Interface for ZwlrForeignToplevelHandleV1 {
type Request = Request;
type Event = Event;
const NAME: &'static str = "zwlr_foreign_toplevel_handle_v1";
const VERSION: u32 = 1;
fn c_interface() -> *const wl_interface {
unsafe { &super::super::c_interfaces::zwlr_foreign_toplevel_handle_v1_interface }
}
}
pub trait RequestsTrait {
#[doc = "requests that the toplevel be maximized\n\nRequests that the toplevel be maximized. If the maximized state actually\nchanges, this will be indicated by the state event."]
fn set_maximized(&self) -> ();
#[doc = "requests that the toplevel be unmaximized\n\nRequests that the toplevel be unmaximized. If the maximized state actually\nchanges, this will be indicated by the state event."]
fn unset_maximized(&self) -> ();
#[doc = "requests that the toplevel be minimized\n\nRequests that the toplevel be minimized. If the minimized state actually\nchanges, this will be indicated by the state event."]
fn set_minimized(&self) -> ();
#[doc = "requests that the toplevel be unminimized\n\nRequests that the toplevel be unminimized. If the minimized state actually\nchanges, this will be indicated by the state event."]
fn unset_minimized(&self) -> ();
#[doc = "activate the toplevel\n\nRequest that this toplevel be activated on the given seat.\nThere is no guarantee the toplevel will be actually activated."]
fn activate(&self, seat: &Proxy<super::wl_seat::WlSeat>) -> ();
#[doc = "request that the toplevel be closed\n\nSend a request to the toplevel to close itself. The compositor would\ntypically use a shell-specific method to carry out this request, for\nexample by sending the xdg_toplevel.close event. However, this gives\nno guarantees the toplevel will actually be destroyed. If and when\nthis happens, the zwlr_foreign_toplevel_handle_v1.closed event will\nbe emitted."]
fn close(&self) -> ();
#[doc = "the rectangle which represents the toplevel\n\nThe rectangle of the surface specified in this request corresponds to\nthe place where the app using this protocol represents the given toplevel.\nIt can be used by the compositor as a hint for some operations, e.g\nminimizing. The client is however not required to set this, in which\ncase the compositor is free to decide some default value.\n\nIf the client specifies more than one rectangle, only the last one is\nconsidered.\n\nThe dimensions are given in surface-local coordinates.\nSetting width=height=0 removes the already-set rectangle."]
fn set_rectangle(
&self,
surface: &Proxy<super::wl_surface::WlSurface>,
x: i32,
y: i32,
width: i32,
height: i32,
) -> ();
#[doc = "destroy the zwlr_foreign_toplevel_handle_v1 object\n\nDestroys the zwlr_foreign_toplevel_handle_v1 object.\n\nThis request should be called either when the client does not want to\nuse the toplevel anymore or after the closed event to finalize the\ndestruction of the object.\n\nThis is a destructor, you cannot send requests to this object any longer once this method is called."]
fn destroy(&self) -> ();
}
impl RequestsTrait for Proxy<ZwlrForeignToplevelHandleV1> {
fn set_maximized(&self) -> () {
let msg = Request::SetMaximized;
self.send(msg);
}
fn unset_maximized(&self) -> () {
let msg = Request::UnsetMaximized;
self.send(msg);
}
fn set_minimized(&self) -> () {
let msg = Request::SetMinimized;
self.send(msg);
}
fn unset_minimized(&self) -> () {
let msg = Request::UnsetMinimized;
self.send(msg);
}
fn activate(&self, seat: &Proxy<super::wl_seat::WlSeat>) -> () {
let msg = Request::Activate { seat: seat.clone() };
self.send(msg);
}
fn close(&self) -> () {
let msg = Request::Close;
self.send(msg);
}
fn set_rectangle(
&self,
surface: &Proxy<super::wl_surface::WlSurface>,
x: i32,
y: i32,
width: i32,
height: i32,
) -> () {
let msg = Request::SetRectangle {
surface: surface.clone(),
x: x,
y: y,
width: width,
height: height,
};
self.send(msg);
}
fn destroy(&self) -> () {
let msg = Request::Destroy;
self.send(msg);
}
}
#[doc = r" The minimal object version supporting this request"]
pub const REQ_SET_MAXIMIZED_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this request"]
pub const REQ_UNSET_MAXIMIZED_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this request"]
pub const REQ_SET_MINIMIZED_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this request"]
pub const REQ_UNSET_MINIMIZED_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this request"]
pub const REQ_ACTIVATE_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this request"]
pub const REQ_CLOSE_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this request"]
pub const REQ_SET_RECTANGLE_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this request"]
pub const REQ_DESTROY_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_TITLE_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_APP_ID_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_OUTPUT_ENTER_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_OUTPUT_LEAVE_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_STATE_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_DONE_SINCE: u16 = 1u16;
#[doc = r" The minimal object version supporting this event"]
pub const EVT_CLOSED_SINCE: u16 = 1u16;
}
| true |
93c29c81a15a7db86e429b7ba7d090df557c8a6d
|
Rust
|
izelnakri/mber-rust
|
/src/commands/new.rs
|
UTF-8
| 4,759 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
// TODO: rewrite this in tokio
use super::super::utils::console;
use super::super::injections::new_ember_application;
use mustache::MapBuilder;
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process;
use yansi::Paint;
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum KeyValue {
Vec(Vec<u8>),
RefCell(HashMap<String, KeyValue>),
}
pub fn run() -> std::io::Result<()> {
let application_name = std::env::args().nth(2).unwrap_or_else(|| {
println!("You forgot to include an application name! Example: mber init example-app");
process::exit(1);
});
let path = env::current_dir()?;
let user_has_the_app_in_path: bool = path
.iter()
.any(|folder| folder.to_str().unwrap() == application_name);
if user_has_the_app_in_path || user_has_app_in_current_directory(&path, &application_name) {
console::log(format!("{} already exists!", application_name));
process::exit(1);
}
console::log(format!("creating {} application", application_name));
let current_directory = path.display().to_string();
let application_directory = format!("{}/{}", ¤t_directory, &application_name);
let fs_hashmap: HashMap<String, KeyValue> =
serde_json::from_str(new_ember_application::as_str()).unwrap();
create_nested_directory_and_files_from_hashmap(
&fs_hashmap,
current_directory,
&application_name,
);
add_application_name_to_boilerplate_files(application_directory, &application_name)?;
if let KeyValue::RefCell(hashmap) = fs_hashmap.get("ember-app-boilerplate").unwrap() {
for (key, _value) in hashmap {
println!("{} {}", Paint::green("created"), key);
}
}
console::log(Paint::green(format!(
"{} ember application created. Next is to do:",
application_name
)));
println!("$ cd {} && npm install && mber s", application_name);
Ok(())
}
fn user_has_app_in_current_directory(path: &PathBuf, application_name: &str) -> bool {
return fs::read_dir(path)
.unwrap()
.any(|element| element.unwrap().file_name() == application_name);
}
fn create_nested_directory_and_files_from_hashmap(
fs_hashmap: &HashMap<String, KeyValue>,
current_directory: String,
application_name: &String,
) {
for (file_or_directory_name, value) in fs_hashmap {
let target_path = if &file_or_directory_name.as_str() == &"ember-app-boilerplate" {
format!("{}/{}", ¤t_directory, &application_name).to_string()
} else {
format!("{}/{}", ¤t_directory, &file_or_directory_name).to_string()
};
match value {
KeyValue::Vec(content) => {
fs::write(&target_path, content)
.expect(format!("couldnt write to {}", target_path).as_str());
();
}
KeyValue::RefCell(directory_map) => {
fs::create_dir(&target_path)
.expect(format!("couldnt create dir! {}", target_path).as_str());
create_nested_directory_and_files_from_hashmap(
&directory_map,
target_path,
application_name,
)
}
}
}
return ();
}
fn add_application_name_to_boilerplate_files(
application_directory: String,
application_name: &String,
) -> std::io::Result<()> {
let application_name = application_name.as_str();
add_application_data_to_file(
format!("{}/config/environment.js", &application_directory),
&application_name,
)
.unwrap();
add_application_data_to_file(
format!("{}/package.json", &application_directory),
&application_name,
)
.unwrap();
add_application_data_to_file(
format!("{}/tests/index.html", &application_directory),
&application_name,
)
.unwrap();
fs::write(
format!("{}/.gitignore", &application_directory),
format!(
"{}\n{}\n{}\n{}\n{}\n{}",
".cache", "dist", "node_modules", "npm-debug.log*", "yarn-error.log", "tmp"
),
)?;
return Ok(());
}
fn add_application_data_to_file(
file_path: String,
application_name: &str,
) -> Result<(), std::io::Error> {
let application_data = MapBuilder::new()
.insert_str("applicationName", application_name)
.build();
let file_template = mustache::compile_path(&file_path).unwrap();
return fs::write(
file_path,
file_template
.render_data_to_string(&application_data)
.unwrap(),
);
}
| true |
97856f0cc6b518882dc942b917268ad7399d220a
|
Rust
|
rkanati/sleeper
|
/src/assembler.rs
|
UTF-8
| 7,457 | 2.859375 | 3 |
[] |
no_license
|
use {
crate::{
instruction::{self, Reg},
},
std::{
cmp::{min, max},
collections::HashMap,
iter::repeat,
slice,
},
};
type SymTab = HashMap<&'static str, i32>;
#[derive(Clone, Copy)]
pub enum Imm {
Lit(i32),
Ref(&'static str),
HiB(&'static str),
LoB(&'static str),
}
impl Imm {
fn resolve(self, symtab: &SymTab) -> Option<i32> {
let check = |x: &i32| *x >= -32768 && *x <= 65536;
match self {
Imm::Lit(value) => Some(value),
Imm::Ref(name) => symtab.get(name).cloned(),
Imm::HiB(name) => symtab.get(name).cloned().filter(check).map(|x| (x >> 8) & 0xff),
Imm::LoB(name) => symtab.get(name).cloned().filter(check).map(|x| (x >> 0) & 0xff),
}
}
fn resolve_rel8(self, symtab: &SymTab, pc: u32) -> Option<i8> {
let abs = self.resolve(symtab)?;
let value = (abs - pc as i32);
if value > (i8::max_value() as i32) || value < (i8::min_value() as i32) || value & 1 != 0 {
None
}
else {
Some((value >> 1) as i8)
}
}
fn resolve_u4(self, symtab: &SymTab) -> Option<u8> {
let value = self.resolve(symtab)?;
if value > 15 || value < 0 {
None
}
else {
Some(value as u8)
}
}
fn resolve_byte(self, symtab: &SymTab) -> Option<u8> {
let value = self.resolve(symtab)?;
if value > (u8::max_value() as i32) || value < (i8::min_value() as i32) {
None
}
else {
Some(value as u8)
}
}
}
#[derive(Clone, Copy)]
pub enum Inst {
NOp,
Hlt,
LdB(Reg, Reg),
LdW(Reg, Reg),
StB(Reg, Reg),
StW(Reg, Reg),
LdI(Reg, Imm),
LUI(Reg, Imm),
Add(Reg, Reg, Reg),
Sub(Reg, Reg, Reg),
And(Reg, Reg, Reg),
Or(Reg, Reg, Reg),
XOr(Reg, Reg, Reg),
Not(Reg, Reg),
Inc(Reg, Imm),
Dec(Reg, Imm),
SL(Reg, Reg, Reg),
SR(Reg, Reg, Reg),
SA(Reg, Reg, Reg),
SLI(Reg, Reg, Imm),
SRI(Reg, Reg, Imm),
SAI(Reg, Reg, Imm),
TEq(Reg, Reg),
TNE(Reg, Reg),
TGT(Reg, Reg),
TLT(Reg, Reg),
TGE(Reg, Reg),
TLE(Reg, Reg),
JR(Imm),
BR(Reg, Imm),
J(Reg, Imm),
B(Reg, Reg, Imm)
}
impl Inst {
fn assemble(self, symtab: &SymTab, pc: u32) -> Option<u16> {
use instruction::Instruction as O;
let inst = match self {
Inst::NOp => O::NOp,
Inst::Hlt => O::Hlt,
Inst::LdB(dst, ptr) => O::LdB { dst, ptr },
Inst::LdW(dst, ptr) => O::LdW { dst, ptr },
Inst::StB(src, ptr) => O::StB { src, ptr },
Inst::StW(src, ptr) => O::StW { src, ptr },
Inst::LdI(dst, imm) => O::LdI { dst, imm: imm.resolve_byte(symtab)? },
Inst::LUI(dst, imm) => O::LUI { dst, imm: imm.resolve_byte(symtab)? },
Inst::Add(dst, a, b) => O::Add { dst, a, b },
Inst::Sub(dst, a, b) => O::Sub { dst, a, b },
Inst::And(dst, a, b) => O::And { dst, a, b },
Inst:: Or(dst, a, b) => O::Or { dst, a, b },
Inst::XOr(dst, a, b) => O::XOr { dst, a, b },
Inst::Not(dst, src) => O::Not { dst, src },
Inst::Inc(dst, imm) => O::Inc { dst, imm: imm.resolve_u4(symtab)? },
Inst::Dec(dst, imm) => O::Dec { dst, imm: imm.resolve_u4(symtab)? },
Inst:: SL(dst, src, amt) => O::SL { dst, src, amt },
Inst:: SR(dst, src, amt) => O::SR { dst, src, amt },
Inst:: SA(dst, src, amt) => O::SA { dst, src, amt },
Inst::SLI(dst, src, amt) => O::SLI { dst, src, amt: amt.resolve_u4(symtab)? },
Inst::SRI(dst, src, amt) => O::SRI { dst, src, amt: amt.resolve_u4(symtab)? },
Inst::SAI(dst, src, amt) => O::SAI { dst, src, amt: amt.resolve_u4(symtab)? },
Inst::TEq(a, b) => O::TEq { a, b },
Inst::TNE(a, b) => O::TNE { a, b },
Inst::TGT(a, b) => O::TGT { a, b },
Inst::TLT(a, b) => O::TLT { a, b },
Inst::TGE(a, b) => O::TGE { a, b },
Inst::TLE(a, b) => O::TLE { a, b },
Inst:: JR(off) => O::JR { off: off.resolve_rel8(symtab, pc)? },
Inst:: BR(cnd, off) => O::BR { cnd, off: off.resolve_rel8(symtab, pc)? },
Inst:: J(ptr, off) => O::J { ptr, off: off.resolve_u4(symtab)? },
Inst:: B(cnd, ptr, off) => O::B { cnd, ptr, off: off.resolve_u4(symtab)? },
};
inst.encode()
}
}
#[derive(Clone, Copy)]
pub enum Asm {
Label(&'static str),
Const(&'static str, i32),
Orig(u16),
Reserve(u32),
DataBytes(&'static [u8]),
DataWords(&'static [u8]),
Inst(Inst),
}
type Binary = Vec<u8>;
pub fn assemble(asm: &[Asm]) -> Option<Binary> {
// compute addresses
let (base, size, symtab) = {
let mut ptr = 0u32;
let mut minmax = (u32::max_value(), 0);
let mut symtab = HashMap::new();
for item in asm {
// align ptr
if ptr & 1 != 0 { ptr += 1 }
match *item {
Asm::Label(name) => {
if let Some(_) = symtab.insert(name, ptr as i32) {
return None;
}
},
Asm::Const(name, value) => {
if let Some(_) = symtab.insert(name, value) {
return None;
}
},
Asm::Orig(addr) => ptr = addr as u32,
Asm::Reserve(n) => ptr += n,
Asm::DataBytes(bs) => ptr += bs.len() as u32,
Asm::DataWords(ws) => ptr += ws.len() as u32,
Asm::Inst(_) => ptr += 2,
}
minmax = (min(minmax.0, ptr), max(minmax.1, ptr));
}
(minmax.0, (minmax.1 - minmax.0) as usize, symtab)
};
// assemble for real
let mut out: Binary = repeat(0u8).take(size).collect();
let mut pc = 0u32;
for item in asm {
if pc & 1 != 0 { pc += 1 }
match *item {
Asm::Label(_) => { }
Asm::Const(_, _) => { }
Asm::Orig(addr) => {
pc = addr as u32;
}
Asm::Reserve(n) => {
pc += n;
}
Asm::DataBytes(bs) => {
for b in bs {
let idx = (pc - base) as usize;
out[idx] = *b;
pc += 1;
}
}
Asm::DataWords(ws) => {
let bp = ws.as_ptr() as *const u8;
let bs = unsafe { slice::from_raw_parts(bp, ws.len() * 2) };
for b in bs {
let idx = (pc - base) as usize;
out[idx] = *b;
pc += 1;
}
},
Asm::Inst(i) => {
pc += 2;
let word = i.assemble(&symtab, pc)?;
let bs = word.to_le_bytes();
let idx = (pc - base - 2) as usize;
out[idx + 0] = bs[0];
out[idx + 1] = bs[1];
}
}
}
Some(out)
}
| true |
7fdfbfb78b970a2a2a8af65201b34f5cea4e88d5
|
Rust
|
MDeiml/nextflix
|
/src/model.rs
|
UTF-8
| 409 | 2.640625 | 3 |
[] |
no_license
|
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug)]
pub struct User {
pub username: String,
pub password_hash: String,
pub friends: HashMap<u64, FriendData>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct FriendData {
pub movies: Vec<u64>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Movie {
pub name: String,
}
| true |
b7e52e57c6d34f0b868074187a65140a527c6598
|
Rust
|
seanchen1991/rune
|
/crates/rune/src/ast/stmt.rs
|
UTF-8
| 314 | 2.796875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::ast;
use crate::{Spanned, ToTokens};
/// A statement within a block.
#[derive(Debug, Clone, ToTokens, Spanned)]
pub enum Stmt {
/// A declaration.
Item(ast::Item),
/// An expression.
Expr(ast::Expr),
/// An expression followed by a semicolon.
Semi(ast::Expr, ast::SemiColon),
}
| true |
dfb754f83d2c85f2ab4775383c3f21c82673ae25
|
Rust
|
jgdavey/advent_of_code_2020
|
/aoc05/src/main.rs
|
UTF-8
| 814 | 3.640625 | 4 |
[] |
no_license
|
pub fn decode(seat: &str) -> usize {
let binary: String = seat
.chars()
.map(|c| match c {
'B' | 'R' => '1',
'F' | 'L' => '0',
_ => c,
})
.collect();
usize::from_str_radix(&binary, 2).unwrap()
}
fn main() {
let input = std::fs::read_to_string("input.txt").unwrap();
let mut seat_ids: Vec<_> = input.lines().map(decode).collect();
seat_ids.sort();
for (i, seat) in seat_ids.iter().skip(1).enumerate() {
if seat - seat_ids[i] > 1 {
print!("Seat: {}", seat - 1);
break;
}
}
}
#[cfg(test)]
mod tests {
use super::decode;
#[test]
fn test_decode_seat_id() {
let seat = "FBFBBFFRLR";
let decoded = decode(seat);
assert_eq!(decoded, 357);
}
}
| true |
c78807bd57df95ae5028a7a42c7b52520629fc9d
|
Rust
|
harpsword/tex-rs
|
/src/tex_the_program/section_0498.rs
|
UTF-8
| 3,075 | 2.71875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! @ A condition is started when the |expand| procedure encounters
//! an |if_test| command; in that case |expand| reduces to |conditional|,
//! which is a recursive procedure.
//! @^recursion@>
//
// @p procedure conditional;
#[allow(unused_variables)]
pub(crate) fn conditional(globals: &mut TeXGlobals) -> TeXResult<()> {
// label exit,common_ending;
// var b:boolean; {is the condition true?}
/// is the condition true?
let b: boolean;
// @!r:"<"..">"; {relation to be evaluated}
// @!m,@!n:integer; {to be tested against the second operand}
// @!p,@!q:pointer; {for traversing token lists in \.{\\ifx} tests}
// @!save_scanner_status:small_number; {|scanner_status| upon entry}
// @!save_cond_ptr:pointer; {|cond_ptr| corresponding to this conditional}
/// `cond_ptr` corresponding to this conditional
let save_cond_ptr: pointer;
// @!this_if:small_number; {type of this conditional}
/// type of this conditional
let this_if: small_number;
// begin @<Push the condition stack@>;@+save_cond_ptr:=cond_ptr;this_if:=cur_chr;@/
crate::section_0495::Push_the_condition_stack!(globals);
save_cond_ptr = globals.cond_ptr;
this_if = (globals.cur_chr.get() as u8).into();
crate::region_forward_label!(
|'common_ending|
{
// @<Either process \.{\\ifcase} or set |b| to the value of a boolean condition@>;
crate::section_0501::Either_process_ifcase_or_set_b_to_the_value_of_a_boolean_condition!(globals, this_if, b, save_cond_ptr, 'common_ending);
// if tracing_commands>1 then @<Display the value of |b|@>;
if tracing_commands!(globals) > 1 {
crate::section_0502::Display_the_value_of_b!(globals, b);
}
// if b then
if b {
// begin change_if_limit(else_code,save_cond_ptr);
change_if_limit(globals, else_code.into(), save_cond_ptr);
// return; {wait for \.{\\else} or \.{\\fi}}
/// wait for `\else` or `\fi`
crate::return_nojump!();
// end;
}
// @<Skip to \.{\\else} or \.{\\fi}, then |goto common_ending|@>;
crate::section_0500::Skip_to_else_or_fi__then_goto_common_ending!(globals, save_cond_ptr, 'common_ending);
}
// common_ending: if cur_chr=fi_code then @<Pop the condition stack@>
'common_ending <-
);
if globals.cur_chr.get() == fi_code as chr_code_repr {
crate::section_0496::Pop_the_condition_stack!(globals);
}
// else if_limit:=fi_code; {wait for \.{\\fi}}
else {
/// wait for `\fi`
const _: () = ();
globals.if_limit = fi_code.into();
}
// exit:end;
crate::ok_nojump!()
}
use crate::pascal::boolean;
use crate::section_0004::TeXGlobals;
use crate::section_0081::TeXResult;
use crate::section_0101::small_number;
use crate::section_0115::pointer;
use crate::section_0236::tracing_commands;
use crate::section_0297::chr_code_repr;
use crate::section_0489::else_code;
use crate::section_0489::fi_code;
use crate::section_0497::change_if_limit;
| true |
18e06dd40833b4accee1aca504f04440b3017c28
|
Rust
|
XuShaohua/nc
|
/src/platform/darwin-types/sys/ipc.rs
|
UTF-8
| 1,425 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) 2022 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by Apache-2.0 License that can be found
// in the LICENSE file.
//! From `sys/ipc.h`
use crate::{gid_t, key_t, mode_t, uid_t};
/// Information used in determining permission to perform an IPC operation
#[derive(Debug, Default, Clone)]
#[repr(C)]
pub struct ipc_perm_t {
/// Owner's user ID
pub uid: uid_t,
/// Owner's group ID
pub gid: gid_t,
/// Creator's user ID
pub cuid: uid_t,
/// Creator's group ID
pub cgid: gid_t,
/// Read/write permission
pub mode: mode_t,
// Reserved for internal use
_seq: u16,
// Reserved for internal use
_key: key_t,
}
/// Definitions shall be provided for the following constants:
///
/// Mode bits
///
/// Create entry if key does not exist
pub const IPC_CREAT: i32 = 0o01000;
/// Fail if key exists
pub const IPC_EXCL: i32 = 0o02000;
/// Error if request must wait
pub const IPC_NOWAIT: i32 = 0o04000;
/// Keys
///
/// Private key
pub const IPC_PRIVATE: key_t = 0;
/// Control commands
///
/// Remove identifier
pub const IPC_RMID: i32 = 0;
/// Set options
pub const IPC_SET: i32 = 1;
/// Get options
pub const IPC_STAT: i32 = 2;
/// common mode bits
///
/// Read permission
pub const IPC_R: i32 = 0o00400;
/// Write/alter permission
pub const IPC_W: i32 = 0o00200;
/// Modify control info permission
pub const IPC_M: i32 = 0o10000;
| true |
652dda8ebab123e14b31696975099539d6177257
|
Rust
|
bazelbuild/rules_rust
|
/test/rust_test_suite/tests/integrated_test_b.rs
|
UTF-8
| 86 | 2.796875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use math_lib::add;
#[test]
fn add_three_and_four() {
assert_eq!(add(3, 4), 7);
}
| true |
977f35a82a09ed9c2e6ed732a15383654a742ef0
|
Rust
|
wveitch/greenhouse-rs
|
/src/server/http.rs
|
UTF-8
| 1,889 | 2.671875 | 3 |
[] |
no_license
|
use crossbeam::channel::Sender;
use log::info;
use rocket::config::LoggingLevel;
use rocket::config::{Config, Environment, Limits};
use std::io;
use std::path::PathBuf;
use std::thread;
use crate::config::CachePath;
use crate::router;
pub struct HttpServe {
http_handle: Option<thread::JoinHandle<()>>,
http_addr: String,
http_port: u16,
path: String,
tx: Sender<PathBuf>,
}
impl HttpServe {
pub fn new(addr: String, port: u16, path: String, tx: Sender<PathBuf>) -> HttpServe {
HttpServe {
http_handle: None,
http_addr: addr,
http_port: port,
path: path,
tx: tx,
}
}
pub fn start(&mut self) -> Result<(), io::Error> {
let builder = thread::Builder::new().name(thd_name!("public-http-service".to_string()));
let config = Config::build(Environment::Staging)
.address(self.http_addr.clone())
.port(self.http_port)
.limits(Limits::new().limit("forms", 1024 * 1024 * 512))
.log_level(LoggingLevel::Off)
.finalize()
.unwrap();
let server = rocket::custom(config)
.manage(CachePath(self.path.clone()))
.manage(self.tx.clone())
.mount("/", routes![router::upload, router::get, router::head]);
let h = builder.spawn(move || {
server.launch();
})?;
self.http_handle = Some(h);
Ok(())
}
pub fn stop(&mut self) -> Result<(), io::Error> {
info!("stop metric server");
let h = match self.http_handle.take() {
None => return Ok(()),
Some(h) => h,
};
if let Err(e) = h.join() {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"join metric thread err",
));
}
Ok(())
}
}
| true |
e20c9dcfb15239e93000cc3371f58b7ecd911c26
|
Rust
|
Mathspy/unsafe-now
|
/index.rs
|
UTF-8
| 5,922 | 2.703125 | 3 |
[] |
no_license
|
use geiger::{find_unsafe_in_file, Count, CounterBlock, IncludeTests, ScanFileError};
use git2::Repository;
use http::{header, Request, Response, StatusCode};
use serde::Serialize;
use std::{collections::HashMap, path::Path};
use tempdir::TempDir;
use url::Url;
use walkdir::{DirEntry, Error as WalkDirError, WalkDir};
#[derive(Serialize)]
// Thanks Globi for this actual black magic
#[serde(remote = "Count")]
struct NewCount {
safe: u64,
// Thanks let dumbqt = proxi; for this! <3
#[serde(rename = "unsafe")]
unsafe_: u64,
}
#[derive(Serialize)]
struct Output {
#[serde(with = "NewCount")]
functions: Count,
#[serde(with = "NewCount")]
exprs: Count,
#[serde(with = "NewCount")]
item_impls: Count,
#[serde(with = "NewCount")]
item_traits: Count,
#[serde(with = "NewCount")]
methods: Count,
#[serde(with = "NewCount")]
total: Count,
}
impl From<CounterBlock> for Output {
fn from(counter_block: CounterBlock) -> Self {
Output {
// No we can't remove those clone()s because we don't own type
// so we can't derive copy ourselves on it
//
// And yes there's no performance difference between clone()ing
// and copying a struct with primitives
// Thanks &star_wars, Fenrir, ~~EYESqu~~ ~~eyes-chan~~ I mean seequ
// C: <3
functions: counter_block.functions.clone(),
exprs: counter_block.exprs.clone(),
item_impls: counter_block.item_impls.clone(),
item_traits: counter_block.item_traits.clone(),
methods: counter_block.methods.clone(),
total: counter_block.functions
+ counter_block.exprs
+ counter_block.item_impls
+ counter_block.item_traits
+ counter_block.methods,
}
}
}
#[derive(Debug)]
pub enum ScanningError {
WalkDirError(WalkDirError),
ScanFileError(ScanFileError),
}
// Thanks Globi I totally didn't understand http's errors apparently lol
impl From<ScanningError> for http::Response<String> {
fn from(error: ScanningError) -> Self {
match error {
ScanningError::WalkDirError(_) => Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body("Failed to traverse repo".to_owned())
// We literally just created an error-y response so it's okay to unwrap_err
.unwrap(),
ScanningError::ScanFileError(error) => Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(format!("Failed to scan file {}", error))
// Same as error above
.unwrap(),
}
}
}
fn is_hidden(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|s| s.starts_with("."))
.unwrap_or(false)
}
// Reworked find_unsafe thanks to let dumbqt = proxi;
// Much less allocations now and probably more readable lol
pub fn find_unsafe<P: AsRef<Path>>(root: P) -> Result<CounterBlock, ScanningError> {
let mut counter_block = CounterBlock::default();
for entry in WalkDir::new(root)
.into_iter()
.filter_entry(|e| !is_hidden(e))
{
let file = entry
.map(|dir_entry| dir_entry.path().to_owned())
.map_err(|err| ScanningError::WalkDirError(err))?;
if file.to_str().map(|s| s.ends_with(".rs")).unwrap_or(false) {
let file_metrics = find_unsafe_in_file(&file, IncludeTests::No)
.map_err(|err| ScanningError::ScanFileError(err))?;
counter_block = counter_block + file_metrics.counters;
}
}
Ok(counter_block)
}
fn handler(request: Request<()>) -> http::Result<Response<String>> {
let url = Url::parse(&request.uri().to_string()).unwrap();
let hash_query: HashMap<_, _> = url.query_pairs().to_owned().collect();
match (hash_query.get("user"), hash_query.get("repo")) {
(Some(user), Some(repo)) => {
let repo_url = format!("https://github.com/{}/{}", user, repo);
// Thanks let dumbqt = proxi; for telling me about this crate!
let temp_dir = TempDir::new(&repo).expect("Should be able to create a temp dir");
match Repository::clone(&repo_url, &temp_dir) {
Ok(_) => (),
Err(e) => {
return Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(format!(
"Failed to clone {}\n> {:?}: {}",
repo_url,
e.code(),
e.to_string(),
));
}
};
let data = match find_unsafe(&temp_dir) {
Ok(data) => data,
Err(error) => return Ok(error.into()),
};
let formattable_data = Output::from(data);
let response = Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "application/json")
// Our serde_json implementation should never fail, okay to unwrap
.body(serde_json::to_string_pretty(&formattable_data).unwrap())
.expect("Failed to render response");
Ok(response)
}
_ => Response::builder()
.status(StatusCode::BAD_REQUEST)
.body("BAD REQUEST.\nUsage instruction: /<github_username>/<github_repo>/".to_string()),
}
}
// For local testing:
// fn main() {
// let test = handler(
// Request::get("https://unsafe-now-awqpllhtf.now.sh/?user=amethyst&repo=rendy")
// .body(())
// .unwrap(),
// );
// dbg!(test.unwrap().body());
// // dbg!(find_unsafe("./amethyst/rendy"));
// }
| true |
7881b9b1817251d52633f49da1ab9edbb4151700
|
Rust
|
haraldmaida/advent-of-code-2018
|
/src/day14/tests.rs
|
UTF-8
| 2,547 | 3.09375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use super::*;
const INPUT: &str = include_str!("../../input/2018/day14.txt");
mod score_seq {
use super::*;
#[test]
fn fmt_display() {
assert_eq!(
ScoreSeq(vec![5, 1, 5, 8, 9, 1, 6, 7, 7, 9]).to_string(),
"[5, 1, 5, 8, 9, 1, 6, 7, 7, 9]"
);
}
}
mod scoreboard {
use super::*;
#[test]
fn fmt_display() {
assert_eq!(
Scoreboard::new(vec![
3, 7, 1, 0, 1, 0, 1, 2, 4, 5, 1, 5, 8, 9, 1, 6, 7, 7, 9, 2
])
.to_string(),
"3 7 1 0 1 0 1 2 4 5 1 5 8 9 1 6 7 7 9 2"
);
}
}
mod part1 {
use super::*;
#[test]
fn example1() {
let num_recipes = "9";
let answer = score_seq_after_num_recipes(num_recipes);
assert_eq!(answer, ScoreSeq(vec![5, 1, 5, 8, 9, 1, 6, 7, 7, 9]));
}
#[test]
fn example2() {
let num_recipes = "5";
let answer = score_seq_after_num_recipes(num_recipes);
assert_eq!(answer, ScoreSeq(vec![0, 1, 2, 4, 5, 1, 5, 8, 9, 1]));
}
#[test]
fn example3() {
let num_recipes = "18";
let answer = score_seq_after_num_recipes(num_recipes);
assert_eq!(answer, ScoreSeq(vec![9, 2, 5, 1, 0, 7, 1, 0, 8, 5]));
}
#[test]
fn example4() {
let num_recipes = "2018";
let answer = score_seq_after_num_recipes(num_recipes);
assert_eq!(answer, ScoreSeq(vec![5, 9, 4, 1, 4, 2, 9, 8, 8, 2]));
}
#[test]
fn answer() {
let num_recipes = INPUT;
let answer = score_seq_after_num_recipes(num_recipes);
assert_eq!(answer, ScoreSeq(vec![6, 1, 0, 7, 1, 0, 1, 5, 4, 4]));
}
}
mod part2 {
use super::*;
#[test]
fn example1() {
let score_seq = "51589";
let answer = num_needed_recipes(score_seq);
assert_eq!(answer, 9);
}
#[test]
fn example2() {
let score_seq = "01245";
let answer = num_needed_recipes(score_seq);
assert_eq!(answer, 5);
}
#[test]
fn example3() {
let score_seq = "92510";
let answer = num_needed_recipes(score_seq);
assert_eq!(answer, 18);
}
#[test]
fn example4() {
let score_seq = "59414";
let answer = num_needed_recipes(score_seq);
assert_eq!(answer, 2018);
}
#[test]
fn answer() {
let score_seq = INPUT;
let answer = num_needed_recipes(score_seq);
assert_eq!(answer, 20_291_131);
}
}
| true |
9f1fdf85a89b490693558b60dfff7d60b4fd6a31
|
Rust
|
drainiard/rr8
|
/src/rr8/ui/prompt.rs
|
UTF-8
| 1,051 | 2.6875 | 3 |
[
"CC-BY-3.0"
] |
permissive
|
use crate::*;
#[derive(Debug, Default, Eq, PartialEq)]
pub struct Prompt;
impl System for Prompt {
fn update(&mut self, ctx: &mut Context, game: &mut Game) -> GameResult {
todo!()
}
fn draw(&self, ctx: &mut Context, game: &Game) -> GameResult {
let ui = &game.ui;
if let GameMode::Prompt = &game.mode {
// GameMode::Normal => (Pal::Gray.dark(), game.get_status()),
let column = if ui.dt & 0b100000 > 0 { 15 } else { 20 };
let beam = ui.tile8(TileId::Ico, column, Pal::Red, false)?;
let (cursor_pos, prompt) = game.get_prompt();
// this also works nice because drawing the beam before the
// prompt makes the char underneath it visible
ui.draw(ctx, &beam, 2. + cursor_pos as f32 / 2., 19.)?;
let (prompt_color, prompt_text) = (Pal::Blue, prompt);
ui.draw_text(ctx, "#", 1., 19., Pal::Gray.dark())?;
ui.draw_text(ctx, prompt_text, 2., 19., prompt_color)?;
}
Ok(())
}
}
| true |
18699d753f27a66af5e9e0be2508c91df4748510
|
Rust
|
mitnk/h2okv
|
/src/cli/cli.rs
|
UTF-8
| 1,146 | 2.8125 | 3 |
[] |
no_license
|
use std::net::TcpStream;
use crate::do_delete;
use crate::do_get;
use crate::do_put;
use crate::do_scan;
pub fn query(line: &str, stream: &mut TcpStream) {
if line.starts_with("del ") {
let tokens: Vec<&str> = line.split_whitespace().collect();
do_delete::delete(tokens[1], stream);
return;
}
if line.starts_with("get ") {
let tokens: Vec<&str> = line.split_whitespace().collect();
do_get::get(tokens[1], stream);
return;
}
if line.starts_with("put ") || line.starts_with("set ") {
let tokens: Vec<&str> = line.split_whitespace().collect();
if tokens.len() != 3 {
println!("invalid command");
return;
}
do_put::put(tokens[1], tokens[2], stream);
return;
}
if line.starts_with("scan") {
let tokens: Vec<&str> = line.split_whitespace().collect();
if tokens.len() > 1 {
do_scan::scan(tokens[1], stream);
} else {
do_scan::scan("", stream);
}
return;
}
if !line.is_empty() {
println!("unknown command: {:?}", line);
}
}
| true |
29e5285023c5a00519b102657cfa9f1183277635
|
Rust
|
CPerezz/Corretto
|
/src/backend/u64/scalar.rs
|
UTF-8
| 26,912 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
//! Arithmetic mod `2^249 - 15145038707218910765482344729778085401`
//! with five 52-bit unsigned limbs
//! represented in radix `2^52`.
use core::fmt::Debug;
use core::ops::{Index, IndexMut};
use core::ops::{Add, Sub, Mul, Neg};
use std::cmp::{PartialOrd, Ordering, Ord};
use num::Integer;
use crate::backend::u64::constants;
use crate::traits::Identity;
use crate::traits::ops::*;
/// The `Scalar` struct represents an Scalar over the modulo
/// `2^249 - 15145038707218910765482344729778085401` as 5 52-bit limbs
/// represented in radix `2^52`.
#[derive(Copy,Clone)]
pub struct Scalar(pub [u64; 5]);
impl Debug for Scalar {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "Scalar: {:?}", &self.0[..])
}
}
impl Index<usize> for Scalar {
type Output = u64;
fn index(&self, _index: usize) -> &u64 {
&(self.0[_index])
}
}
impl IndexMut<usize> for Scalar {
fn index_mut(&mut self, _index: usize) -> &mut u64 {
&mut (self.0[_index])
}
}
impl PartialOrd for Scalar {
fn partial_cmp(&self, other: &Scalar) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for Scalar {
fn cmp(&self, other: &Self) -> Ordering {
for i in (0..5).rev() {
if self[i] > other[i] {
return Ordering::Greater;
}else if self[i] < other[i] {
return Ordering::Less;
}
}
Ordering::Equal
}
}
//-------------- From Implementations -----------------//
impl<'a> From<&'a u8> for Scalar {
/// Performs the conversion.
fn from(_inp: &'a u8) -> Scalar {
let mut res = Scalar::zero();
res[0] = *_inp as u64;
res
}
}
impl<'a> From<&'a u16> for Scalar {
/// Performs the conversion.
fn from(_inp: &'a u16) -> Scalar {
let mut res = Scalar::zero();
res[0] = *_inp as u64;
res
}
}
impl<'a> From<&'a u32> for Scalar {
/// Performs the conversion.
fn from(_inp: &'a u32) -> Scalar {
let mut res = Scalar::zero();
res[0] = *_inp as u64;
res
}
}
impl<'a> From<&'a u64> for Scalar {
/// Performs the conversion.
fn from(_inp: &'a u64) -> Scalar {
let mut res = Scalar::zero();
let mask = (1u64 << 52) - 1;
res[0] = _inp & mask;
res[1] = _inp >> 52;
res
}
}
impl<'a> From<&'a u128> for Scalar {
/// Performs the conversion.
fn from(_inp: &'a u128) -> Scalar {
let mut res = Scalar::zero();
let mask = (1u128 << 52) - 1;
// Since 128 / 52 < 4 , we only need to care
// about the first three limbs.
res[0] = (_inp & mask) as u64;
res[1] = ((_inp >> 52) & mask) as u64;
res[2] = (_inp >> 104) as u64;
res
}
}
impl<'a> Neg for &'a Scalar {
type Output = Scalar;
/// Performs the negate operation over the
/// sub-group modulo l.
fn neg(self) -> Scalar {
&Scalar::zero() - &self
}
}
impl Neg for Scalar {
type Output = Scalar;
/// Performs the negate operation over the
/// sub-group modulo l.
fn neg(self) -> Scalar {
-&self
}
}
impl Identity for Scalar {
/// Returns the `Identity` element for `Scalar`
/// which equals `1 (mod l)`.
fn identity() -> Scalar {
Scalar::one()
}
}
impl<'a, 'b> Add<&'b Scalar> for &'a Scalar {
type Output = Scalar;
/// Compute `a + b (mod l)`.
fn add(self, b: &'b Scalar) -> Scalar {
let mut sum = Scalar::zero();
let mask = (1u64 << 52) - 1;
// a + b
let mut carry: u64 = 0;
for i in 0..5 {
carry = self.0[i] + b[i] + (carry >> 52);
sum[i] = carry & mask;
}
// subtract l if the sum is >= l
sum - constants::L
}
}
impl Add<Scalar> for Scalar {
type Output = Scalar;
/// Compute `a + b (mod l)`.
fn add(self, b: Scalar) -> Scalar {
&self + &b
}
}
impl<'a, 'b> Sub<&'b Scalar> for &'a Scalar {
type Output = Scalar;
/// Compute `a - b (mod l)`.
fn sub(self, b: &'b Scalar) -> Scalar {
let mut difference = Scalar::zero();
let mask = (1u64 << 52) - 1;
// a - b
let mut borrow: u64 = 0;
// Save the wrapping_sub in borrow and add the remainder to the next limb.
for i in 0..5 {
// Borrow >> 63 so the Most Significant Bit of the remainder (2^64) can be carried to the next limb.
borrow = self.0[i].wrapping_sub(b[i] + (borrow >> 63));
difference[i] = borrow & mask;
}
// conditionally add `l` if the difference is negative.
// Note that here borrow tells us the Most Signif Bit of the last limb so then we know if it's greater than `l`.
let underflow_mask = ((borrow >> 63) ^ 1).wrapping_sub(1); // If isn't greater, we will not add it as XOR = 0.
let mut carry: u64 = 0;
for i in 0..5 {
carry = (carry >> 52) + difference[i] + (constants::L[i] & underflow_mask);
difference[i] = carry & mask;
}
difference
}
}
impl Sub<Scalar> for Scalar {
type Output = Scalar;
/// Compute `a - b (mod l)`.
fn sub(self, b: Scalar) -> Scalar {
&self - &b
}
}
impl<'a, 'b> Mul<&'a Scalar> for &'b Scalar {
type Output = Scalar;
/// This `Mul` implementation returns a double precision result.
/// The result of the standard mul is stored on a [u128; 9].
///
/// Then, we apply the Montgomery Reduction function to perform
/// the modulo and the reduction to the `Scalar` format: [u64; 5].
fn mul(self, b: &'a Scalar) -> Scalar {
let ab = Scalar::montgomery_reduce(&Scalar::mul_internal(self, b));
Scalar::montgomery_reduce(&Scalar::mul_internal(&ab, &constants::RR))
}
}
impl Mul<Scalar> for Scalar {
type Output = Scalar;
/// This `Mul` implementation returns a double precision result.
/// The result of the standard mul is stored on a [u128; 9].
///
/// Then, we apply the Montgomery Reduction function to perform
/// the modulo and the reduction to the `Scalar` format: [u64; 5].
fn mul(self, b: Scalar) -> Scalar {
&self * &b
}
}
impl<'a> Square for &'a Scalar {
type Output = Scalar;
/// This `Square` implementation returns a double precision result.
/// The result of the standard mul is stored on a [u128; 9].
///
/// Then, we apply the Montgomery Reduction function to perform
/// the modulo and the reduction to the `Scalar` format: [u64; 5].
fn square(self) -> Scalar {
let aa = Scalar::montgomery_reduce(&Scalar::square_internal(self));
Scalar::montgomery_reduce(&Scalar::mul_internal(&aa, &constants::RR))
}
}
impl<'a> Half for &'a Scalar {
type Output = Scalar;
/// Give the half of the Scalar value (mod l).
///
/// This op **SHOULD ONLY** be used with even
/// `Scalars` otherways, can produce erroneus
/// results.
///
/// The implementation for `Scalar` has indeed
/// an `assert!` statement to check this.
#[inline]
fn half(self) -> Scalar {
assert!(self.is_even(), "The Scalar has to be even.");
let mut res = self.clone();
let mut remainder = 0u64;
for i in (0..5).rev() {
res[i] = res[i] + remainder;
match(res[i] == 1, res[i].is_even()){
(true, _) => {
remainder = 4503599627370496u64;
}
(_, false) => {
res[i] = res[i] - 1u64;
remainder = 4503599627370496u64;
}
(_, true) => {
remainder = 0;
}
}
res[i] = res[i] >> 1;
};
res
}
}
/// u64 * u64 = u128 inline func multiply helper.
#[inline]
fn m(x: u64, y: u64) -> u128 {
(x as u128) * (y as u128)
}
/// u64 * u64 = u128 macro multiply helper
macro_rules! m {
($x:expr, $y:expr) => {
$x as u128 * $y as u128
}
}
impl Scalar {
/// Return a Scalar with value = `0`.
pub fn zero() -> Scalar {
Scalar([0,0,0,0,0])
}
/// Return a Scalar with value = `1`.
pub fn one() -> Scalar {
Scalar([1,0,0,0,0])
}
/// Return a Scalar with value = `-1 (mod l)`.
pub fn minus_one() -> Scalar {
Scalar([2766226127823334, 4237835465749098, 4503599626623787, 4503599627370495, 2199023255551])
}
/// Evaluate if a `Scalar` is even or not.
pub fn is_even(self) -> bool {
self.0[0].is_even()
}
/// Unpack a 32 byte / 256 bit Scalar into 5 52-bit limbs.
pub fn from_bytes(bytes: &[u8; 32]) -> Scalar {
let mut words = [0u64; 4];
for i in 0..4 {
for j in 0..8 {
words[i] |= (bytes[(i * 8) + j] as u64) << (j * 8);
}
}
let mask = (1u64 << 52) - 1;
let top_mask = (1u64 << 48) - 1;
let mut s = Scalar::zero();
s[0] = words[0] & mask;
// Get the 64-52 = 12 bits and add words[1] (shifting 12 to the left) on the front with `|` then apply mask.
s[1] = ((words[0] >> 52) | (words[1] << 12)) & mask;
s[2] = ((words[1] >> 40) | (words[2] << 24)) & mask;
s[3] = ((words[2] >> 28) | (words[3] << 36)) & mask;
// Shift 16 to the right to get the 52 bits of the scalar on that limb. Then apply top_mask.
s[4] = (words[3] >> 16) & top_mask;
s
}
/// Reduce a 64 byte / 512 bit scalar mod l
pub fn from_bytes_wide(_bytes: &[u8; 64]) -> Scalar {
// We could provide 512 bit scalar support using Montgomery Reduction.
// But first we need to finnish the 256-bit implementation.
unimplemented!()
}
/// Pack the limbs of this `Scalar` into 32 bytes
pub fn to_bytes(&self) -> [u8; 32] {
let mut res = [0u8; 32];
res[0] = (self.0[0] >> 0) as u8;
res[1] = (self.0[0] >> 8) as u8;
res[2] = (self.0[0] >> 16) as u8;
res[3] = (self.0[0] >> 24) as u8;
res[4] = (self.0[0] >> 32) as u8;
res[5] = (self.0[0] >> 40) as u8;
res[6] = ((self.0[0] >> 48) | (self.0[1] << 4)) as u8;
res[7] = (self.0[1] >> 4) as u8;
res[8] = (self.0[1] >> 12) as u8;
res[9] = (self.0[ 1] >> 20) as u8;
res[10] = (self.0[ 1] >> 28) as u8;
res[11] = (self.0[ 1] >> 36) as u8;
res[12] = (self.0[ 1] >> 44) as u8;
res[13] = (self.0[ 2] >> 0) as u8;
res[14] = (self.0[ 2] >> 8) as u8;
res[15] = (self.0[ 2] >> 16) as u8;
res[16] = (self.0[ 2] >> 24) as u8;
res[17] = (self.0[ 2] >> 32) as u8;
res[18] = (self.0[ 2] >> 40) as u8;
res[19] = ((self.0[ 2] >> 48) | (self.0[ 3] << 4)) as u8;
res[20] = (self.0[ 3] >> 4) as u8;
res[21] = (self.0[ 3] >> 12) as u8;
res[22] = (self.0[ 3] >> 20) as u8;
res[23] = (self.0[ 3] >> 28) as u8;
res[24] = (self.0[ 3] >> 36) as u8;
res[25] = (self.0[ 3] >> 44) as u8;
res[26] = (self.0[ 4] >> 0) as u8;
res[27] = (self.0[ 4] >> 8) as u8;
res[28] = (self.0[ 4] >> 16) as u8;
res[29] = (self.0[ 4] >> 24) as u8;
res[30] = (self.0[ 4] >> 32) as u8;
res[31] = (self.0[ 4] >> 40) as u8;
// High bit should be zero.
debug_assert!((res[31] & 0b1000_0000u8) == 0u8);
res
}
/// Given a `k`: u64, compute `2^k` giving the resulting result
/// as a `Scalar`.
///
/// See that the input must be between the range => 0..250.
///
/// NOTE: This function implements an `assert!` statement that
/// checks the correctness of the exponent provided as param.
pub fn two_pow_k(exp: &u64) -> Scalar {
// Check that exp has to be less than 260.
// Note that a Scalar can be as much
// `2^249 - 15145038707218910765482344729778085401` so we pick
// 250 knowing that 249 will be lower than the prime of the
// sub group.
assert!(exp < &253u64, "Exponent can't be greater than 260");
let mut res = Scalar::zero();
match exp {
0...51 => {
res[0] = 1u64 << exp;
},
52...103 => {
res[1] = 1u64 << (exp - 52);
},
104...155 => {
res[2] = 1u64 << (exp - 104);
},
156...207 => {
res[3] = 1u64 << (exp - 156);
},
_ => {
res[4] = 1u64 << (exp - 208);
}
}
res
}
/// Compute `a * b`.
/// Note that this is just the normal way of performing a product.
/// This operation returns back a double precision result stored
/// on a `[u128; 9] in order to avoid overflowings.
#[inline]
pub(self) fn mul_internal(a: &Scalar, b: &Scalar) -> [u128; 9] {
let mut res = [0u128; 9];
res[0] = m(a[0],b[0]);
res[1] = m(a[0],b[1]) + m(a[1],b[0]);
res[2] = m(a[0],b[2]) + m(a[1],b[1]) + m(a[2],b[0]);
res[3] = m(a[0],b[3]) + m(a[1],b[2]) + m(a[2],b[1]) + m(a[3],b[0]);
res[4] = m(a[0],b[4]) + m(a[1],b[3]) + m(a[2],b[2]) + m(a[3],b[1]) + m(a[4],b[0]);
res[5] = m(a[1],b[4]) + m(a[2],b[3]) + m(a[3],b[2]) + m(a[4],b[1]);
res[6] = m(a[2],b[4]) + m(a[3],b[3]) + m(a[4],b[2]);
res[7] = m(a[3],b[4]) + m(a[4],b[3]);
res[8] = m(a[4],b[4]);
res
}
#[allow(dead_code)]
#[inline]
/// Compute `a * b`.
/// Note that this is just the normal way of performing a product.
/// This operation returns back a double precision result stored
/// on a `[u128; 9] in order to avoid overflowings.
pub(self) fn mul_internal_macros(a: &Scalar, b: &Scalar) -> [u128; 9] {
let mut res = [0u128; 9];
res[0] = m!(a[0],b[0]);
res[1] = m!(a[0],b[1]) + m!(a[1],b[0]);
res[2] = m!(a[0],b[2]) + m!(a[1],b[1]) + m!(a[2],b[0]);
res[3] = m!(a[0],b[3]) + m!(a[1],b[2]) + m!(a[2],b[1]) + m!(a[3],b[0]);
res[4] = m!(a[0],b[4]) + m!(a[1],b[3]) + m!(a[2],b[2]) + m!(a[3],b[1]) + m!(a[4],b[0]);
res[5] = m!(a[1],b[4]) + m!(a[2],b[3]) + m!(a[3],b[2]) + m!(a[4],b[1]);
res[6] = m!(a[2],b[4]) + m!(a[3],b[3]) + m!(a[4],b[2]);
res[7] = m!(a[3],b[4]) + m!(a[4],b[3]);
res[8] = m!(a[4],b[4]);
res
}
/// Compute `a^2`.
///
/// This operation returns a double precision result.
/// So it gives back a `[u128; 9]` with the result of the squaring.
#[inline]
pub(self) fn square_internal(a: &Scalar) -> [u128; 9] {
let a_sqrt = [
a[0]*2,
a[1]*2,
a[2]*2,
a[3]*2,
];
[
m(a[0],a[0]),
m(a_sqrt[0],a[1]),
m(a_sqrt[0],a[2]) + m(a[1],a[1]),
m(a_sqrt[0],a[3]) + m(a_sqrt[1],a[2]),
m(a_sqrt[0],a[4]) + m(a_sqrt[1],a[3]) + m(a[2],a[2]),
m(a_sqrt[1],a[4]) + m(a_sqrt[2],a[3]),
m(a_sqrt[2],a[4]) + m(a[3],a[3]),
m(a_sqrt[3],a[4]),
m(a[4],a[4])
]
}
/// Give the half of the Scalar value (mod l).
///
/// This op **SHOULD NEVER** be used by the end-user
/// since it's designed to allow some behaviours
/// needed on certain points of algorithm implementations.
#[inline]
#[doc(hidden)]
pub(crate) fn inner_half(self) -> Scalar {
let mut res = self.clone();
let mut remainder = 0u64;
for i in (0..5).rev() {
res[i] = res[i] + remainder;
match(res[i] == 1, res[i].is_even()){
(true, _) => {
remainder = 4503599627370496u64;
}
(_, false) => {
res[i] = res[i] - 1u64;
remainder = 4503599627370496u64;
}
(_, true) => {
remainder = 0;
}
}
res[i] = res[i] >> 1;
};
res
}
/// Compute `limbs/R` (mod l), where R is the Montgomery modulus 2^260
#[inline]
pub(self) fn montgomery_reduce(limbs: &[u128; 9]) -> Scalar {
#[inline]
fn adjustment_fact(sum: u128) -> (u128, u64) {
let p = (sum as u64).wrapping_mul(constants::LFACTOR) & ((1u64 << 52) - 1);
((sum + m(p,constants::L[0])) >> 52, p)
}
#[inline]
fn montg_red_res(sum: u128) -> (u128, u64) {
let w = (sum as u64) & ((1u64 << 52) - 1);
(sum >> 52, w)
}
let l = &constants::L;
// the first half computes the Montgomery adjustment factor n, and begins adding n*l to make limbs divisible by R
let (carry, n0) = adjustment_fact( limbs[0]);
let (carry, n1) = adjustment_fact(carry + limbs[1] + m(n0,l[1]));
let (carry, n2) = adjustment_fact(carry + limbs[2] + m(n0,l[2]) + m(n1,l[1]));
let (carry, n3) = adjustment_fact(carry + limbs[3] + m(n0,l[3]) + m(n1,l[2]) + m(n2,l[1]));
let (carry, n4) = adjustment_fact(carry + limbs[4] + m(n0,l[4]) + m(n1,l[3]) + m(n2,l[2]) + m(n3,l[1]));
// limbs is divisible by R now, so we can divide by R by simply storing the upper half as the result
let (carry, r0) = montg_red_res(carry + limbs[5] + m(n1,l[4]) + m(n2,l[3]) + m(n3,l[2]) + m(n4,l[1]));
let (carry, r1) = montg_red_res(carry + limbs[6] + m(n2,l[4]) + m(n3,l[3]) + m(n4,l[2]));
let (carry, r2) = montg_red_res(carry + limbs[7] + m(n3,l[4]) + m(n4,l[3]));
let (carry, r3) = montg_red_res(carry + limbs[8] + m(n4,l[4]));
let r4 = carry as u64;
// result may be >= r, so attempt to subtract l
&Scalar([r0,r1,r2,r3,r4]) - l
}
/// Compute `(a * b) / R` (mod l), where R is the Montgomery modulus 2^260
#[inline]
#[allow(dead_code)]
pub(self) fn montgomery_mul(a: &Scalar, b: &Scalar) -> Scalar {
Scalar::montgomery_reduce(&Scalar::mul_internal(a, b))
}
/// Puts a Scalar into Montgomery form, i.e. computes `a*R (mod l)`
#[inline]
#[allow(dead_code)]
pub(self) fn to_montgomery(&self) -> Scalar {
Scalar::montgomery_mul(self, &constants::RR)
}
/// Takes a Scalar out of Montgomery form, i.e. computes `a/R (mod l)`
#[inline]
#[allow(dead_code)]
pub(self) fn from_montgomery(&self) -> Scalar {
let mut limbs = [0u128; 9];
for i in 0..5 {
limbs[i] = self[i] as u128;
}
Scalar::montgomery_reduce(&limbs)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `A = 182687704666362864775460604089535377456991567872`.
pub static A: Scalar = Scalar([0, 0, 0, 2, 0]);
/// `B = 904625697166532776746648320197686575422163851717637391703244652875051672039`
pub static B: Scalar = Scalar([2766226127823335, 4237835465749098, 4503599626623787, 4503599627370493, 2199023255551]);
/// `AB = A - B = -904625697166532776746648320014998870755800986942176787613709275418060104167 (mod l)`.
/// which is equal to: `365375409332725729550921208179070754913983135744`.
pub static AB: Scalar = Scalar([0, 0, 0, 4, 0]);
/// `BA = B - A = 904625697166532776746648320014998870755800986942176787613709275418060104167`.
pub static BA: Scalar = Scalar([2766226127823335, 4237835465749098, 4503599626623787, 4503599627370491, 2199023255551]);
/// `A * AB (mod l). Result expected of the product mentioned before.
pub static A_TIMES_AB: [u128; 9] = [0,0,0,0,0,0,0,8,0];
/// `B * BA` computed in Sage limb by limb. (Since we don't have any other way to verify it.)
pub static B_TIMES_BA: [u128; 9] =
[7652006990252481706224970522225,
23445622381543053554951959203660,
42875199347605145563220777152894,
63086978359456741425512297249892,
58465604036906492621308128018971,
40583457398062310210466901672404,
20302216644276907411437105105337,
19807040628557059606945202184,
4835703278454118652313601];
/// A in Montgomery domain; `A_MONT = (A * R) (mod l) = 295345389055300509611653655730781949282003822754281035405592286100742960688`
pub static A_MONT: Scalar = Scalar([946644518663728, 4368868487057990, 2524289321948647, 594442899788814, 717944870444]);
/// `X = 1809251394333065553493296640760748560207343510400633813116524750123642650623`
pub static X: Scalar = Scalar([4503599627370495, 4503599627370495, 4503599627370495, 4503599627370495, 4398046511103]);
/// `Y = 717350576871794411262215878514291949349241575907629849852603275827191647632`.
pub static Y: Scalar = Scalar([138340288859536, 461913478537005, 1182880083788836, 1688835920473363, 1743782656037]);
/// `Y^2 (mod l) = 351405481126033478170820083848817267677692781462667634162278835827410585241`.
pub static Y_SQ: Scalar = Scalar([2359521284310681, 3823495160731511, 2863901539039406, 2131140264591444, 854219405379]);
/// `Y/2 = 358675288435897205631107939257145974674620787953814924926301637913595823816`.
pub static Y_HALF: Scalar = Scalar([2320969958115016, 230956739268502, 2843239855579666, 3096217773921929, 871891328018]);
/// Y in Montgomery domain; `Y_MONT = (Y * R) (mod l) = 682963356548663143913382285837893622221394109239214830065314998385324548003`
pub static Y_MONT: Scalar = Scalar([2328716356837283, 1997480944140188, 4481133454453893, 3196446152249575, 1660191953914]);
/// `(X * Y)/R (mod l) = 781842614815424000988673591006250240924873016371899513350486876443913409068`
pub static X_TIMES_Y_MONT: Scalar = Scalar([1458967730377260, 963769115966027, 34859148282403, 2124040828839810, 1900554115968]);
/// `X * Y (mod l) = 890263784947025690345271110799906008759402458672628420828189878638015362081`
pub static X_TIMES_Y: Scalar = Scalar([3414372756436001, 1500062170770321, 4341044393209371, 2791496957276064, 2164111380879]);
//------------------ Tests ------------------//
#[test]
fn partial_ord_and_eq() {
assert!(Y.is_even());
assert!(!X.is_even());
assert!(A_MONT < Y);
assert!(Y < X);
assert!(Y >= Y);
assert!(X == X);
}
#[test]
fn add_with_modulo() {
let res = A + B;
let zero = Scalar::zero();;
for i in 0..5 {
assert!(res[i] == zero[i]);
}
}
#[test]
fn sub_with_modulo() {
let res = A - B;
for i in 0..5 {
assert!(res[i] == AB[i]);
}
}
#[test]
fn sub_without_modulo() {
let res = B - A;
for i in 0..5 {
assert!(res[i] == BA[i]);
}
}
#[test]
fn mul_internal() {
let easy_res = Scalar::mul_internal(&A, &AB);
for i in 0..5 {
assert!(easy_res[i] == A_TIMES_AB[i]);
}
let res = Scalar::mul_internal(&B, &BA);
for i in 0..9 {
assert!(res[i] == B_TIMES_BA[i]);
}
}
#[test]
fn square_internal() {
let easy_res = Scalar::square_internal(&AB);
let res_correct: [u128; 9] = [0,0,0,0,0,0,16,0,0];
for i in 0..5 {
assert!(easy_res[i] == res_correct[i]);
}
}
#[test]
fn to_montgomery_conversion() {
let a = Scalar::to_montgomery(&A);
for i in 0..5 {
assert!(a[i] == A_MONT[i]);
}
}
#[test]
fn from_montgomery_conversion() {
let y = Scalar::from_montgomery(&Y_MONT);
for i in 0..5 {
assert!(y[i] == Y[i]);
}
}
#[test]
fn scalar_mul() {
let res = &X * &Y;
for i in 0..5 {
assert!(res[i] == X_TIMES_Y[i]);
}
}
#[test]
fn mul_by_identity() {
let res = &Y * &Scalar::identity();
println!("{:?}", res);
for i in 0..5 {
assert!(res[i] == Y[i]);
}
}
#[test]
fn mul_by_zero() {
let res = &Y * &Scalar::zero();
for i in 0..5 {
assert!(res[i] == Scalar::zero()[i]);
}
}
#[test]
fn montgomery_mul() {
let res = Scalar::montgomery_mul(&X, &Y);
for i in 0..5 {
assert!(res[i] == X_TIMES_Y_MONT[i]);
}
}
#[test]
fn square() {
let res = &Y.square();
for i in 0..5 {
assert!(res[i] == Y_SQ[i]);
}
}
#[test]
fn square_zero_and_identity() {
let zero = &Scalar::zero().square();
let one = &Scalar::identity().square();
for i in 0..5 {
assert!(zero[i] == Scalar::zero()[i]);
assert!(one[i] == Scalar::one()[i]);
}
}
#[test]
fn half() {
let res = &Y.half();
for i in 0..5 {
assert!(res[i] == Y_HALF[i]);
}
let a_half = Scalar([0, 0, 0, 1, 0]);
let a_half_half = Scalar([0, 0, 2251799813685248, 0, 0]);
for i in 0..5 {
assert!(a_half[i] == A.half()[i]);
assert!(a_half_half[i] == A.half().half()[i]);
}
}
#[test]
fn even_scalar() {
assert!(Y.is_even());
assert!(!X.is_even());
assert!(Scalar::zero().is_even());
}
}
| true |
5fa49c2cdc373e29c2566069b44de7cb23242a57
|
Rust
|
d-plaindoux/celma
|
/core/tests/parser/option.rs
|
UTF-8
| 1,214 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
Copyright 2019-2023 Didier Plaindoux
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#[cfg(test)]
mod tests_option {
use celma_core::parser::char::char;
use celma_core::parser::option::OptionalOperation;
use celma_core::parser::parser::Parse;
use celma_core::stream::char_stream::CharStream;
#[test]
fn it_parse_zero_character() {
let response = char('a').opt().parse(CharStream::new(""));
assert_eq!(response.fold(|v, _, _| v == None, |_, _| false), true);
}
#[test]
fn it_parse_one_character() {
let response = char('a').opt().parse(CharStream::new("a"));
assert_eq!(response.fold(|v, _, _| v == Some('a'), |_, _| true), true);
}
}
| true |
c11696102b9b31b3d38a937fd6f9baf8c82915b4
|
Rust
|
jugglerchris/aoc2017
|
/examples/day5.rs
|
UTF-8
| 1,155 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
#![feature(conservative_impl_trait)]
extern crate aoc2017;
fn solve(input: &str) -> isize {
let mut data = aoc2017::parse_lines::<isize>(input);
let mut count = 0;
let mut pc = 0;
loop {
let newpc = pc + data[pc as usize];
data[pc as usize] += 1;
count += 1;
if (newpc as usize) >= data.len() || newpc < 0 {
return count;
}
pc = newpc;
}
}
fn solve2(input: &str) -> isize {
let mut data = aoc2017::parse_lines::<isize>(input);
let mut count = 0;
let mut pc = 0;
loop {
let offset = data[pc as usize];
let newpc = pc + offset;
let newoffset = if offset >= 3 { offset-1 } else { offset+1 };
data[pc as usize] = newoffset;
count += 1;
if (newpc as usize) >= data.len() || newpc < 0 {
return count;
}
pc = newpc;
}
}
fn main() {
let input = aoc2017::get_input(5).unwrap();
assert_eq!(solve("0\n3\n0\n1\n-3\n"), 5);
println!("Answer part 1: {}", solve(&input));
assert_eq!(solve2("0\n3\n0\n1\n-3\n"), 10);
println!("Answer part 2: {}", solve2(&input));
}
| true |
a36ff07ed4e69971dbcfffd4d3376303304bf69c
|
Rust
|
ZcashFoundation/librustzcash
|
/zcash_client_sqlite/src/lib.rs
|
UTF-8
| 26,572 | 2.578125 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//! *An SQLite-based Zcash light client.*
//!
//! `zcash_client_sqlite` contains complete SQLite-based implementations of the [`WalletRead`],
//! [`WalletWrite`], and [`BlockSource`] traits from the [`zcash_client_backend`] crate. In
//! combination with [`zcash_client_backend`], it provides a full implementation of a SQLite-backed
//! client for the Zcash network.
//!
//! # Design
//!
//! The light client is built around two SQLite databases:
//!
//! - A cache database, used to inform the light client about new [`CompactBlock`]s. It is
//! read-only within all light client APIs *except* for [`init_cache_database`] which
//! can be used to initialize the database.
//!
//! - A data database, where the light client's state is stored. It is read-write within
//! the light client APIs, and **assumed to be read-only outside these APIs**. Callers
//! **MUST NOT** write to the database without using these APIs. Callers **MAY** read
//! the database directly in order to extract information for display to users.
//!
//! # Features
//!
//! The `mainnet` feature configures the light client for use with the Zcash mainnet. By
//! default, the light client is configured for use with the Zcash testnet.
//!
//! [`WalletRead`]: zcash_client_backend::data_api::WalletRead
//! [`WalletWrite`]: zcash_client_backend::data_api::WalletWrite
//! [`BlockSource`]: zcash_client_backend::data_api::BlockSource
//! [`CompactBlock`]: zcash_client_backend::proto::compact_formats::CompactBlock
//! [`init_cache_database`]: crate::chain::init::init_cache_database
// Catch documentation errors caused by code changes.
#![deny(broken_intra_doc_links)]
use std::collections::HashMap;
use std::fmt;
use std::path::Path;
use rusqlite::{Connection, Statement, NO_PARAMS};
use zcash_primitives::{
block::BlockHash,
consensus::{self, BlockHeight},
memo::Memo,
merkle_tree::{CommitmentTree, IncrementalWitness},
sapling::{Node, Nullifier, PaymentAddress},
transaction::{components::Amount, TxId},
zip32::ExtendedFullViewingKey,
};
use zcash_client_backend::{
data_api::{
BlockSource, PrunedBlock, ReceivedTransaction, SentTransaction, WalletRead, WalletWrite,
},
encoding::encode_payment_address,
proto::compact_formats::CompactBlock,
wallet::{AccountId, SpendableNote},
};
use crate::error::SqliteClientError;
pub mod chain;
pub mod error;
pub mod wallet;
/// A newtype wrapper for sqlite primary key values for the notes
/// table.
#[derive(Debug, Copy, Clone)]
pub enum NoteId {
SentNoteId(i64),
ReceivedNoteId(i64),
}
impl fmt::Display for NoteId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
NoteId::SentNoteId(id) => write!(f, "Sent Note {}", id),
NoteId::ReceivedNoteId(id) => write!(f, "Received Note {}", id),
}
}
}
/// A wrapper for the SQLite connection to the wallet database.
pub struct WalletDb<P> {
conn: Connection,
params: P,
}
impl<P: consensus::Parameters> WalletDb<P> {
/// Construct a connection to the wallet database stored at the specified path.
pub fn for_path<F: AsRef<Path>>(path: F, params: P) -> Result<Self, rusqlite::Error> {
Connection::open(path).map(move |conn| WalletDb { conn, params })
}
/// Given a wallet database connection, obtain a handle for the write operations
/// for that database. This operation may eagerly initialize and cache sqlite
/// prepared statements that are used in write operations.
pub fn get_update_ops(&self) -> Result<DataConnStmtCache<'_, P>, SqliteClientError> {
Ok(
DataConnStmtCache {
wallet_db: self,
stmt_insert_block: self.conn.prepare(
"INSERT INTO blocks (height, hash, time, sapling_tree)
VALUES (?, ?, ?, ?)",
)?,
stmt_insert_tx_meta: self.conn.prepare(
"INSERT INTO transactions (txid, block, tx_index)
VALUES (?, ?, ?)",
)?,
stmt_update_tx_meta: self.conn.prepare(
"UPDATE transactions
SET block = ?, tx_index = ? WHERE txid = ?",
)?,
stmt_insert_tx_data: self.conn.prepare(
"INSERT INTO transactions (txid, created, expiry_height, raw)
VALUES (?, ?, ?, ?)",
)?,
stmt_update_tx_data: self.conn.prepare(
"UPDATE transactions
SET expiry_height = ?, raw = ? WHERE txid = ?",
)?,
stmt_select_tx_ref: self.conn.prepare(
"SELECT id_tx FROM transactions WHERE txid = ?",
)?,
stmt_mark_recived_note_spent: self.conn.prepare(
"UPDATE received_notes SET spent = ? WHERE nf = ?"
)?,
stmt_insert_received_note: self.conn.prepare(
"INSERT INTO received_notes (tx, output_index, account, diversifier, value, rcm, memo, nf, is_change)
VALUES (:tx, :output_index, :account, :diversifier, :value, :rcm, :memo, :nf, :is_change)",
)?,
stmt_update_received_note: self.conn.prepare(
"UPDATE received_notes
SET account = :account,
diversifier = :diversifier,
value = :value,
rcm = :rcm,
nf = IFNULL(:nf, nf),
memo = IFNULL(:memo, memo),
is_change = IFNULL(:is_change, is_change)
WHERE tx = :tx AND output_index = :output_index",
)?,
stmt_select_received_note: self.conn.prepare(
"SELECT id_note FROM received_notes WHERE tx = ? AND output_index = ?"
)?,
stmt_update_sent_note: self.conn.prepare(
"UPDATE sent_notes
SET from_account = ?, address = ?, value = ?, memo = ?
WHERE tx = ? AND output_index = ?",
)?,
stmt_insert_sent_note: self.conn.prepare(
"INSERT INTO sent_notes (tx, output_index, from_account, address, value, memo)
VALUES (?, ?, ?, ?, ?, ?)",
)?,
stmt_insert_witness: self.conn.prepare(
"INSERT INTO sapling_witnesses (note, block, witness)
VALUES (?, ?, ?)",
)?,
stmt_prune_witnesses: self.conn.prepare(
"DELETE FROM sapling_witnesses WHERE block < ?"
)?,
stmt_update_expired: self.conn.prepare(
"UPDATE received_notes SET spent = NULL WHERE EXISTS (
SELECT id_tx FROM transactions
WHERE id_tx = received_notes.spent AND block IS NULL AND expiry_height < ?
)",
)?,
}
)
}
}
impl<P: consensus::Parameters> WalletRead for WalletDb<P> {
type Error = SqliteClientError;
type NoteRef = NoteId;
type TxRef = i64;
fn block_height_extrema(&self) -> Result<Option<(BlockHeight, BlockHeight)>, Self::Error> {
wallet::block_height_extrema(self).map_err(SqliteClientError::from)
}
fn get_block_hash(&self, block_height: BlockHeight) -> Result<Option<BlockHash>, Self::Error> {
wallet::get_block_hash(self, block_height).map_err(SqliteClientError::from)
}
fn get_tx_height(&self, txid: TxId) -> Result<Option<BlockHeight>, Self::Error> {
wallet::get_tx_height(self, txid).map_err(SqliteClientError::from)
}
fn get_extended_full_viewing_keys(
&self,
) -> Result<HashMap<AccountId, ExtendedFullViewingKey>, Self::Error> {
wallet::get_extended_full_viewing_keys(self)
}
fn get_address(&self, account: AccountId) -> Result<Option<PaymentAddress>, Self::Error> {
wallet::get_address(self, account)
}
fn is_valid_account_extfvk(
&self,
account: AccountId,
extfvk: &ExtendedFullViewingKey,
) -> Result<bool, Self::Error> {
wallet::is_valid_account_extfvk(self, account, extfvk)
}
fn get_balance_at(
&self,
account: AccountId,
anchor_height: BlockHeight,
) -> Result<Amount, Self::Error> {
wallet::get_balance_at(self, account, anchor_height)
}
fn get_memo(&self, id_note: Self::NoteRef) -> Result<Memo, Self::Error> {
match id_note {
NoteId::SentNoteId(id_note) => wallet::get_sent_memo(self, id_note),
NoteId::ReceivedNoteId(id_note) => wallet::get_received_memo(self, id_note),
}
}
fn get_commitment_tree(
&self,
block_height: BlockHeight,
) -> Result<Option<CommitmentTree<Node>>, Self::Error> {
wallet::get_commitment_tree(self, block_height)
}
#[allow(clippy::type_complexity)]
fn get_witnesses(
&self,
block_height: BlockHeight,
) -> Result<Vec<(Self::NoteRef, IncrementalWitness<Node>)>, Self::Error> {
wallet::get_witnesses(self, block_height)
}
fn get_nullifiers(&self) -> Result<Vec<(AccountId, Nullifier)>, Self::Error> {
wallet::get_nullifiers(self)
}
fn get_spendable_notes(
&self,
account: AccountId,
anchor_height: BlockHeight,
) -> Result<Vec<SpendableNote>, Self::Error> {
wallet::transact::get_spendable_notes(self, account, anchor_height)
}
fn select_spendable_notes(
&self,
account: AccountId,
target_value: Amount,
anchor_height: BlockHeight,
) -> Result<Vec<SpendableNote>, Self::Error> {
wallet::transact::select_spendable_notes(self, account, target_value, anchor_height)
}
}
/// The primary type used to implement [`WalletWrite`] for the SQLite database.
///
/// A data structure that stores the SQLite prepared statements that are
/// required for the implementation of [`WalletWrite`] against the backing
/// store.
///
/// [`WalletWrite`]: zcash_client_backend::data_api::WalletWrite
pub struct DataConnStmtCache<'a, P> {
wallet_db: &'a WalletDb<P>,
stmt_insert_block: Statement<'a>,
stmt_insert_tx_meta: Statement<'a>,
stmt_update_tx_meta: Statement<'a>,
stmt_insert_tx_data: Statement<'a>,
stmt_update_tx_data: Statement<'a>,
stmt_select_tx_ref: Statement<'a>,
stmt_mark_recived_note_spent: Statement<'a>,
stmt_insert_received_note: Statement<'a>,
stmt_update_received_note: Statement<'a>,
stmt_select_received_note: Statement<'a>,
stmt_insert_sent_note: Statement<'a>,
stmt_update_sent_note: Statement<'a>,
stmt_insert_witness: Statement<'a>,
stmt_prune_witnesses: Statement<'a>,
stmt_update_expired: Statement<'a>,
}
impl<'a, P: consensus::Parameters> WalletRead for DataConnStmtCache<'a, P> {
type Error = SqliteClientError;
type NoteRef = NoteId;
type TxRef = i64;
fn block_height_extrema(&self) -> Result<Option<(BlockHeight, BlockHeight)>, Self::Error> {
self.wallet_db.block_height_extrema()
}
fn get_block_hash(&self, block_height: BlockHeight) -> Result<Option<BlockHash>, Self::Error> {
self.wallet_db.get_block_hash(block_height)
}
fn get_tx_height(&self, txid: TxId) -> Result<Option<BlockHeight>, Self::Error> {
self.wallet_db.get_tx_height(txid)
}
fn get_extended_full_viewing_keys(
&self,
) -> Result<HashMap<AccountId, ExtendedFullViewingKey>, Self::Error> {
self.wallet_db.get_extended_full_viewing_keys()
}
fn get_address(&self, account: AccountId) -> Result<Option<PaymentAddress>, Self::Error> {
self.wallet_db.get_address(account)
}
fn is_valid_account_extfvk(
&self,
account: AccountId,
extfvk: &ExtendedFullViewingKey,
) -> Result<bool, Self::Error> {
self.wallet_db.is_valid_account_extfvk(account, extfvk)
}
fn get_balance_at(
&self,
account: AccountId,
anchor_height: BlockHeight,
) -> Result<Amount, Self::Error> {
self.wallet_db.get_balance_at(account, anchor_height)
}
fn get_memo(&self, id_note: Self::NoteRef) -> Result<Memo, Self::Error> {
self.wallet_db.get_memo(id_note)
}
fn get_commitment_tree(
&self,
block_height: BlockHeight,
) -> Result<Option<CommitmentTree<Node>>, Self::Error> {
self.wallet_db.get_commitment_tree(block_height)
}
#[allow(clippy::type_complexity)]
fn get_witnesses(
&self,
block_height: BlockHeight,
) -> Result<Vec<(Self::NoteRef, IncrementalWitness<Node>)>, Self::Error> {
self.wallet_db.get_witnesses(block_height)
}
fn get_nullifiers(&self) -> Result<Vec<(AccountId, Nullifier)>, Self::Error> {
self.wallet_db.get_nullifiers()
}
fn get_spendable_notes(
&self,
account: AccountId,
anchor_height: BlockHeight,
) -> Result<Vec<SpendableNote>, Self::Error> {
self.wallet_db.get_spendable_notes(account, anchor_height)
}
fn select_spendable_notes(
&self,
account: AccountId,
target_value: Amount,
anchor_height: BlockHeight,
) -> Result<Vec<SpendableNote>, Self::Error> {
self.wallet_db
.select_spendable_notes(account, target_value, anchor_height)
}
}
impl<'a, P: consensus::Parameters> DataConnStmtCache<'a, P> {
fn transactionally<F, A>(&mut self, f: F) -> Result<A, SqliteClientError>
where
F: FnOnce(&mut Self) -> Result<A, SqliteClientError>,
{
self.wallet_db.conn.execute("BEGIN IMMEDIATE", NO_PARAMS)?;
match f(self) {
Ok(result) => {
self.wallet_db.conn.execute("COMMIT", NO_PARAMS)?;
Ok(result)
}
Err(error) => {
match self.wallet_db.conn.execute("ROLLBACK", NO_PARAMS) {
Ok(_) => Err(error),
Err(e) =>
// Panicking here is probably the right thing to do, because it
// means the database is corrupt.
panic!(
"Rollback failed with error {} while attempting to recover from error {}; database is likely corrupt.",
e,
error
)
}
}
}
}
}
impl<'a, P: consensus::Parameters> WalletWrite for DataConnStmtCache<'a, P> {
#[allow(clippy::type_complexity)]
fn advance_by_block(
&mut self,
block: &PrunedBlock,
updated_witnesses: &[(Self::NoteRef, IncrementalWitness<Node>)],
) -> Result<Vec<(Self::NoteRef, IncrementalWitness<Node>)>, Self::Error> {
// database updates for each block are transactional
self.transactionally(|up| {
// Insert the block into the database.
wallet::insert_block(
up,
block.block_height,
block.block_hash,
block.block_time,
&block.commitment_tree,
)?;
let mut new_witnesses = vec![];
for tx in block.transactions {
let tx_row = wallet::put_tx_meta(up, &tx, block.block_height)?;
// Mark notes as spent and remove them from the scanning cache
for spend in &tx.shielded_spends {
wallet::mark_spent(up, tx_row, &spend.nf)?;
}
for output in &tx.shielded_outputs {
let received_note_id = wallet::put_received_note(up, output, tx_row)?;
// Save witness for note.
new_witnesses.push((received_note_id, output.witness.clone()));
}
}
// Insert current new_witnesses into the database.
for (received_note_id, witness) in updated_witnesses.iter().chain(new_witnesses.iter())
{
if let NoteId::ReceivedNoteId(rnid) = *received_note_id {
wallet::insert_witness(up, rnid, witness, block.block_height)?;
} else {
return Err(SqliteClientError::InvalidNoteId);
}
}
// Prune the stored witnesses (we only expect rollbacks of at most 100 blocks).
wallet::prune_witnesses(up, block.block_height - 100)?;
// Update now-expired transactions that didn't get mined.
wallet::update_expired_notes(up, block.block_height)?;
Ok(new_witnesses)
})
}
fn store_received_tx(
&mut self,
received_tx: &ReceivedTransaction,
) -> Result<Self::TxRef, Self::Error> {
self.transactionally(|up| {
let tx_ref = wallet::put_tx_data(up, received_tx.tx, None)?;
for output in received_tx.outputs {
if output.outgoing {
wallet::put_sent_note(up, output, tx_ref)?;
} else {
wallet::put_received_note(up, output, tx_ref)?;
}
}
Ok(tx_ref)
})
}
fn store_sent_tx(&mut self, sent_tx: &SentTransaction) -> Result<Self::TxRef, Self::Error> {
// Update the database atomically, to ensure the result is internally consistent.
self.transactionally(|up| {
let tx_ref = wallet::put_tx_data(up, &sent_tx.tx, Some(sent_tx.created))?;
// Mark notes as spent.
//
// This locks the notes so they aren't selected again by a subsequent call to
// create_spend_to_address() before this transaction has been mined (at which point the notes
// get re-marked as spent).
//
// Assumes that create_spend_to_address() will never be called in parallel, which is a
// reasonable assumption for a light client such as a mobile phone.
if let Some(bundle) = sent_tx.tx.sapling_bundle() {
for spend in &bundle.shielded_spends {
wallet::mark_spent(up, tx_ref, &spend.nullifier)?;
}
}
wallet::insert_sent_note(
up,
tx_ref,
sent_tx.output_index,
sent_tx.account,
sent_tx.recipient_address,
sent_tx.value,
sent_tx.memo.as_ref(),
)?;
// Return the row number of the transaction, so the caller can fetch it for sending.
Ok(tx_ref)
})
}
fn rewind_to_height(&mut self, block_height: BlockHeight) -> Result<(), Self::Error> {
wallet::rewind_to_height(self.wallet_db, block_height)
}
}
/// A wrapper for the SQLite connection to the block cache database.
pub struct BlockDb(Connection);
impl BlockDb {
/// Opens a connection to the wallet database stored at the specified path.
pub fn for_path<P: AsRef<Path>>(path: P) -> Result<Self, rusqlite::Error> {
Connection::open(path).map(BlockDb)
}
}
impl BlockSource for BlockDb {
type Error = SqliteClientError;
fn with_blocks<F>(
&self,
from_height: BlockHeight,
limit: Option<u32>,
with_row: F,
) -> Result<(), Self::Error>
where
F: FnMut(CompactBlock) -> Result<(), Self::Error>,
{
chain::with_blocks(self, from_height, limit, with_row)
}
}
fn address_from_extfvk<P: consensus::Parameters>(
params: &P,
extfvk: &ExtendedFullViewingKey,
) -> String {
let addr = extfvk.default_address().1;
encode_payment_address(params.hrp_sapling_payment_address(), &addr)
}
#[cfg(test)]
mod tests {
use ff::PrimeField;
use group::GroupEncoding;
use protobuf::Message;
use rand_core::{OsRng, RngCore};
use rusqlite::params;
use zcash_client_backend::proto::compact_formats::{
CompactBlock, CompactOutput, CompactSpend, CompactTx,
};
use zcash_primitives::{
block::BlockHash,
consensus::{BlockHeight, Network, NetworkUpgrade, Parameters},
memo::MemoBytes,
sapling::{
note_encryption::sapling_note_encryption, util::generate_random_rseed, Note, Nullifier,
PaymentAddress,
},
transaction::components::Amount,
zip32::ExtendedFullViewingKey,
};
use super::BlockDb;
#[cfg(feature = "mainnet")]
pub(crate) fn network() -> Network {
Network::MainNetwork
}
#[cfg(not(feature = "mainnet"))]
pub(crate) fn network() -> Network {
Network::TestNetwork
}
#[cfg(feature = "mainnet")]
pub(crate) fn sapling_activation_height() -> BlockHeight {
Network::MainNetwork
.activation_height(NetworkUpgrade::Sapling)
.unwrap()
}
#[cfg(not(feature = "mainnet"))]
pub(crate) fn sapling_activation_height() -> BlockHeight {
Network::TestNetwork
.activation_height(NetworkUpgrade::Sapling)
.unwrap()
}
/// Create a fake CompactBlock at the given height, containing a single output paying
/// the given address. Returns the CompactBlock and the nullifier for the new note.
pub(crate) fn fake_compact_block(
height: BlockHeight,
prev_hash: BlockHash,
extfvk: ExtendedFullViewingKey,
value: Amount,
) -> (CompactBlock, Nullifier) {
let to = extfvk.default_address().1;
// Create a fake Note for the account
let mut rng = OsRng;
let rseed = generate_random_rseed(&network(), height, &mut rng);
let note = Note {
g_d: to.diversifier().g_d().unwrap(),
pk_d: *to.pk_d(),
value: value.into(),
rseed,
};
let encryptor = sapling_note_encryption::<_, Network>(
Some(extfvk.fvk.ovk),
note.clone(),
to,
MemoBytes::empty(),
&mut rng,
);
let cmu = note.cmu().to_repr().as_ref().to_vec();
let epk = encryptor.epk().to_bytes().to_vec();
let enc_ciphertext = encryptor.encrypt_note_plaintext();
// Create a fake CompactBlock containing the note
let mut cout = CompactOutput::new();
cout.set_cmu(cmu);
cout.set_epk(epk);
cout.set_ciphertext(enc_ciphertext.as_ref()[..52].to_vec());
let mut ctx = CompactTx::new();
let mut txid = vec![0; 32];
rng.fill_bytes(&mut txid);
ctx.set_hash(txid);
ctx.outputs.push(cout);
let mut cb = CompactBlock::new();
cb.set_height(u64::from(height));
cb.hash.resize(32, 0);
rng.fill_bytes(&mut cb.hash);
cb.prevHash.extend_from_slice(&prev_hash.0);
cb.vtx.push(ctx);
(cb, note.nf(&extfvk.fvk.vk, 0))
}
/// Create a fake CompactBlock at the given height, spending a single note from the
/// given address.
pub(crate) fn fake_compact_block_spending(
height: BlockHeight,
prev_hash: BlockHash,
(nf, in_value): (Nullifier, Amount),
extfvk: ExtendedFullViewingKey,
to: PaymentAddress,
value: Amount,
) -> CompactBlock {
let mut rng = OsRng;
let rseed = generate_random_rseed(&network(), height, &mut rng);
// Create a fake CompactBlock containing the note
let mut cspend = CompactSpend::new();
cspend.set_nf(nf.to_vec());
let mut ctx = CompactTx::new();
let mut txid = vec![0; 32];
rng.fill_bytes(&mut txid);
ctx.set_hash(txid);
ctx.spends.push(cspend);
// Create a fake Note for the payment
ctx.outputs.push({
let note = Note {
g_d: to.diversifier().g_d().unwrap(),
pk_d: *to.pk_d(),
value: value.into(),
rseed,
};
let encryptor = sapling_note_encryption::<_, Network>(
Some(extfvk.fvk.ovk),
note.clone(),
to,
MemoBytes::empty(),
&mut rng,
);
let cmu = note.cmu().to_repr().as_ref().to_vec();
let epk = encryptor.epk().to_bytes().to_vec();
let enc_ciphertext = encryptor.encrypt_note_plaintext();
let mut cout = CompactOutput::new();
cout.set_cmu(cmu);
cout.set_epk(epk);
cout.set_ciphertext(enc_ciphertext.as_ref()[..52].to_vec());
cout
});
// Create a fake Note for the change
ctx.outputs.push({
let change_addr = extfvk.default_address().1;
let rseed = generate_random_rseed(&network(), height, &mut rng);
let note = Note {
g_d: change_addr.diversifier().g_d().unwrap(),
pk_d: *change_addr.pk_d(),
value: (in_value - value).unwrap().into(),
rseed,
};
let encryptor = sapling_note_encryption::<_, Network>(
Some(extfvk.fvk.ovk),
note.clone(),
change_addr,
MemoBytes::empty(),
&mut rng,
);
let cmu = note.cmu().to_repr().as_ref().to_vec();
let epk = encryptor.epk().to_bytes().to_vec();
let enc_ciphertext = encryptor.encrypt_note_plaintext();
let mut cout = CompactOutput::new();
cout.set_cmu(cmu);
cout.set_epk(epk);
cout.set_ciphertext(enc_ciphertext.as_ref()[..52].to_vec());
cout
});
let mut cb = CompactBlock::new();
cb.set_height(u64::from(height));
cb.hash.resize(32, 0);
rng.fill_bytes(&mut cb.hash);
cb.prevHash.extend_from_slice(&prev_hash.0);
cb.vtx.push(ctx);
cb
}
/// Insert a fake CompactBlock into the cache DB.
pub(crate) fn insert_into_cache(db_cache: &BlockDb, cb: &CompactBlock) {
let cb_bytes = cb.write_to_bytes().unwrap();
db_cache
.0
.prepare("INSERT INTO compactblocks (height, data) VALUES (?, ?)")
.unwrap()
.execute(params![u32::from(cb.height()), cb_bytes,])
.unwrap();
}
}
| true |
5690194a79be769bf81a7dd514c412d3e77cfba2
|
Rust
|
GregBowyer/rust-ar
|
/src/lib.rs
|
UTF-8
| 77,765 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
//! A library for encoding/decoding Unix archive files.
//!
//! This library provides utilities necessary to manage [Unix archive
//! files](https://en.wikipedia.org/wiki/Ar_(Unix)) (as generated by the
//! standard `ar` command line utility) abstracted over a reader or writer.
//! This library provides a streaming interface that avoids having to ever load
//! a full archive entry into memory.
//!
//! The API of this crate is meant to be similar to that of the
//! [`tar`](https://crates.io/crates/tar) crate.
//!
//! # Format variants
//!
//! Unix archive files come in several variants, of which three are the most
//! common:
//!
//! * The *common variant*, used for Debian package (`.deb`) files among other
//! things, which only supports filenames up to 16 characters.
//! * The *BSD variant*, used by the `ar` utility on BSD systems (including Mac
//! OS X), which is backwards-compatible with the common variant, but extends
//! it to support longer filenames and filenames containing spaces.
//! * The *GNU variant*, used by the `ar` utility on GNU and many other systems
//! (including Windows), which is similar to the common format, but which
//! stores filenames in a slightly different, incompatible way, and has its
//! own strategy for supporting long filenames.
//!
//! This crate supports reading and writing all three of these variants.
//!
//! # Example usage
//!
//! Writing an archive:
//!
//! ```no_run
//! use ar::Builder;
//! use std::fs::File;
//! // Create a new archive that will be written to foo.a:
//! let mut builder = Builder::new(File::create("foo.a").unwrap());
//! // Add foo/bar.txt to the archive, under the name "bar.txt":
//! builder.append_path("foo/bar.txt").unwrap();
//! // Add foo/baz.txt to the archive, under the name "hello.txt":
//! let mut file = File::open("foo/baz.txt").unwrap();
//! builder.append_file(b"hello.txt", &mut file).unwrap();
//! ```
//!
//! Reading an archive:
//!
//! ```no_run
//! use ar::Archive;
//! use std::fs::File;
//! use std::io;
//! use std::str;
//! // Read an archive from the file foo.a:
//! let mut archive = Archive::new(File::open("foo.a").unwrap());
//! // Iterate over all entries in the archive:
//! while let Some(entry_result) = archive.next_entry() {
//! let mut entry = entry_result.unwrap();
//! // Create a new file with the same name as the archive entry:
//! let mut file = File::create(
//! str::from_utf8(entry.header().identifier()).unwrap(),
//! ).unwrap();
//! // The Entry object also acts as an io::Read, so we can easily copy the
//! // contents of the archive entry into the file:
//! io::copy(&mut entry, &mut file).unwrap();
//! }
//! ```
#![warn(missing_docs)]
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::fs::{File, Metadata};
use std::io::{self, BufRead, BufReader, Error, ErrorKind, Read, Result, Seek,
SeekFrom, Write};
use std::path::Path;
use std::str;
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
#[cfg(windows)]
use std::os::windows::ffi::OsStrExt;
// ========================================================================= //
fn read_le_u32(r: &mut impl io::Read) -> io::Result<u32> {
let mut buf = [0; 4];
r.read_exact(&mut buf).map(|()| u32::from_le_bytes(buf))
}
fn read_be_u32(r: &mut impl io::Read) -> io::Result<u32> {
let mut buf = [0; 4];
r.read_exact(&mut buf).map(|()| u32::from_be_bytes(buf))
}
// ========================================================================= //
const GLOBAL_HEADER_LEN: usize = 8;
const GLOBAL_HEADER: &'static [u8; GLOBAL_HEADER_LEN] = b"!<arch>\n";
const ENTRY_HEADER_LEN: usize = 60;
const BSD_SYMBOL_LOOKUP_TABLE_ID: &[u8] = b"__.SYMDEF";
const BSD_SORTED_SYMBOL_LOOKUP_TABLE_ID: &[u8] = b"__.SYMDEF SORTED";
const GNU_NAME_TABLE_ID: &str = "//";
const GNU_SYMBOL_LOOKUP_TABLE_ID: &[u8] = b"/";
// ========================================================================= //
/// Variants of the Unix archive format.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Variant {
/// Used by Debian package files; allows only short filenames.
Common,
/// Used by BSD `ar` (and OS X); backwards-compatible with common variant.
BSD,
/// Used by GNU `ar` (and Windows); incompatible with common variant.
GNU,
}
// ========================================================================= //
/// Representation of an archive entry header.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Header {
identifier: Vec<u8>,
mtime: u64,
uid: u32,
gid: u32,
mode: u32,
size: u64,
}
impl Header {
/// Creates a header with the given file identifier and size, and all
/// other fields set to zero.
pub fn new(identifier: Vec<u8>, size: u64) -> Header {
Header {
identifier,
mtime: 0,
uid: 0,
gid: 0,
mode: 0,
size,
}
}
/// Creates a header with the given file identifier and all other fields
/// set from the given filesystem metadata.
#[cfg(unix)]
pub fn from_metadata(identifier: Vec<u8>, meta: &Metadata) -> Header {
Header {
identifier,
mtime: meta.mtime() as u64,
uid: meta.uid(),
gid: meta.gid(),
mode: meta.mode(),
size: meta.len(),
}
}
#[cfg(not(unix))]
pub fn from_metadata(identifier: Vec<u8>, meta: &Metadata) -> Header {
Header::new(identifier, meta.len())
}
/// Returns the file identifier.
pub fn identifier(&self) -> &[u8] { &self.identifier }
/// Sets the file identifier.
pub fn set_identifier(&mut self, identifier: Vec<u8>) {
self.identifier = identifier;
}
/// Returns the last modification time in Unix time format.
pub fn mtime(&self) -> u64 { self.mtime }
/// Sets the last modification time in Unix time format.
pub fn set_mtime(&mut self, mtime: u64) { self.mtime = mtime; }
/// Returns the value of the owner's user ID field.
pub fn uid(&self) -> u32 { self.uid }
/// Sets the value of the owner's user ID field.
pub fn set_uid(&mut self, uid: u32) { self.uid = uid; }
/// Returns the value of the group's user ID field.
pub fn gid(&self) -> u32 { self.gid }
/// Returns the value of the group's user ID field.
pub fn set_gid(&mut self, gid: u32) { self.gid = gid; }
/// Returns the mode bits for this file.
pub fn mode(&self) -> u32 { self.mode }
/// Sets the mode bits for this file.
pub fn set_mode(&mut self, mode: u32) { self.mode = mode; }
/// Returns the length of the file, in bytes.
pub fn size(&self) -> u64 { self.size }
/// Sets the length of the file, in bytes.
pub fn set_size(&mut self, size: u64) { self.size = size; }
/// Parses and returns the next header and its length. Returns `Ok(None)`
/// if we are at EOF.
fn read<R>(reader: &mut R, variant: &mut Variant, name_table: &mut Vec<u8>)
-> Result<Option<(Header, u64)>>
where
R: Read,
{
let mut buffer = [0; 60];
let bytes_read = reader.read(&mut buffer)?;
if bytes_read == 0 {
return Ok(None);
} else if bytes_read < buffer.len() {
if let Err(error) = reader.read_exact(&mut buffer[bytes_read..]) {
if error.kind() == ErrorKind::UnexpectedEof {
let msg = "unexpected EOF in the middle of archive entry \
header";
return Err(Error::new(ErrorKind::UnexpectedEof, msg));
} else {
let msg = "failed to read archive entry header";
return Err(annotate(error, msg));
}
}
}
let mut identifier = buffer[0..16].to_vec();
while identifier.last() == Some(&b' ') {
identifier.pop();
}
let mut size = parse_number("file size", &buffer[48..58], 10)?;
let mut header_len = ENTRY_HEADER_LEN as u64;
if *variant != Variant::BSD && identifier.starts_with(b"/") {
*variant = Variant::GNU;
if identifier == GNU_SYMBOL_LOOKUP_TABLE_ID {
io::copy(&mut reader.by_ref().take(size), &mut io::sink())?;
return Ok(Some((Header::new(identifier, size), header_len)));
} else if identifier == GNU_NAME_TABLE_ID.as_bytes() {
*name_table = vec![0; size as usize];
reader.read_exact(name_table as &mut [u8]).map_err(|err| {
annotate(err, "failed to read name table")
})?;
return Ok(Some((Header::new(identifier, size), header_len)));
}
let start =
parse_number("GNU filename index", &buffer[1..16], 10)? as
usize;
let end = match name_table[start..].iter().position(|&ch| {
ch == b'/' || ch == b'\x00'
}) {
Some(len) => start + len,
None => name_table.len(),
};
identifier = name_table[start..end].to_vec();
} else if *variant != Variant::BSD && identifier.ends_with(b"/") {
*variant = Variant::GNU;
identifier.pop();
}
let mtime = parse_number("timestamp", &buffer[16..28], 10)?;
let uid = if *variant == Variant::GNU {
parse_number_permitting_empty("owner ID", &buffer[28..34], 10)?
} else {
parse_number("owner ID", &buffer[28..34], 10)?
} as u32;
let gid = if *variant == Variant::GNU {
parse_number_permitting_empty("group ID", &buffer[34..40], 10)?
} else {
parse_number("group ID", &buffer[34..40], 10)?
} as u32;
let mode = parse_number("file mode", &buffer[40..48], 8)? as u32;
if *variant != Variant::GNU && identifier.starts_with(b"#1/") {
*variant = Variant::BSD;
let padded_length =
parse_number("BSD filename length", &buffer[3..16], 10)?;
if size < padded_length {
let msg = format!(
"Entry size ({}) smaller than extended \
entry identifier length ({})",
size,
padded_length
);
return Err(Error::new(ErrorKind::InvalidData, msg));
}
size -= padded_length;
header_len += padded_length;
let mut id_buffer = vec![0; padded_length as usize];
let bytes_read = reader.read(&mut id_buffer)?;
if bytes_read < id_buffer.len() {
if let Err(error) = reader.read_exact(
&mut id_buffer[bytes_read..],
)
{
if error.kind() == ErrorKind::UnexpectedEof {
let msg = "unexpected EOF in the middle of extended \
entry identifier";
return Err(Error::new(ErrorKind::UnexpectedEof, msg));
} else {
let msg = "failed to read extended entry identifier";
return Err(annotate(error, msg));
}
}
}
while id_buffer.last() == Some(&0) {
id_buffer.pop();
}
identifier = id_buffer;
if identifier == BSD_SYMBOL_LOOKUP_TABLE_ID ||
identifier == BSD_SORTED_SYMBOL_LOOKUP_TABLE_ID
{
io::copy(&mut reader.by_ref().take(size), &mut io::sink())?;
return Ok(Some((Header::new(identifier, size), header_len)));
}
}
Ok(Some((
Header {
identifier,
mtime,
uid,
gid,
mode,
size,
},
header_len,
)))
}
fn write<W: Write>(&self, writer: &mut W) -> Result<()> {
if self.identifier.len() > 16 || self.identifier.contains(&b' ') {
let padding_length = (4 - self.identifier.len() % 4) % 4;
let padded_length = self.identifier.len() + padding_length;
write!(
writer,
"#1/{:<13}{:<12}{:<6}{:<6}{:<8o}{:<10}`\n",
padded_length,
self.mtime,
self.uid,
self.gid,
self.mode,
self.size + padded_length as u64
)?;
writer.write_all(&self.identifier)?;
writer.write_all(&vec![0; padding_length])?;
} else {
writer.write_all(&self.identifier)?;
writer.write_all(&vec![b' '; 16 - self.identifier.len()])?;
write!(
writer,
"{:<12}{:<6}{:<6}{:<8o}{:<10}`\n",
self.mtime,
self.uid,
self.gid,
self.mode,
self.size
)?;
}
Ok(())
}
fn write_gnu<W>(&self, writer: &mut W, names: &HashMap<Vec<u8>, usize>)
-> Result<()>
where
W: Write,
{
if self.identifier.len() > 15 {
let offset = names[&self.identifier];
write!(writer, "/{:<15}", offset)?;
} else {
writer.write_all(&self.identifier)?;
writer.write_all(b"/")?;
writer.write_all(&vec![b' '; 15 - self.identifier.len()])?;
}
write!(
writer,
"{:<12}{:<6}{:<6}{:<8o}{:<10}`\n",
self.mtime,
self.uid,
self.gid,
self.mode,
self.size
)?;
Ok(())
}
}
fn parse_number(field_name: &str, bytes: &[u8], radix: u32) -> Result<u64> {
if let Ok(string) = str::from_utf8(bytes) {
if let Ok(value) = u64::from_str_radix(string.trim_end(), radix) {
return Ok(value);
}
}
let msg = format!(
"Invalid {} field in entry header ({:?})",
field_name,
String::from_utf8_lossy(bytes)
);
Err(Error::new(ErrorKind::InvalidData, msg))
}
/*
* Equivalent to parse_number() except for the case of bytes being
* all spaces (eg all 0x20) as MS tools emit for UID/GID
*/
fn parse_number_permitting_empty(field_name: &str, bytes: &[u8], radix: u32)
-> Result<u64> {
if let Ok(string) = str::from_utf8(bytes) {
let trimmed = string.trim_end();
if trimmed.len() == 0 {
return Ok(0);
} else if let Ok(value) = u64::from_str_radix(trimmed, radix) {
return Ok(value);
}
}
let msg = format!(
"Invalid {} field in entry header ({:?})",
field_name,
String::from_utf8_lossy(bytes)
);
Err(Error::new(ErrorKind::InvalidData, msg))
}
// ========================================================================= //
struct HeaderAndLocation {
header: Header,
header_start: u64,
data_start: u64,
}
// ========================================================================= //
/// A structure for reading archives.
pub struct Archive<R: Read> {
reader: R,
variant: Variant,
name_table: Vec<u8>,
entry_headers: Vec<HeaderAndLocation>,
new_entry_start: u64,
next_entry_index: usize,
symbol_table_header: Option<HeaderAndLocation>,
symbol_table: Option<Vec<(Vec<u8>, u64)>>,
started: bool, // True if we've read past the global header.
padding: bool, // True if there's a padding byte before the next entry.
scanned: bool, // True if entry_headers is complete.
error: bool, // True if we have encountered an error.
}
impl<R: Read> Archive<R> {
/// Create a new archive reader with the underlying reader object as the
/// source of all data read.
pub fn new(reader: R) -> Archive<R> {
Archive {
reader,
variant: Variant::Common,
name_table: Vec::new(),
entry_headers: Vec::new(),
new_entry_start: GLOBAL_HEADER_LEN as u64,
next_entry_index: 0,
symbol_table_header: None,
symbol_table: None,
started: false,
padding: false,
scanned: false,
error: false,
}
}
/// Returns which format variant this archive appears to be so far.
///
/// Note that this may not be accurate before the archive has been fully
/// read (i.e. before the `next_entry()` method returns `None`). In
/// particular, a new `Archive` object that hasn't yet read any data at all
/// will always return `Variant::Common`.
pub fn variant(&self) -> Variant { self.variant }
/// Unwrap this archive reader, returning the underlying reader object.
pub fn into_inner(self) -> Result<R> { Ok(self.reader) }
fn is_name_table_id(&self, identifier: &[u8]) -> bool {
self.variant == Variant::GNU &&
identifier == GNU_NAME_TABLE_ID.as_bytes()
}
fn is_symbol_lookup_table_id(&self, identifier: &[u8]) -> bool {
match self.variant {
Variant::Common => false,
Variant::BSD => {
identifier == BSD_SYMBOL_LOOKUP_TABLE_ID ||
identifier == BSD_SORTED_SYMBOL_LOOKUP_TABLE_ID
}
Variant::GNU => identifier == GNU_SYMBOL_LOOKUP_TABLE_ID,
}
}
fn read_global_header_if_necessary(&mut self) -> Result<()> {
if self.started {
return Ok(());
}
let mut buffer = [0; GLOBAL_HEADER_LEN];
match self.reader.read_exact(&mut buffer) {
Ok(()) => {}
Err(error) => {
self.error = true;
return Err(annotate(error, "failed to read global header"));
}
}
if &buffer != GLOBAL_HEADER {
self.error = true;
let msg = "Not an archive file (invalid global header)";
return Err(Error::new(ErrorKind::InvalidData, msg));
}
self.started = true;
Ok(())
}
/// Reads the next entry from the archive, or returns None if there are no
/// more.
pub fn next_entry(&mut self) -> Option<Result<Entry<R>>> {
loop {
if self.error {
return None;
}
if self.scanned &&
self.next_entry_index == self.entry_headers.len()
{
return None;
}
match self.read_global_header_if_necessary() {
Ok(()) => {}
Err(error) => return Some(Err(error)),
}
if self.padding {
let mut buffer = [0u8; 1];
match self.reader.read_exact(&mut buffer) {
Ok(()) => {
if buffer[0] != b'\n' {
self.error = true;
let msg = format!("invalid padding byte ({})",
buffer[0]);
let error =
Error::new(ErrorKind::InvalidData, msg);
return Some(Err(error));
}
}
Err(error) => {
if error.kind() != ErrorKind::UnexpectedEof {
self.error = true;
let msg = "failed to read padding byte";
return Some(Err(annotate(error, msg)));
}
}
}
self.padding = false;
}
let header_start = self.new_entry_start;
match Header::read(
&mut self.reader,
&mut self.variant,
&mut self.name_table,
) {
Ok(Some((header, header_len))) => {
let size = header.size();
if size % 2 != 0 {
self.padding = true;
}
if self.next_entry_index == self.entry_headers.len() {
self.new_entry_start += header_len + size + (size % 2);
}
if self.is_name_table_id(header.identifier()) {
continue;
}
if self.is_symbol_lookup_table_id(header.identifier()) {
self.symbol_table_header = Some(HeaderAndLocation {
header: header,
header_start: header_start,
data_start: header_start + header_len,
});
continue;
}
if self.next_entry_index == self.entry_headers.len() {
self.entry_headers.push(HeaderAndLocation {
header: header,
header_start: header_start,
data_start: header_start + header_len,
});
}
let header = &self.entry_headers[self.next_entry_index]
.header;
self.next_entry_index += 1;
return Some(Ok(Entry {
header: header,
reader: self.reader.by_ref(),
length: size,
position: 0,
}));
}
Ok(None) => {
self.scanned = true;
return None;
}
Err(error) => {
self.error = true;
return Some(Err(error));
}
}
}
}
}
impl<R: Read + Seek> Archive<R> {
fn scan_if_necessary(&mut self) -> io::Result<()> {
if self.scanned {
return Ok(());
}
self.read_global_header_if_necessary()?;
loop {
let header_start = self.new_entry_start;
self.reader.seek(SeekFrom::Start(header_start))?;
if let Some((header, header_len)) =
Header::read(
&mut self.reader,
&mut self.variant,
&mut self.name_table,
)?
{
let size = header.size();
self.new_entry_start += header_len + size + (size % 2);
if self.is_name_table_id(header.identifier()) {
continue;
}
if self.is_symbol_lookup_table_id(header.identifier()) {
self.symbol_table_header = Some(HeaderAndLocation {
header: header,
header_start: header_start,
data_start: header_start + header_len,
});
continue;
}
self.entry_headers.push(HeaderAndLocation {
header: header,
header_start: header_start,
data_start: header_start + header_len,
});
} else {
break;
}
}
// Resume our previous position in the file.
if self.next_entry_index < self.entry_headers.len() {
let offset = self.entry_headers[self.next_entry_index]
.header_start;
self.reader.seek(SeekFrom::Start(offset))?;
}
self.scanned = true;
Ok(())
}
/// Scans the archive and returns the total number of entries in the
/// archive (not counting special entries, such as the GNU archive name
/// table or symbol table, that are not returned by `next_entry()`).
pub fn count_entries(&mut self) -> io::Result<usize> {
self.scan_if_necessary()?;
Ok(self.entry_headers.len())
}
/// Scans the archive and jumps to the entry at the given index. Returns
/// an error if the index is not less than the result of `count_entries()`.
pub fn jump_to_entry(&mut self, index: usize) -> io::Result<Entry<R>> {
self.scan_if_necessary()?;
if index >= self.entry_headers.len() {
let msg = "Entry index out of bounds";
return Err(Error::new(ErrorKind::InvalidInput, msg));
}
let offset = self.entry_headers[index].data_start;
self.reader.seek(SeekFrom::Start(offset))?;
let header = &self.entry_headers[index].header;
let size = header.size();
if size % 2 != 0 {
self.padding = true;
} else {
self.padding = false;
}
self.next_entry_index = index + 1;
Ok(Entry {
header,
reader: self.reader.by_ref(),
length: size,
position: 0,
})
}
fn parse_symbol_table_if_necessary(&mut self) -> io::Result<()> {
self.scan_if_necessary()?;
if self.symbol_table.is_some() {
return Ok(());
}
if let Some(ref header_and_loc) = self.symbol_table_header {
let offset = header_and_loc.data_start;
self.reader.seek(SeekFrom::Start(offset))?;
let mut reader = BufReader::new(self.reader.by_ref().take(
header_and_loc.header.size(),
));
if self.variant == Variant::GNU {
let num_symbols = read_be_u32(&mut reader)? as usize;
let mut symbol_offsets =
Vec::<u32>::with_capacity(num_symbols);
for _ in 0..num_symbols {
let offset = read_be_u32(&mut reader)?;
symbol_offsets.push(offset);
}
let mut symbol_table = Vec::with_capacity(num_symbols);
for offset in symbol_offsets.into_iter() {
let mut buffer = Vec::<u8>::new();
reader.read_until(0, &mut buffer)?;
if buffer.last() == Some(&0) {
buffer.pop();
}
buffer.shrink_to_fit();
symbol_table.push((buffer, offset as u64));
}
self.symbol_table = Some(symbol_table);
} else {
let num_symbols = (read_le_u32(&mut reader)? / 8) as
usize;
let mut symbol_offsets =
Vec::<(u32, u32)>::with_capacity(num_symbols);
for _ in 0..num_symbols {
let str_offset = read_le_u32(&mut reader)?;
let file_offset = read_le_u32(&mut reader)?;
symbol_offsets.push((str_offset, file_offset));
}
let str_table_len = read_le_u32(&mut reader)?;
let mut str_table_data = vec![0u8; str_table_len as usize];
reader.read_exact(&mut str_table_data).map_err(|err| {
annotate(err, "failed to read string table")
})?;
let mut symbol_table = Vec::with_capacity(num_symbols);
for (str_start, file_offset) in symbol_offsets.into_iter() {
let str_start = str_start as usize;
let mut str_end = str_start;
while str_end < str_table_data.len() &&
str_table_data[str_end] != 0u8
{
str_end += 1;
}
let string = &str_table_data[str_start..str_end];
symbol_table.push((string.to_vec(), file_offset as u64));
}
self.symbol_table = Some(symbol_table);
}
}
// Resume our previous position in the file.
if self.entry_headers.len() > 0 {
let offset = self.entry_headers[self.next_entry_index]
.header_start;
self.reader.seek(SeekFrom::Start(offset))?;
}
Ok(())
}
/// Scans the archive and returns an iterator over the symbols in the
/// archive's symbol table. If the archive doesn't have a symbol table,
/// this method will still succeed, but the iterator won't produce any
/// values.
pub fn symbols(&mut self) -> io::Result<Symbols<R>> {
self.parse_symbol_table_if_necessary()?;
Ok(Symbols {
archive: self,
index: 0,
})
}
}
// ========================================================================= //
/// Representation of an archive entry.
///
/// `Entry` objects implement the `Read` trait, and can be used to extract the
/// data from this archive entry. If the underlying reader supports the `Seek`
/// trait, then the `Entry` object supports `Seek` as well.
pub struct Entry<'a, R: 'a + Read> {
header: &'a Header,
reader: &'a mut R,
length: u64,
position: u64,
}
impl<'a, R: 'a + Read> Entry<'a, R> {
/// Returns the header for this archive entry.
pub fn header(&self) -> &Header { self.header }
}
impl<'a, R: 'a + Read> Read for Entry<'a, R> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
debug_assert!(self.position <= self.length);
if self.position == self.length {
return Ok(0);
}
let max_len =
cmp::min(self.length - self.position, buf.len() as u64) as usize;
let bytes_read = self.reader.read(&mut buf[0..max_len])?;
self.position += bytes_read as u64;
debug_assert!(self.position <= self.length);
Ok(bytes_read)
}
}
impl<'a, R: 'a + Read + Seek> Seek for Entry<'a, R> {
fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
let delta = match pos {
SeekFrom::Start(offset) => offset as i64 - self.position as i64,
SeekFrom::End(offset) => {
self.length as i64 + offset - self.position as i64
}
SeekFrom::Current(delta) => delta,
};
let new_position = self.position as i64 + delta;
if new_position < 0 {
let msg = format!(
"Invalid seek to negative position ({})",
new_position
);
return Err(Error::new(ErrorKind::InvalidInput, msg));
}
let new_position = new_position as u64;
if new_position > self.length {
let msg = format!(
"Invalid seek to position past end of entry ({} vs. {})",
new_position,
self.length
);
return Err(Error::new(ErrorKind::InvalidInput, msg));
}
self.reader.seek(SeekFrom::Current(delta))?;
self.position = new_position;
Ok(self.position)
}
}
impl<'a, R: 'a + Read> Drop for Entry<'a, R> {
fn drop(&mut self) {
if self.position < self.length {
// Consume the rest of the data in this entry.
let mut remaining = self.reader.take(self.length - self.position);
let _ = io::copy(&mut remaining, &mut io::sink());
}
}
}
// ========================================================================= //
/// An iterator over the symbols in the symbol table of an archive.
pub struct Symbols<'a, R: 'a + Read> {
archive: &'a Archive<R>,
index: usize,
}
impl<'a, R: Read> Iterator for Symbols<'a, R> {
type Item = &'a [u8];
fn next(&mut self) -> Option<&'a [u8]> {
if let Some(ref table) = self.archive.symbol_table {
if self.index < table.len() {
let next = table[self.index].0.as_slice();
self.index += 1;
return Some(next);
}
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = if let Some(ref table) = self.archive.symbol_table {
table.len() - self.index
} else {
0
};
(remaining, Some(remaining))
}
}
impl<'a, R: Read> ExactSizeIterator for Symbols<'a, R> {}
// ========================================================================= //
/// A structure for building Common or BSD-variant archives (the archive format
/// typically used on e.g. BSD and Mac OS X systems).
///
/// This structure has methods for building up an archive from scratch into any
/// arbitrary writer.
pub struct Builder<W: Write> {
writer: W,
started: bool,
}
impl<W: Write> Builder<W> {
/// Create a new archive builder with the underlying writer object as the
/// destination of all data written.
pub fn new(writer: W) -> Builder<W> {
Builder {
writer,
started: false,
}
}
/// Unwrap this archive builder, returning the underlying writer object.
pub fn into_inner(self) -> Result<W> { Ok(self.writer) }
/// Adds a new entry to this archive.
pub fn append<R: Read>(&mut self, header: &Header, mut data: R)
-> Result<()> {
if !self.started {
self.writer.write_all(GLOBAL_HEADER)?;
self.started = true;
}
header.write(&mut self.writer)?;
let actual_size = io::copy(&mut data, &mut self.writer)?;
if actual_size != header.size() {
let msg = format!(
"Wrong file size (header.size() = {}, actual \
size was {})",
header.size(),
actual_size
);
return Err(Error::new(ErrorKind::InvalidData, msg));
}
if actual_size % 2 != 0 {
self.writer.write_all(&['\n' as u8])?;
}
Ok(())
}
/// Adds a file on the local filesystem to this archive, using the file
/// name as its identifier.
pub fn append_path<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
let name: &OsStr = path.as_ref().file_name().ok_or_else(|| {
let msg = "Given path doesn't have a file name";
Error::new(ErrorKind::InvalidInput, msg)
})?;
let identifier = osstr_to_bytes(name)?;
let mut file = File::open(&path)?;
self.append_file_id(identifier, &mut file)
}
/// Adds a file to this archive, with the given name as its identifier.
pub fn append_file(&mut self, name: &[u8], file: &mut File) -> Result<()> {
self.append_file_id(name.to_vec(), file)
}
fn append_file_id(&mut self, id: Vec<u8>, file: &mut File) -> Result<()> {
let metadata = file.metadata()?;
let header = Header::from_metadata(id, &metadata);
self.append(&header, file)
}
}
// ========================================================================= //
/// A structure for building GNU-variant archives (the archive format typically
/// used on e.g. GNU/Linux and Windows systems).
///
/// This structure has methods for building up an archive from scratch into any
/// arbitrary writer.
pub struct GnuBuilder<W: Write> {
writer: W,
short_names: HashSet<Vec<u8>>,
long_names: HashMap<Vec<u8>, usize>,
name_table_size: usize,
name_table_needs_padding: bool,
started: bool,
}
impl<W: Write> GnuBuilder<W> {
/// Create a new archive builder with the underlying writer object as the
/// destination of all data written. The `identifiers` parameter must give
/// the complete list of entry identifiers that will be included in this
/// archive.
pub fn new(writer: W, identifiers: Vec<Vec<u8>>) -> GnuBuilder<W> {
let mut short_names = HashSet::<Vec<u8>>::new();
let mut long_names = HashMap::<Vec<u8>, usize>::new();
let mut name_table_size: usize = 0;
for identifier in identifiers.into_iter() {
let length = identifier.len();
if length > 15 {
long_names.insert(identifier, name_table_size);
name_table_size += length + 2;
} else {
short_names.insert(identifier);
}
}
let name_table_needs_padding = name_table_size % 2 != 0;
if name_table_needs_padding {
name_table_size += 3; // ` /\n`
}
GnuBuilder {
writer,
short_names,
long_names,
name_table_size,
name_table_needs_padding,
started: false,
}
}
/// Unwrap this archive builder, returning the underlying writer object.
pub fn into_inner(self) -> Result<W> { Ok(self.writer) }
/// Adds a new entry to this archive.
pub fn append<R: Read>(&mut self, header: &Header, mut data: R)
-> Result<()> {
let is_long_name = header.identifier().len() > 15;
let has_name = if is_long_name {
self.long_names.contains_key(header.identifier())
} else {
self.short_names.contains(header.identifier())
};
if !has_name {
let msg = format!(
"Identifier {:?} was not in the list of \
identifiers passed to GnuBuilder::new()",
String::from_utf8_lossy(header.identifier())
);
return Err(Error::new(ErrorKind::InvalidInput, msg));
}
if !self.started {
self.writer.write_all(GLOBAL_HEADER)?;
if !self.long_names.is_empty() {
write!(
self.writer,
"{:<48}{:<10}`\n",
GNU_NAME_TABLE_ID,
self.name_table_size
)?;
let mut entries: Vec<(usize, &[u8])> = self.long_names
.iter()
.map(|(id, &start)| (start, id.as_slice()))
.collect();
entries.sort();
for (_, id) in entries {
self.writer.write_all(id)?;
self.writer.write_all(b"/\n")?;
}
if self.name_table_needs_padding {
self.writer.write_all(b" /\n")?;
}
}
self.started = true;
}
header.write_gnu(&mut self.writer, &self.long_names)?;
let actual_size = io::copy(&mut data, &mut self.writer)?;
if actual_size != header.size() {
let msg = format!(
"Wrong file size (header.size() = {}, actual \
size was {})",
header.size(),
actual_size
);
return Err(Error::new(ErrorKind::InvalidData, msg));
}
if actual_size % 2 != 0 {
self.writer.write_all(&['\n' as u8])?;
}
Ok(())
}
/// Adds a file on the local filesystem to this archive, using the file
/// name as its identifier.
pub fn append_path<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
let name: &OsStr = path.as_ref().file_name().ok_or_else(|| {
let msg = "Given path doesn't have a file name";
Error::new(ErrorKind::InvalidInput, msg)
})?;
let identifier = osstr_to_bytes(name)?;
let mut file = File::open(&path)?;
self.append_file_id(identifier, &mut file)
}
/// Adds a file to this archive, with the given name as its identifier.
pub fn append_file(&mut self, name: &[u8], file: &mut File) -> Result<()> {
self.append_file_id(name.to_vec(), file)
}
fn append_file_id(&mut self, id: Vec<u8>, file: &mut File) -> Result<()> {
let metadata = file.metadata()?;
let header = Header::from_metadata(id, &metadata);
self.append(&header, file)
}
}
// ========================================================================= //
#[cfg(unix)]
fn osstr_to_bytes(string: &OsStr) -> Result<Vec<u8>> {
Ok(string.as_bytes().to_vec())
}
#[cfg(windows)]
fn osstr_to_bytes(string: &OsStr) -> Result<Vec<u8>> {
let mut bytes = Vec::<u8>::new();
for wide in string.encode_wide() {
// Little-endian:
bytes.push((wide & 0xff) as u8);
bytes.push((wide >> 8) as u8);
}
Ok(bytes)
}
#[cfg(not(any(unix, windows)))]
fn osstr_to_bytes(string: &OsStr) -> Result<Vec<u8>> {
let utf8: &str = string.to_str().ok_or_else(|| {
Error::new(ErrorKind::InvalidData, "Non-UTF8 file name")
})?;
Ok(utf8.as_bytes().to_vec())
}
// ========================================================================= //
fn annotate(error: io::Error, msg: &str) -> io::Error {
let kind = error.kind();
if let Some(inner) = error.into_inner() {
io::Error::new(kind, format!("{}: {}", msg, inner))
} else {
io::Error::new(kind, msg)
}
}
// ========================================================================= //
#[cfg(test)]
mod tests {
use super::{Archive, Builder, GnuBuilder, Header, Variant};
use std::io::{Cursor, Read, Result, Seek, SeekFrom};
use std::str;
struct SlowReader<'a> {
current_position: usize,
buffer: &'a [u8],
}
impl<'a> Read for SlowReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
if self.current_position >= self.buffer.len() {
return Ok(0);
}
buf[0] = self.buffer[self.current_position];
self.current_position += 1;
return Ok(1);
}
}
#[test]
fn build_common_archive() {
let mut builder = Builder::new(Vec::new());
let mut header1 = Header::new(b"foo.txt".to_vec(), 7);
header1.set_mtime(1487552916);
header1.set_uid(501);
header1.set_gid(20);
header1.set_mode(0o100644);
builder.append(&header1, "foobar\n".as_bytes()).unwrap();
let header2 = Header::new(b"baz.txt".to_vec(), 4);
builder.append(&header2, "baz\n".as_bytes()).unwrap();
let actual = builder.into_inner().unwrap();
let expected = "\
!<arch>\n\
foo.txt 1487552916 501 20 100644 7 `\n\
foobar\n\n\
baz.txt 0 0 0 0 4 `\n\
baz\n";
assert_eq!(str::from_utf8(&actual).unwrap(), expected);
}
#[test]
fn build_bsd_archive_with_long_filenames() {
let mut builder = Builder::new(Vec::new());
let mut header1 = Header::new(b"short".to_vec(), 1);
header1.set_identifier(b"this_is_a_very_long_filename.txt".to_vec());
header1.set_mtime(1487552916);
header1.set_uid(501);
header1.set_gid(20);
header1.set_mode(0o100644);
header1.set_size(7);
builder.append(&header1, "foobar\n".as_bytes()).unwrap();
let header2 = Header::new(
b"and_this_is_another_very_long_filename.txt".to_vec(),
4,
);
builder.append(&header2, "baz\n".as_bytes()).unwrap();
let actual = builder.into_inner().unwrap();
let expected = "\
!<arch>\n\
#1/32 1487552916 501 20 100644 39 `\n\
this_is_a_very_long_filename.txtfoobar\n\n\
#1/44 0 0 0 0 48 `\n\
and_this_is_another_very_long_filename.txt\x00\x00baz\n";
assert_eq!(str::from_utf8(&actual).unwrap(), expected);
}
#[test]
fn build_bsd_archive_with_space_in_filename() {
let mut builder = Builder::new(Vec::new());
let header = Header::new(b"foo bar".to_vec(), 4);
builder.append(&header, "baz\n".as_bytes()).unwrap();
let actual = builder.into_inner().unwrap();
let expected = "\
!<arch>\n\
#1/8 0 0 0 0 12 `\n\
foo bar\x00baz\n";
assert_eq!(str::from_utf8(&actual).unwrap(), expected);
}
#[test]
fn build_gnu_archive() {
let names = vec![b"baz.txt".to_vec(), b"foo.txt".to_vec()];
let mut builder = GnuBuilder::new(Vec::new(), names);
let mut header1 = Header::new(b"foo.txt".to_vec(), 7);
header1.set_mtime(1487552916);
header1.set_uid(501);
header1.set_gid(20);
header1.set_mode(0o100644);
builder.append(&header1, "foobar\n".as_bytes()).unwrap();
let header2 = Header::new(b"baz.txt".to_vec(), 4);
builder.append(&header2, "baz\n".as_bytes()).unwrap();
let actual = builder.into_inner().unwrap();
let expected = "\
!<arch>\n\
foo.txt/ 1487552916 501 20 100644 7 `\n\
foobar\n\n\
baz.txt/ 0 0 0 0 4 `\n\
baz\n";
assert_eq!(str::from_utf8(&actual).unwrap(), expected);
}
#[test]
fn build_gnu_archive_with_long_filenames() {
let names = vec![
b"this_is_a_very_long_filename.txt".to_vec(),
b"and_this_is_another_very_long_filename.txt".to_vec(),
];
let mut builder = GnuBuilder::new(Vec::new(), names);
let mut header1 = Header::new(b"short".to_vec(), 1);
header1.set_identifier(b"this_is_a_very_long_filename.txt".to_vec());
header1.set_mtime(1487552916);
header1.set_uid(501);
header1.set_gid(20);
header1.set_mode(0o100644);
header1.set_size(7);
builder.append(&header1, "foobar\n".as_bytes()).unwrap();
let header2 = Header::new(
b"and_this_is_another_very_long_filename.txt".to_vec(),
4,
);
builder.append(&header2, "baz\n".as_bytes()).unwrap();
let actual = builder.into_inner().unwrap();
let expected = "\
!<arch>\n\
// 78 `\n\
this_is_a_very_long_filename.txt/\n\
and_this_is_another_very_long_filename.txt/\n\
/0 1487552916 501 20 100644 7 `\n\
foobar\n\n\
/34 0 0 0 0 4 `\n\
baz\n";
assert_eq!(str::from_utf8(&actual).unwrap(), expected);
}
#[test]
fn build_gnu_archive_with_space_in_filename() {
let names = vec![b"foo bar".to_vec()];
let mut builder = GnuBuilder::new(Vec::new(), names);
let header = Header::new(b"foo bar".to_vec(), 4);
builder.append(&header, "baz\n".as_bytes()).unwrap();
let actual = builder.into_inner().unwrap();
let expected = "\
!<arch>\n\
foo bar/ 0 0 0 0 4 `\n\
baz\n";
assert_eq!(str::from_utf8(&actual).unwrap(), expected);
}
#[test]
#[should_panic(expected = "Identifier \\\"bar\\\" was not in the list of \
identifiers passed to GnuBuilder::new()")]
fn build_gnu_archive_with_unexpected_identifier() {
let names = vec![b"foo".to_vec()];
let mut builder = GnuBuilder::new(Vec::new(), names);
let header = Header::new(b"bar".to_vec(), 4);
builder.append(&header, "baz\n".as_bytes()).unwrap();
}
#[test]
fn read_common_archive() {
let input = "\
!<arch>\n\
foo.txt 1487552916 501 20 100644 7 `\n\
foobar\n\n\
bar.awesome.txt 1487552919 501 20 100644 22 `\n\
This file is awesome!\n\
baz.txt 1487552349 42 12345 100664 4 `\n\
baz\n";
let reader = SlowReader {
current_position: 0,
buffer: input.as_bytes(),
};
let mut archive = Archive::new(reader);
{
// Parse the first entry and check the header values.
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), b"foo.txt");
assert_eq!(entry.header().mtime(), 1487552916);
assert_eq!(entry.header().uid(), 501);
assert_eq!(entry.header().gid(), 20);
assert_eq!(entry.header().mode(), 0o100644);
assert_eq!(entry.header().size(), 7);
// Read the first few bytes of the entry data and make sure they're
// correct.
let mut buffer = [0; 4];
entry.read_exact(&mut buffer).unwrap();
assert_eq!(&buffer, "foob".as_bytes());
// Dropping the Entry object should automatically consume the rest
// of the entry data so that the archive reader is ready to parse
// the next entry.
}
{
// Parse the second entry and check a couple header values.
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), b"bar.awesome.txt");
assert_eq!(entry.header().size(), 22);
// Read in all the entry data.
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "This file is awesome!\n".as_bytes());
}
{
// Parse the third entry and check a couple header values.
let entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), b"baz.txt");
assert_eq!(entry.header().size(), 4);
}
assert!(archive.next_entry().is_none());
assert_eq!(archive.variant(), Variant::Common);
}
#[test]
fn read_bsd_archive_with_long_filenames() {
let input = "\
!<arch>\n\
#1/32 1487552916 501 20 100644 39 `\n\
this_is_a_very_long_filename.txtfoobar\n\n\
#1/44 0 0 0 0 48 `\n\
and_this_is_another_very_long_filename.txt\x00\x00baz\n";
let mut archive = Archive::new(input.as_bytes());
{
// Parse the first entry and check the header values.
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
assert_eq!(entry.header().mtime(), 1487552916);
assert_eq!(entry.header().uid(), 501);
assert_eq!(entry.header().gid(), 20);
assert_eq!(entry.header().mode(), 0o100644);
// We should get the size of the actual file, not including the
// filename, even though this is not the value that's in the size
// field in the input.
assert_eq!(entry.header().size(), 7);
// Read in the entry data; we should get only the payload and not
// the filename.
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
{
// Parse the second entry and check a couple header values.
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"and_this_is_another_very_long_filename.txt".as_bytes()
);
assert_eq!(entry.header().size(), 4);
// Read in the entry data; we should get only the payload and not
// the filename or the padding bytes.
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
assert!(archive.next_entry().is_none());
assert_eq!(archive.variant(), Variant::BSD);
}
#[test]
fn read_bsd_archive_with_space_in_filename() {
let input = "\
!<arch>\n\
#1/8 0 0 0 0 12 `\n\
foo bar\x00baz\n";
let mut archive = Archive::new(input.as_bytes());
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "foo bar".as_bytes());
assert_eq!(entry.header().size(), 4);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
assert!(archive.next_entry().is_none());
assert_eq!(archive.variant(), Variant::BSD);
}
#[test]
fn read_gnu_archive() {
let input = "\
!<arch>\n\
foo.txt/ 1487552916 501 20 100644 7 `\n\
foobar\n\n\
bar.awesome.txt/1487552919 501 20 100644 22 `\n\
This file is awesome!\n\
baz.txt/ 1487552349 42 12345 100664 4 `\n\
baz\n";
let mut archive = Archive::new(input.as_bytes());
{
let entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "foo.txt".as_bytes());
assert_eq!(entry.header().size(), 7);
}
{
let entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"bar.awesome.txt".as_bytes()
);
assert_eq!(entry.header().size(), 22);
}
{
let entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "baz.txt".as_bytes());
assert_eq!(entry.header().size(), 4);
}
assert!(archive.next_entry().is_none());
assert_eq!(archive.variant(), Variant::GNU);
}
#[test]
fn read_gnu_archive_with_long_filenames() {
let input = "\
!<arch>\n\
// 78 `\n\
this_is_a_very_long_filename.txt/\n\
and_this_is_another_very_long_filename.txt/\n\
/0 1487552916 501 20 100644 7 `\n\
foobar\n\n\
/34 0 0 0 0 4 `\n\
baz\n";
let mut archive = Archive::new(input.as_bytes());
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
assert_eq!(entry.header().mtime(), 1487552916);
assert_eq!(entry.header().uid(), 501);
assert_eq!(entry.header().gid(), 20);
assert_eq!(entry.header().mode(), 0o100644);
assert_eq!(entry.header().size(), 7);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"and_this_is_another_very_long_filename.txt".as_bytes()
);
assert_eq!(entry.header().size(), 4);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
assert!(archive.next_entry().is_none());
assert_eq!(archive.variant(), Variant::GNU);
}
// MS `.lib` files are very similar to GNU `ar` archives, but with a few
// tweaks:
// * File names in the name table are terminated by null, rather than /\n
// * Numeric entries may be all empty string, interpreted as 0, possibly?
#[test]
fn read_ms_archive_with_long_filenames() {
let input = "\
!<arch>\n\
// 76 `\n\
this_is_a_very_long_filename.txt\x00\
and_this_is_another_very_long_filename.txt\x00\
/0 1487552916 100644 7 `\n\
foobar\n\n\
/33 1446790218 100666 4 `\n\
baz\n";
let mut archive = Archive::new(input.as_bytes());
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
assert_eq!(entry.header().mtime(), 1487552916);
assert_eq!(entry.header().uid(), 0);
assert_eq!(entry.header().gid(), 0);
assert_eq!(entry.header().mode(), 0o100644);
assert_eq!(entry.header().size(), 7);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"and_this_is_another_very_long_filename.txt".as_bytes()
);
assert_eq!(entry.header().size(), 4);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
assert!(archive.next_entry().is_none());
assert_eq!(archive.variant(), Variant::GNU);
}
#[test]
fn read_gnu_archive_with_space_in_filename() {
let input = "\
!<arch>\n\
foo bar/ 0 0 0 0 4 `\n\
baz\n";
let mut archive = Archive::new(input.as_bytes());
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "foo bar".as_bytes());
assert_eq!(entry.header().size(), 4);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
assert!(archive.next_entry().is_none());
assert_eq!(archive.variant(), Variant::GNU);
}
#[test]
fn read_gnu_archive_with_symbol_lookup_table() {
let input = b"\
!<arch>\n\
/ 0 0 0 0 15 `\n\
\x00\x00\x00\x01\x00\x00\x00\xb2foobar\x00\n\
// 34 `\n\
this_is_a_very_long_filename.txt/\n\
/0 1487552916 501 20 100644 7 `\n\
foobar\n";
let mut archive = Archive::new(input as &[u8]);
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
assert!(archive.next_entry().is_none());
}
#[test]
fn read_archive_with_no_padding_byte_in_final_entry() {
let input = "\
!<arch>\n\
foo.txt 1487552916 501 20 100644 7 `\n\
foobar\n\n\
bar.txt 1487552919 501 20 100644 3 `\n\
foo";
let mut archive = Archive::new(input.as_bytes());
{
let entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "foo.txt".as_bytes());
assert_eq!(entry.header().size(), 7);
}
{
let entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "bar.txt".as_bytes());
assert_eq!(entry.header().size(), 3);
}
assert!(archive.next_entry().is_none());
}
#[test]
#[should_panic(expected = "Invalid timestamp field in entry header \
(\\\"helloworld \\\")")]
fn read_archive_with_invalid_mtime() {
let input = "\
!<arch>\n\
foo.txt helloworld 501 20 100644 7 `\n\
foobar\n\n";
let mut archive = Archive::new(input.as_bytes());
archive.next_entry().unwrap().unwrap();
}
#[test]
#[should_panic(expected = "Invalid owner ID field in entry header \
(\\\"foo \\\")")]
fn read_archive_with_invalid_uid() {
let input = "\
!<arch>\n\
foo.txt 1487552916 foo 20 100644 7 `\n\
foobar\n\n";
let mut archive = Archive::new(input.as_bytes());
archive.next_entry().unwrap().unwrap();
}
#[test]
#[should_panic(expected = "Invalid group ID field in entry header \
(\\\"bar \\\")")]
fn read_archive_with_invalid_gid() {
let input = "\
!<arch>\n\
foo.txt 1487552916 501 bar 100644 7 `\n\
foobar\n\n";
let mut archive = Archive::new(input.as_bytes());
archive.next_entry().unwrap().unwrap();
}
#[test]
#[should_panic(expected = "Invalid file mode field in entry header \
(\\\"foobar \\\")")]
fn read_archive_with_invalid_mode() {
let input = "\
!<arch>\n\
foo.txt 1487552916 501 20 foobar 7 `\n\
foobar\n\n";
let mut archive = Archive::new(input.as_bytes());
archive.next_entry().unwrap().unwrap();
}
#[test]
#[should_panic(expected = "Invalid file size field in entry header \
(\\\"whatever \\\")")]
fn read_archive_with_invalid_size() {
let input = "\
!<arch>\n\
foo.txt 1487552916 501 20 100644 whatever `\n\
foobar\n\n";
let mut archive = Archive::new(input.as_bytes());
archive.next_entry().unwrap().unwrap();
}
#[test]
#[should_panic(expected = "Invalid BSD filename length field in entry \
header (\\\"foobar \\\")")]
fn read_bsd_archive_with_invalid_filename_length() {
let input = "\
!<arch>\n\
#1/foobar 1487552916 501 20 100644 39 `\n\
this_is_a_very_long_filename.txtfoobar\n\n";
let mut archive = Archive::new(input.as_bytes());
archive.next_entry().unwrap().unwrap();
}
#[test]
#[should_panic(expected = "Invalid GNU filename index field in entry \
header (\\\"foobar \\\")")]
fn read_gnu_archive_with_invalid_filename_index() {
let input = "\
!<arch>\n\
// 34 `\n\
this_is_a_very_long_filename.txt/\n\
/foobar 1487552916 501 20 100644 7 `\n\
foobar\n\n";
let mut archive = Archive::new(input.as_bytes());
archive.next_entry().unwrap().unwrap();
}
#[test]
fn seek_within_entry() {
let input = "\
!<arch>\n\
foo.txt 1487552916 501 20 100644 31 `\n\
abcdefghij0123456789ABCDEFGHIJ\n\n\
bar.awesome.txt 1487552919 501 20 100644 22 `\n\
This file is awesome!\n";
let mut archive = Archive::new(Cursor::new(input.as_bytes()));
{
// Parse the first entry, then seek around the entry, performing
// different reads.
let mut entry = archive.next_entry().unwrap().unwrap();
let mut buffer = [0; 5];
entry.seek(SeekFrom::Start(10)).unwrap();
entry.read_exact(&mut buffer).unwrap();
assert_eq!(&buffer, "01234".as_bytes());
entry.seek(SeekFrom::Start(5)).unwrap();
entry.read_exact(&mut buffer).unwrap();
assert_eq!(&buffer, "fghij".as_bytes());
entry.seek(SeekFrom::End(-10)).unwrap();
entry.read_exact(&mut buffer).unwrap();
assert_eq!(&buffer, "BCDEF".as_bytes());
entry.seek(SeekFrom::End(-30)).unwrap();
entry.read_exact(&mut buffer).unwrap();
assert_eq!(&buffer, "bcdef".as_bytes());
entry.seek(SeekFrom::Current(10)).unwrap();
entry.read_exact(&mut buffer).unwrap();
assert_eq!(&buffer, "6789A".as_bytes());
entry.seek(SeekFrom::Current(-8)).unwrap();
entry.read_exact(&mut buffer).unwrap();
assert_eq!(&buffer, "34567".as_bytes());
// Dropping the Entry object should automatically consume the rest
// of the entry data so that the archive reader is ready to parse
// the next entry.
}
{
// Parse the second entry and read in all the entry data.
let mut entry = archive.next_entry().unwrap().unwrap();
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "This file is awesome!\n".as_bytes());
}
}
#[test]
#[should_panic(expected = "Invalid seek to negative position (-17)")]
fn seek_entry_to_negative_position() {
let input = "\
!<arch>\n\
foo.txt 1487552916 501 20 100644 30 `\n\
abcdefghij0123456789ABCDEFGHIJ";
let mut archive = Archive::new(Cursor::new(input.as_bytes()));
let mut entry = archive.next_entry().unwrap().unwrap();
entry.seek(SeekFrom::End(-47)).unwrap();
}
#[test]
#[should_panic(expected = "Invalid seek to position past end of entry \
(47 vs. 30)")]
fn seek_entry_beyond_end() {
let input = "\
!<arch>\n\
foo.txt 1487552916 501 20 100644 30 `\n\
abcdefghij0123456789ABCDEFGHIJ";
let mut archive = Archive::new(Cursor::new(input.as_bytes()));
let mut entry = archive.next_entry().unwrap().unwrap();
entry.seek(SeekFrom::Start(47)).unwrap();
}
#[test]
fn count_entries_in_bsd_archive() {
let input = b"\
!<arch>\n\
#1/32 1487552916 501 20 100644 39 `\n\
this_is_a_very_long_filename.txtfoobar\n\n\
baz.txt 0 0 0 0 4 `\n\
baz\n";
let mut archive = Archive::new(Cursor::new(input as &[u8]));
assert_eq!(archive.count_entries().unwrap(), 2);
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
assert_eq!(archive.count_entries().unwrap(), 2);
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "baz.txt".as_bytes());
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
assert_eq!(archive.count_entries().unwrap(), 2);
}
#[test]
fn count_entries_in_gnu_archive() {
let input = b"\
!<arch>\n\
/ 0 0 0 0 15 `\n\
\x00\x00\x00\x01\x00\x00\x00\xb2foobar\x00\n\
// 34 `\n\
this_is_a_very_long_filename.txt/\n\
/0 1487552916 501 20 100644 7 `\n\
foobar\n\n\
baz.txt/ 1487552349 42 12345 100664 4 `\n\
baz\n";
let mut archive = Archive::new(Cursor::new(input as &[u8]));
assert_eq!(archive.count_entries().unwrap(), 2);
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
assert_eq!(archive.count_entries().unwrap(), 2);
{
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "baz.txt".as_bytes());
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
assert_eq!(archive.count_entries().unwrap(), 2);
}
#[test]
fn jump_to_entry_in_bsd_archive() {
let input = b"\
!<arch>\n\
hello.txt 1487552316 42 12345 100644 14 `\n\
Hello, world!\n\
#1/32 1487552916 501 20 100644 39 `\n\
this_is_a_very_long_filename.txtfoobar\n\n\
baz.txt 1487552349 42 12345 100664 4 `\n\
baz\n";
let mut archive = Archive::new(Cursor::new(input as &[u8]));
{
// Jump to the second entry and check its contents.
let mut entry = archive.jump_to_entry(1).unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
{
// Read the next entry, which should be the third one now.
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "baz.txt".as_bytes());
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
// We should be at the end of the archive now.
assert!(archive.next_entry().is_none());
{
// Jump back to the first entry and check its contents.
let mut entry = archive.jump_to_entry(0).unwrap();
assert_eq!(entry.header().identifier(), "hello.txt".as_bytes());
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "Hello, world!\n".as_bytes());
}
{
// Read the next entry, which should be the second one again.
let mut entry = archive.jump_to_entry(1).unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
{
// Jump back to the first entry and check its contents.
let mut entry = archive.jump_to_entry(0).unwrap();
assert_eq!(entry.header().identifier(), "hello.txt".as_bytes());
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "Hello, world!\n".as_bytes());
}
{
// Read the next entry, which should be the second one again.
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
}
#[test]
fn jump_to_entry_in_gnu_archive() {
let input = b"\
!<arch>\n\
// 34 `\n\
this_is_a_very_long_filename.txt/\n\
hello.txt/ 1487552316 42 12345 100644 14 `\n\
Hello, world!\n\
/0 1487552916 501 20 100644 7 `\n\
foobar\n\n\
baz.txt/ 1487552349 42 12345 100664 4 `\n\
baz\n";
let mut archive = Archive::new(Cursor::new(input as &[u8]));
{
// Jump to the second entry and check its contents.
let mut entry = archive.jump_to_entry(1).unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
{
// Read the next entry, which should be the third one now.
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(entry.header().identifier(), "baz.txt".as_bytes());
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
}
// We should be at the end of the archive now.
assert!(archive.next_entry().is_none());
{
// Jump back to the first entry and check its contents.
let mut entry = archive.jump_to_entry(0).unwrap();
assert_eq!(entry.header().identifier(), "hello.txt".as_bytes());
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "Hello, world!\n".as_bytes());
}
{
// Read the next entry, which should be the second one again.
let mut entry = archive.next_entry().unwrap().unwrap();
assert_eq!(
entry.header().identifier(),
"this_is_a_very_long_filename.txt".as_bytes()
);
let mut buffer = Vec::new();
entry.read_to_end(&mut buffer).unwrap();
assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
}
}
#[test]
fn list_symbols_in_bsd_archive() {
let input = b"\
!<arch>\n\
#1/12 0 0 0 0 60 `\n\
__.SYMDEF\x00\x00\x00\x18\x00\x00\x00\
\x00\x00\x00\x00\x80\x00\x00\x00\
\x07\x00\x00\x00\x80\x00\x00\x00\
\x0b\x00\x00\x00\x80\x00\x00\x00\
\x10\x00\x00\x00foobar\x00baz\x00quux\x00\
foo.o/ 1487552916 501 20 100644 16 `\n\
foobar,baz,quux\n";
let mut archive = Archive::new(Cursor::new(input as &[u8]));
assert_eq!(archive.symbols().unwrap().len(), 3);
assert_eq!(archive.variant(), Variant::BSD);
let symbols = archive.symbols().unwrap().collect::<Vec<&[u8]>>();
let expected: Vec<&[u8]> = vec![b"foobar", b"baz", b"quux"];
assert_eq!(symbols, expected);
}
#[test]
fn list_sorted_symbols_in_bsd_archive() {
let input = b"\
!<arch>\n\
#1/16 0 0 0 0 64 `\n\
__.SYMDEF SORTED\x18\x00\x00\x00\
\x00\x00\x00\x00\x80\x00\x00\x00\
\x04\x00\x00\x00\x80\x00\x00\x00\
\x0b\x00\x00\x00\x80\x00\x00\x00\
\x10\x00\x00\x00baz\x00foobar\x00quux\x00\
foo.o/ 1487552916 501 20 100644 16 `\n\
foobar,baz,quux\n";
let mut archive = Archive::new(Cursor::new(input as &[u8]));
assert_eq!(archive.symbols().unwrap().len(), 3);
assert_eq!(archive.variant(), Variant::BSD);
let symbols = archive.symbols().unwrap().collect::<Vec<&[u8]>>();
let expected: Vec<&[u8]> = vec![b"baz", b"foobar", b"quux"];
assert_eq!(symbols, expected);
}
#[test]
fn list_symbols_in_gnu_archive() {
let input = b"\
!<arch>\n\
/ 0 0 0 0 32 `\n\
\x00\x00\x00\x03\x00\x00\x00\x5c\x00\x00\x00\x5c\x00\x00\x00\x5c\
foobar\x00baz\x00quux\x00\
foo.o/ 1487552916 501 20 100644 16 `\n\
foobar,baz,quux\n";
let mut archive = Archive::new(Cursor::new(input as &[u8]));
assert_eq!(archive.symbols().unwrap().len(), 3);
assert_eq!(archive.variant(), Variant::GNU);
let symbols = archive.symbols().unwrap().collect::<Vec<&[u8]>>();
let expected: Vec<&[u8]> = vec![b"foobar", b"baz", b"quux"];
assert_eq!(symbols, expected);
}
#[test]
fn non_multiple_of_two_long_ident_in_gnu_archive() {
let mut buffer = std::io::Cursor::new(Vec::new());
{
let filenames = vec![b"rust.metadata.bin".to_vec(), b"compiler_builtins-78891cf83a7d3547.dummy_name.rcgu.o".to_vec()];
let mut builder = GnuBuilder::new(&mut buffer, filenames.clone());
for filename in filenames {
builder.append(&Header::new(filename, 1), &mut (&[b'?'] as &[u8])).expect("add file");
}
}
buffer.set_position(0);
let mut archive = Archive::new(buffer);
while let Some(entry) = archive.next_entry() {
entry.unwrap();
}
}
}
// ========================================================================= //
| true |
fdda4a41bcc21919e95472dc2882f381b1aeaf36
|
Rust
|
Lireer/ricochet-robot-solver
|
/ricochet_solver/src/lib.rs
|
UTF-8
| 1,783 | 3.265625 | 3 |
[] |
no_license
|
mod a_star;
mod breadth_first;
mod iterative_deepening;
mod mcts;
pub mod util;
use getset::Getters;
use ricochet_board::{Direction, Robot, RobotPositions, Round};
pub use a_star::AStar;
pub use breadth_first::BreadthFirst;
pub use iterative_deepening::IdaStar;
pub use mcts::Mcts;
pub trait Solver {
/// Find a solution to get from the `start_positions` to a target.
fn solve(&mut self, round: &Round, start_positions: RobotPositions) -> Path;
}
/// A path from a starting position to another position.
///
/// Contains the starting positions of the robots, their final positions and a path from the former
/// to the latter. The path consists of tuples of a robot and the direction it moved in.
#[derive(Debug, Clone, PartialEq, Eq, Getters)]
#[getset(get = "pub")]
pub struct Path {
start_pos: RobotPositions,
end_pos: RobotPositions,
movements: Vec<(Robot, Direction)>,
}
impl Path {
/// Creates a new path containing the starting and final positions of the robots and a path
/// to reach the target.
pub fn new(
start_pos: RobotPositions,
end_pos: RobotPositions,
movements: Vec<(Robot, Direction)>,
) -> Self {
debug_assert!(!movements.is_empty() || start_pos == end_pos);
Self {
start_pos,
end_pos,
movements,
}
}
/// Creates a new path which ends on the starting position.
pub fn new_start_on_target(start_pos: RobotPositions) -> Self {
Self::new(start_pos.clone(), start_pos, Vec::new())
}
/// Returns the number of moves in the path.
pub fn len(&self) -> usize {
self.movements.len()
}
/// Checks if the path has a length of 0.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
| true |
8f8c5eab907432bec70eff0b4779fcbfe08575ff
|
Rust
|
patallen/BitRomney
|
/src/gameboy/operations.rs
|
UTF-8
| 89,499 | 2.984375 | 3 |
[] |
no_license
|
#![allow(unused_variables)]
#![allow(non_snake_case)]
use gameboy::cpu::Cpu;
use gameboy::mmu::Mmu;
use gameboy::registers::FlagRegister;
use bitty::BitFlags;
pub struct Operation {
pub dis: &'static str,
pub func: Box<Fn(&mut Cpu, &mut Mmu)>,
pub cycles: u8,
pub mode: ValueMode,
}
impl Operation {
pub fn new(
func: fn(&mut Cpu, &mut Mmu),
cycles: u8,
dis: &'static str,
mode: ValueMode,
) -> Operation {
Operation {
func: Box::new(func),
cycles: cycles,
dis: dis,
mode: mode,
}
}
pub fn disassemble(&self, cpu: &Cpu, mmu: &Mmu) -> String {
let val = match self.mode {
// ValueMode::A8 => Some(format!("${:02X}", cpu.immediate_u8(mmu) as u16)),
ValueMode::A8Hi => Some(format!("${:04X}", (cpu.immediate_u8(mmu) as u16) + 0xFF00)),
ValueMode::A16 => Some(format!("${:04X}", cpu.immediate_u16(mmu))),
ValueMode::D8 => Some(format!("${:02X}", cpu.immediate_u8(mmu) as u16)),
ValueMode::D16 => Some(format!("${:04X}", cpu.immediate_u16(mmu))),
ValueMode::R8 => Some(format!("{}", cpu.immediate_u8(mmu) as i8)),
ValueMode::None => None,
};
match val {
Some(v) => self.dis.replace("{}", &v),
None => self.dis.to_string(),
}
}
}
pub enum ValueMode {
// A8,
A8Hi,
A16,
D8,
D16,
R8,
None,
}
pub fn get_operation(code: u16) -> Operation {
let prefix = code >> 8;
let scode = code & 0x00F0;
let lcode = code & 0x000F;
match prefix {
0x00 => {
match scode { // No Prefix
0x00 => {
match lcode {
0x00 => Operation::new(opx00, 4, "NOP", ValueMode::None),
0x01 => Operation::new(opx01, 12, "LD BC, d16", ValueMode::D16),
0x02 => Operation::new(opx02, 8, "LD (BC), A", ValueMode::None),
0x03 => Operation::new(opx03, 8, "INC BC", ValueMode::None),
0x04 => Operation::new(opx04, 4, "INC B", ValueMode::None),
0x05 => Operation::new(opx05, 4, "DEC B", ValueMode::None),
0x06 => Operation::new(opx06, 8, "LD B, {}", ValueMode::D8),
0x07 => Operation::new(opx07, 4, "RLCA", ValueMode::None),
0x08 => Operation::new(opx08, 20, "LD ({}), SP", ValueMode::A16),
0x09 => Operation::new(opx09, 8, "ADD HL, BC", ValueMode::None),
0x0A => Operation::new(opx0A, 8, "LD A, (BC)", ValueMode::None),
0x0B => Operation::new(opx0B, 8, "DEC BC", ValueMode::None),
0x0C => Operation::new(opx0C, 4, "INC C", ValueMode::None),
0x0D => Operation::new(opx0D, 4, "DEC C", ValueMode::None),
0x0E => Operation::new(opx0E, 8, "LD C, {}", ValueMode::D8),
0x0F => Operation::new(opx0F, 4, "RRCA", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x10 => {
match lcode {
0x00 => Operation::new(opx00, 2, "STOP 0", ValueMode::None),
0x01 => Operation::new(opx11, 12, "LD DE, {}", ValueMode::D16),
0x02 => Operation::new(opx12, 8, "LD (DE), A", ValueMode::None),
0x03 => Operation::new(opx13, 8, "INC DE", ValueMode::None),
0x04 => Operation::new(opx14, 4, "INC D", ValueMode::None),
0x05 => Operation::new(opx15, 4, "DEC D", ValueMode::None),
0x06 => Operation::new(opx16, 8, "LD D, {}", ValueMode::D8),
0x07 => Operation::new(opx17, 4, "RLA", ValueMode::None),
0x08 => Operation::new(opx18, 8, "JR {}", ValueMode::R8),
0x09 => Operation::new(opx19, 8, "ADD HL, DE", ValueMode::None),
0x0A => Operation::new(opx1A, 8, "LD A, (DE)", ValueMode::None),
0x0B => Operation::new(panic, 8, "DEC DE", ValueMode::None),
0x0C => Operation::new(opx1C, 4, "INC E", ValueMode::None),
0x0D => Operation::new(opx1D, 4, "DEC E", ValueMode::None),
0x0E => Operation::new(opx1E, 8, "LD E, {}", ValueMode::D8),
0x0F => Operation::new(opx1F, 4, "RRA", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x20 => {
match lcode {
0x00 => Operation::new(opx20, 12, "JR NZ, {}", ValueMode::R8),
0x01 => Operation::new(opx21, 12, "LD HL, {}", ValueMode::D16),
0x02 => Operation::new(opx22, 12, "LD (HL+), A", ValueMode::None),
0x03 => Operation::new(opx23, 8, "INC HL", ValueMode::None),
0x04 => Operation::new(opx24, 4, "INC H", ValueMode::None),
0x05 => Operation::new(opx25, 4, "DEC H", ValueMode::None),
0x06 => Operation::new(opx26, 8, "LD H, {}", ValueMode::D8),
0x07 => Operation::new(opx27, 4, "DAA", ValueMode::None),
0x08 => Operation::new(opx28, 12, "JR Z, {}", ValueMode::R8),
0x09 => Operation::new(opx29, 8, "ADD HL, HL", ValueMode::None),
0x0A => Operation::new(opx2A, 8, "LD A, (HL+)", ValueMode::None),
0x0B => Operation::new(panic, 8, "DEC HL", ValueMode::None),
0x0C => Operation::new(opx2C, 4, "INC L", ValueMode::None),
0x0D => Operation::new(opx2D, 4, "DEC L", ValueMode::None),
0x0E => Operation::new(opx2E, 8, "LD L, {}", ValueMode::D8),
0x0F => Operation::new(opx2F, 4, "CPL", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x30 => {
match lcode {
0x00 => Operation::new(opx30, 12, "JR NC, r8", ValueMode::R8),
0x01 => Operation::new(opx31, 12, "LD SP, {}", ValueMode::D16),
0x02 => Operation::new(opx32, 8, "LD (HL-), A", ValueMode::None),
0x03 => Operation::new(opx33, 8, "INC SP", ValueMode::None),
0x04 => Operation::new(opx34, 12, "INC (HL)", ValueMode::None),
0x05 => Operation::new(opx35, 12, "DEC (HL)", ValueMode::None),
0x06 => Operation::new(opx36, 12, "LD (HL), d8", ValueMode::D8),
0x07 => Operation::new(panic, 4, "SCF", ValueMode::None),
0x08 => Operation::new(panic, 12, "JR C, r8", ValueMode::R8),
0x09 => Operation::new(opx39, 8, "ADD HL, SP", ValueMode::None),
0x0A => Operation::new(opx3A, 8, "LD A, (HL-)", ValueMode::None),
0x0B => Operation::new(panic, 8, "DEC SP", ValueMode::None),
0x0C => Operation::new(opx3C, 4, "INC A", ValueMode::None),
0x0D => Operation::new(opx3D, 4, "DEC A", ValueMode::None),
0x0E => Operation::new(opx3E, 8, "LD A, {}", ValueMode::D8),
0x0F => Operation::new(panic, 4, "CCF", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x40 => {
match lcode {
0x00 => Operation::new(opx40, 4, "LD B, B", ValueMode::None),
0x01 => Operation::new(opx41, 4, "LD B, C", ValueMode::None),
0x02 => Operation::new(opx42, 4, "LD B, D", ValueMode::None),
0x03 => Operation::new(opx43, 4, "LD B, E", ValueMode::None),
0x04 => Operation::new(opx44, 4, "LD B, H", ValueMode::None),
0x05 => Operation::new(opx45, 4, "LD B, L", ValueMode::None),
0x06 => Operation::new(opx46, 8, "LD B, (HL)", ValueMode::None),
0x07 => Operation::new(opx47, 4, "LD B, A", ValueMode::None),
0x08 => Operation::new(opx48, 4, "LD C, B", ValueMode::None),
0x09 => Operation::new(opx49, 4, "LD C, C", ValueMode::None),
0x0A => Operation::new(opx4A, 4, "LD C, D", ValueMode::None),
0x0B => Operation::new(opx4B, 4, "LD C, E", ValueMode::None),
0x0C => Operation::new(opx4C, 4, "LD C, H", ValueMode::None),
0x0D => Operation::new(opx4D, 4, "LD C, L", ValueMode::None),
0x0E => Operation::new(opx4E, 8, "LD C, (HL)", ValueMode::None),
0x0F => Operation::new(opx4F, 4, "LD C, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x50 => {
match lcode {
0x00 => Operation::new(opx50, 4, "LD D, B", ValueMode::None),
0x01 => Operation::new(opx51, 4, "LD D, C", ValueMode::None),
0x02 => Operation::new(opx52, 4, "LD D, D", ValueMode::None),
0x03 => Operation::new(opx53, 4, "LD D, E", ValueMode::None),
0x04 => Operation::new(opx54, 4, "LD D, H", ValueMode::None),
0x05 => Operation::new(opx55, 4, "LD D, L", ValueMode::None),
0x06 => Operation::new(opx56, 8, "LD D, (HL)", ValueMode::None),
0x07 => Operation::new(opx57, 4, "LD D, A", ValueMode::None),
0x08 => Operation::new(opx58, 4, "LD E, B", ValueMode::None),
0x09 => Operation::new(opx59, 4, "LD E, C", ValueMode::None),
0x0A => Operation::new(opx5A, 4, "LD E, D", ValueMode::None),
0x0B => Operation::new(opx5B, 4, "LD E, E", ValueMode::None),
0x0C => Operation::new(opx5C, 4, "LD E, H", ValueMode::None),
0x0D => Operation::new(opx5D, 4, "LD E, L", ValueMode::None),
0x0E => Operation::new(opx5E, 8, "LD E, (HL)", ValueMode::None),
0x0F => Operation::new(opx5F, 4, "LD E, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x60 => {
match lcode {
0x00 => Operation::new(opx60, 4, "LD H, B", ValueMode::None),
0x01 => Operation::new(opx61, 4, "LD H, C", ValueMode::None),
0x02 => Operation::new(opx62, 4, "LD H, D", ValueMode::None),
0x03 => Operation::new(opx63, 4, "LD H, E", ValueMode::None),
0x04 => Operation::new(opx64, 4, "LD H, H", ValueMode::None),
0x05 => Operation::new(opx65, 4, "LD H, L", ValueMode::None),
0x06 => Operation::new(opx66, 8, "LD H, (HL)", ValueMode::None),
0x07 => Operation::new(opx67, 4, "LD H, A", ValueMode::None),
0x08 => Operation::new(opx68, 4, "LD L, B", ValueMode::None),
0x09 => Operation::new(opx69, 4, "LD L, C", ValueMode::None),
0x0A => Operation::new(opx6A, 4, "LD L, D", ValueMode::None),
0x0B => Operation::new(opx6B, 4, "LD L, E", ValueMode::None),
0x0C => Operation::new(opx6C, 4, "LD L, H", ValueMode::None),
0x0D => Operation::new(opx6D, 4, "LD L, L", ValueMode::None),
0x0E => Operation::new(opx6E, 4, "LD L, (HL)", ValueMode::None),
0x0F => Operation::new(opx6F, 4, "LD L, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x70 => {
match lcode {
0x00 => Operation::new(opx70, 8, "LD (HL), B", ValueMode::None),
0x01 => Operation::new(opx71, 8, "LD (HL), C", ValueMode::None),
0x02 => Operation::new(opx72, 8, "LD (HL), D", ValueMode::None),
0x03 => Operation::new(opx73, 8, "LD (HL), E", ValueMode::None),
0x04 => Operation::new(opx74, 8, "LD (HL), H", ValueMode::None),
0x05 => Operation::new(opx75, 8, "LD (HL), L", ValueMode::None),
0x06 => Operation::new(panic, 4, "HALT", ValueMode::None),
0x07 => Operation::new(opx77, 8, "LD (HL), A", ValueMode::None),
0x08 => Operation::new(opx78, 4, "LD A, B", ValueMode::None),
0x09 => Operation::new(opx79, 4, "LD A, C", ValueMode::None),
0x0A => Operation::new(opx7A, 4, "LD A, D", ValueMode::None),
0x0B => Operation::new(opx7B, 4, "LD A, E", ValueMode::None),
0x0C => Operation::new(opx7C, 4, "LD A, H", ValueMode::None),
0x0D => Operation::new(opx7D, 4, "LD A, L", ValueMode::None),
0x0E => Operation::new(opx7E, 8, "LD A, (HL)", ValueMode::None),
0x0F => Operation::new(opx7F, 4, "LD A, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x80 => {
match lcode {
0x00 => Operation::new(opx80, 4, "ADD A, B", ValueMode::None),
0x01 => Operation::new(opx81, 4, "ADD A, C", ValueMode::None),
0x02 => Operation::new(opx82, 4, "ADD A, D", ValueMode::None),
0x03 => Operation::new(opx83, 4, "ADD A, E", ValueMode::None),
0x04 => Operation::new(opx84, 4, "ADD A, H", ValueMode::None),
0x05 => Operation::new(opx85, 4, "ADD A, L", ValueMode::None),
0x06 => Operation::new(opx86, 8, "ADD A, (HL)", ValueMode::None),
0x07 => Operation::new(opx87, 4, "ADD A, A", ValueMode::None),
0x08 => Operation::new(opx88, 4, "ADC A, B", ValueMode::None),
0x09 => Operation::new(opx89, 4, "ADC A, C", ValueMode::None),
0x0A => Operation::new(opx8A, 4, "ADC A, D", ValueMode::None),
0x0B => Operation::new(opx8B, 4, "ADC A, E", ValueMode::None),
0x0C => Operation::new(opx8C, 4, "ADC A, H", ValueMode::None),
0x0D => Operation::new(opx8D, 4, "ADC A, L", ValueMode::None),
0x0E => Operation::new(opx8E, 8, "ADC A, (HL)", ValueMode::None),
0x0F => Operation::new(opx8F, 4, "ADC A, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x90 => {
match lcode {
0x00 => Operation::new(opx90, 4, "SUB B", ValueMode::None),
0x01 => Operation::new(opx91, 4, "SUB C", ValueMode::None),
0x02 => Operation::new(opx92, 4, "SUB D", ValueMode::None),
0x03 => Operation::new(opx93, 4, "SUB e", ValueMode::None),
0x04 => Operation::new(opx94, 4, "SUB H", ValueMode::None),
0x05 => Operation::new(opx95, 4, "SUB L", ValueMode::None),
0x07 => Operation::new(opx97, 4, "SUB A", ValueMode::None),
0x08 => Operation::new(panic, 4, "SBC A, B", ValueMode::None),
0x09 => Operation::new(panic, 4, "SBC A, C", ValueMode::None),
0x0A => Operation::new(panic, 4, "SBC A, D", ValueMode::None),
0x0B => Operation::new(panic, 4, "SBC A, E", ValueMode::None),
0x0C => Operation::new(panic, 4, "SBC A, H", ValueMode::None),
0x0D => Operation::new(panic, 4, "SBC A, L", ValueMode::None),
0x0E => Operation::new(panic, 8, "SBC A, (HL)", ValueMode::None),
0x0F => Operation::new(panic, 4, "SBC A, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xA0 => {
match lcode {
0x00 => Operation::new(opxA0, 4, "AND B", ValueMode::None),
0x01 => Operation::new(opxA1, 4, "AND C", ValueMode::None),
0x02 => Operation::new(opxA2, 4, "AND D", ValueMode::None),
0x03 => Operation::new(opxA3, 4, "AND E", ValueMode::None),
0x04 => Operation::new(opxA4, 4, "AND H", ValueMode::None),
0x05 => Operation::new(opxA5, 4, "AND L", ValueMode::None),
0x06 => Operation::new(opxA6, 8, "AND (HL)", ValueMode::None),
0x07 => Operation::new(opxA7, 4, "AND A", ValueMode::None),
0x08 => Operation::new(opxA8, 4, "XOR B", ValueMode::None),
0x09 => Operation::new(opxA9, 4, "XOR C", ValueMode::None),
0x0A => Operation::new(opxAA, 4, "XOR D", ValueMode::None),
0x0B => Operation::new(opxAB, 4, "XOR E", ValueMode::None),
0x0C => Operation::new(opxAC, 4, "XOR H", ValueMode::None),
0x0D => Operation::new(opxAD, 4, "XOR L", ValueMode::None),
0x0E => Operation::new(opxAE, 8, "XOR (HL)", ValueMode::None),
0x0F => Operation::new(opxAF, 4, "XOR A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xB0 => {
match lcode {
0x00 => Operation::new(opxB0, 4, "OR B", ValueMode::None),
0x01 => Operation::new(opxB1, 4, "OR C", ValueMode::None),
0x02 => Operation::new(opxB2, 4, "OR D", ValueMode::None),
0x03 => Operation::new(opxB3, 4, "OR E", ValueMode::None),
0x04 => Operation::new(opxB4, 4, "OR H", ValueMode::None),
0x05 => Operation::new(opxB5, 4, "OR L", ValueMode::None),
0x06 => Operation::new(opxB6, 8, "OR (HL)", ValueMode::None),
0x07 => Operation::new(opxB7, 4, "OR A", ValueMode::None),
0x08 => Operation::new(opxB8, 4, "CP B", ValueMode::None),
0x09 => Operation::new(opxB9, 4, "CP C", ValueMode::None),
0x0A => Operation::new(opxBA, 4, "CP D", ValueMode::None),
0x0B => Operation::new(opxBB, 4, "CP E", ValueMode::None),
0x0C => Operation::new(opxBC, 4, "CP H", ValueMode::None),
0x0D => Operation::new(opxBD, 4, "CP L", ValueMode::None),
0x0E => Operation::new(opxBE, 8, "CP (HL)", ValueMode::None),
0x0F => Operation::new(opxBF, 4, "CP A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xC0 => {
match lcode {
0x00 => Operation::new(opxC0, 24, "RET NZ", ValueMode::None),
0x01 => Operation::new(opxC1, 12, "POP BC", ValueMode::None),
0x02 => Operation::new(opxC2, 16, "JP NZ {}", ValueMode::A16),
0x03 => Operation::new(opxC3, 12, "JP {}", ValueMode::A16),
0x04 => Operation::new(opxC4, 24, "CALL NZ, {}", ValueMode::A16),
0x05 => Operation::new(opxC5, 16, "PUSH BC", ValueMode::None),
0x06 => Operation::new(opxC6, 8, "ADD A, {}", ValueMode::D8),
0x07 => Operation::new(opxC7, 16, "RST 00H", ValueMode::D8),
0x08 => Operation::new(opxC8, 20, "RET Z", ValueMode::None),
0x09 => Operation::new(opxC9, 16, "RET", ValueMode::None),
0x0A => Operation::new(opxCA, 16, "JP Z, {}", ValueMode::A16),
0x0C => Operation::new(opxCC, 24, "CALL Z, {}", ValueMode::A16),
0x0D => Operation::new(opxCD, 24, "CALL {}", ValueMode::A16),
0x0E => Operation::new(opxCE, 8, "ADC A, {}", ValueMode::D8),
0x0F => Operation::new(opxCF, 16, "RST 08H", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xD0 => {
match lcode {
0x00 => Operation::new(panic, 20, "RET NC", ValueMode::None),
0x01 => Operation::new(opxD1, 12, "POP DE", ValueMode::None),
0x02 => Operation::new(panic, 16, "JP NC, {}", ValueMode::A16),
0x04 => Operation::new(panic, 24, "CALL NC, {}", ValueMode::A16),
0x05 => Operation::new(opxD5, 16, "PUSH DE", ValueMode::None),
0x06 => Operation::new(opxD6, 8, "SUB {}", ValueMode::D8),
0x07 => Operation::new(panic, 16, "RST 10H", ValueMode::None),
0x08 => Operation::new(opxD8, 20, "RET C", ValueMode::None),
0x09 => Operation::new(opxD9, 16, "RETI", ValueMode::None),
0x0A => Operation::new(opxDA, 16, "JP C, {}", ValueMode::A16),
0x0C => Operation::new(panic, 24, "CALL C, {}", ValueMode::A16),
0x0E => Operation::new(panic, 16, "SBC A, {}", ValueMode::D8),
0x0F => Operation::new(opxDF, 16, "RST 18H", ValueMode::D8),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xE0 => {
match lcode {
0x00 => Operation::new(opxE0, 12, "LDH ({}), A", ValueMode::A8Hi),
0x01 => Operation::new(opxE1, 12, "POP HL", ValueMode::None),
0x02 => Operation::new(opxE2, 8, "LD (C), A", ValueMode::None),
0x05 => Operation::new(opxE5, 16, "PUSH HL", ValueMode::None),
0x06 => Operation::new(opxE6, 8, "AND d8", ValueMode::D8),
0x07 => Operation::new(panic, 16, "RST 20H", ValueMode::None),
0x08 => Operation::new(panic, 16, "ADD SP, {}", ValueMode::R8),
0x09 => Operation::new(opxE9, 4, "JP (HL)", ValueMode::None),
0x0A => Operation::new(opxEA, 16, "LD ({}), A", ValueMode::A16),
0x0E => Operation::new(opxEE, 8, "XOR {}", ValueMode::D8),
0x0F => Operation::new(opxEF, 16, "RST 28H", ValueMode::D8),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xF0 => {
match lcode {
0x00 => Operation::new(opxF0, 12, "LDH A, ({})", ValueMode::A8Hi),
0x01 => Operation::new(opxF1, 12, "POP AF", ValueMode::None),
0x02 => Operation::new(panic, 8, "LD A, (C)", ValueMode::None),
0x03 => Operation::new(opxF3, 4, "DI", ValueMode::None),
0x05 => Operation::new(opxF5, 16, "PUSH AF", ValueMode::None),
0x06 => Operation::new(panic, 8, "OR {}", ValueMode::D8),
0x07 => Operation::new(panic, 16, "RST 30H", ValueMode::None),
0x08 => Operation::new(panic, 12, "LD HL SP+{}", ValueMode::R8),
0x09 => Operation::new(opxF9, 8, "LD SP, HL", ValueMode::None),
0x0A => Operation::new(opxFA, 16, "LD A, ({})", ValueMode::A16),
0x0B => Operation::new(opxFB, 4, "EI", ValueMode::None),
0x0E => Operation::new(opxFE, 8, "CP {}", ValueMode::D8),
0x0F => Operation::new(opxFF, 16, "RST 38H", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xCB => {
match scode { // CB Prefix
0x10 => {
match lcode {
0x01 => Operation::new(cbx11, 8, "RL C", ValueMode::None),
0x08 => Operation::new(cbx18, 8, "RR B", ValueMode::None),
0x09 => Operation::new(cbx19, 8, "RR C", ValueMode::None),
0x0A => Operation::new(cbx1A, 8, "RR D", ValueMode::None),
0x0B => Operation::new(cbx1B, 8, "RR E", ValueMode::None),
0x0C => Operation::new(cbx1C, 8, "RR H", ValueMode::None),
0x0D => Operation::new(cbx1D, 8, "RR L", ValueMode::None),
0x0E => Operation::new(cbx1E, 8, "RR (HL)", ValueMode::None),
0x0F => Operation::new(cbx1F, 8, "RR A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x20 => {
match lcode {
0x00 => Operation::new(cbx20, 8, "SLA B", ValueMode::None),
0x01 => Operation::new(cbx21, 8, "SLA C", ValueMode::None),
0x02 => Operation::new(cbx22, 8, "SLA D", ValueMode::None),
0x03 => Operation::new(cbx23, 8, "SLA E", ValueMode::None),
0x04 => Operation::new(cbx24, 8, "SLA H", ValueMode::None),
0x05 => Operation::new(cbx25, 8, "SLA L", ValueMode::None),
0x07 => Operation::new(cbx27, 8, "SLA A", ValueMode::None),
// 0x08 => Operation::new(cbx28, 8, "SRA B", ValueMode::None),
// 0x09 => Operation::new(cbx29, 8, "SRA C", ValueMode::None),
// 0x0A => Operation::new(cbx2A, 8, "SRA D", ValueMode::None),
// 0x0B => Operation::new(cbx2B, 8, "SRA E", ValueMode::None),
// 0x0C => Operation::new(cbx2C, 8, "SRA H", ValueMode::None),
// 0x0D => Operation::new(cbx2D, 8, "SRA L", ValueMode::None),
// 0x0F => Operation::new(cbx2F, 8, "SRA A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x30 => {
match lcode {
0x00 => Operation::new(cbx30, 8, "SWAP B", ValueMode::None),
0x01 => Operation::new(cbx31, 8, "SWAP C", ValueMode::None),
0x02 => Operation::new(cbx32, 8, "SWAP D", ValueMode::None),
0x03 => Operation::new(cbx33, 8, "SWAP E", ValueMode::None),
0x04 => Operation::new(cbx34, 8, "SWAP H", ValueMode::None),
0x05 => Operation::new(cbx35, 8, "SWAP L", ValueMode::None),
0x07 => Operation::new(cbx37, 8, "SWAP A", ValueMode::None),
0x08 => Operation::new(cbx38, 8, "SRL B", ValueMode::None),
0x09 => Operation::new(cbx39, 8, "SRL C", ValueMode::None),
0x0A => Operation::new(cbx3A, 8, "SRL D", ValueMode::None),
0x0B => Operation::new(cbx3B, 8, "SRL E", ValueMode::None),
0x0C => Operation::new(cbx3C, 8, "SRL H", ValueMode::None),
0x0D => Operation::new(cbx3D, 8, "SRL L", ValueMode::None),
0x0F => Operation::new(cbx3F, 8, "SRL A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x40 => {
match lcode {
0x00 => Operation::new(cbx40, 8, "BIT 0,B", ValueMode::None),
0x01 => Operation::new(cbx41, 8, "BIT 0,C", ValueMode::None),
0x02 => Operation::new(cbx42, 8, "BIT 0,D", ValueMode::None),
0x03 => Operation::new(cbx43, 8, "BIT 0,E", ValueMode::None),
0x04 => Operation::new(cbx44, 8, "BIT 0,H", ValueMode::None),
0x05 => Operation::new(cbx45, 8, "BIT 0,L", ValueMode::None),
0x07 => Operation::new(cbx47, 8, "BIT 0,A", ValueMode::None),
0x08 => Operation::new(cbx48, 8, "BIT 1,B", ValueMode::None),
0x09 => Operation::new(cbx49, 8, "BIT 1,C", ValueMode::None),
0x0A => Operation::new(cbx4A, 8, "BIT 1,D", ValueMode::None),
0x0B => Operation::new(cbx4B, 8, "BIT 1,E", ValueMode::None),
0x0C => Operation::new(cbx4C, 8, "BIT 1,H", ValueMode::None),
0x0D => Operation::new(cbx4D, 8, "BIT 1,L", ValueMode::None),
0x0F => Operation::new(cbx4F, 8, "BIT 1,A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x50 => {
match lcode {
0x00 => Operation::new(cbx50, 8, "BIT 2,B", ValueMode::None),
0x01 => Operation::new(cbx51, 8, "BIT 2,C", ValueMode::None),
0x02 => Operation::new(cbx52, 8, "BIT 2,D", ValueMode::None),
0x03 => Operation::new(cbx53, 8, "BIT 2,E", ValueMode::None),
0x04 => Operation::new(cbx54, 8, "BIT 2,H", ValueMode::None),
0x05 => Operation::new(cbx55, 8, "BIT 2,L", ValueMode::None),
0x07 => Operation::new(cbx57, 8, "BIT 2,A", ValueMode::None),
0x08 => Operation::new(cbx58, 8, "BIT 3,B", ValueMode::None),
0x09 => Operation::new(cbx59, 8, "BIT 3,C", ValueMode::None),
0x0A => Operation::new(cbx5A, 8, "BIT 3,D", ValueMode::None),
0x0B => Operation::new(cbx5B, 8, "BIT 3,E", ValueMode::None),
0x0C => Operation::new(cbx5C, 8, "BIT 3,H", ValueMode::None),
0x0D => Operation::new(cbx5D, 8, "BIT 3,L", ValueMode::None),
0x0F => Operation::new(cbx5F, 8, "BIT 3,A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x60 => {
match lcode {
0x00 => Operation::new(cbx60, 8, "BIT 4,B", ValueMode::None),
0x01 => Operation::new(cbx61, 8, "BIT 4,C", ValueMode::None),
0x02 => Operation::new(cbx62, 8, "BIT 4,D", ValueMode::None),
0x03 => Operation::new(cbx63, 8, "BIT 4,E", ValueMode::None),
0x04 => Operation::new(cbx64, 8, "BIT 4,H", ValueMode::None),
0x05 => Operation::new(cbx65, 8, "BIT 4,L", ValueMode::None),
0x07 => Operation::new(cbx67, 8, "BIT 4,A", ValueMode::None),
0x08 => Operation::new(cbx68, 8, "BIT 5,B", ValueMode::None),
0x09 => Operation::new(cbx69, 8, "BIT 5,C", ValueMode::None),
0x0A => Operation::new(cbx6A, 8, "BIT 5,D", ValueMode::None),
0x0B => Operation::new(cbx6B, 8, "BIT 5,E", ValueMode::None),
0x0C => Operation::new(cbx6C, 8, "BIT 5,H", ValueMode::None),
0x0D => Operation::new(cbx6D, 8, "BIT 5,L", ValueMode::None),
0x0F => Operation::new(cbx6F, 8, "BIT 5,A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x70 => {
match lcode {
0x00 => Operation::new(cbx70, 8, "BIT 5,B", ValueMode::None),
0x01 => Operation::new(cbx71, 8, "BIT 5,C", ValueMode::None),
0x02 => Operation::new(cbx72, 8, "BIT 5,D", ValueMode::None),
0x03 => Operation::new(cbx73, 8, "BIT 5,E", ValueMode::None),
0x04 => Operation::new(cbx74, 8, "BIT 5,H", ValueMode::None),
0x05 => Operation::new(cbx75, 8, "BIT 5,L", ValueMode::None),
0x07 => Operation::new(cbx77, 8, "BIT 5,A", ValueMode::None),
0x08 => Operation::new(cbx78, 8, "BIT 7,B", ValueMode::None),
0x09 => Operation::new(cbx79, 8, "BIT 7,C", ValueMode::None),
0x0A => Operation::new(cbx7A, 8, "BIT 7,D", ValueMode::None),
0x0B => Operation::new(cbx7B, 8, "BIT 7,E", ValueMode::None),
0x0C => Operation::new(cbx7C, 8, "BIT 7,H", ValueMode::None),
0x0D => Operation::new(cbx7D, 8, "BIT 7,L", ValueMode::None),
0x0E => Operation::new(cbx7E, 8, "BIT 7,(HL)", ValueMode::None),
0x0F => Operation::new(cbx7F, 8, "BIT 7,A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x80 => {
match lcode {
0x00 => Operation::new(cbx80, 8, "RES 0, B", ValueMode::None),
0x01 => Operation::new(cbx81, 8, "RES 0, C", ValueMode::None),
0x02 => Operation::new(cbx82, 8, "RES 0, D", ValueMode::None),
0x03 => Operation::new(cbx83, 8, "RES 0, E", ValueMode::None),
0x04 => Operation::new(cbx84, 8, "RES 0, H", ValueMode::None),
0x05 => Operation::new(cbx85, 8, "RES 0, L", ValueMode::None),
0x06 => Operation::new(cbx86, 8, "RES 0, (HL)", ValueMode::None),
0x07 => Operation::new(cbx87, 8, "RES 0, A", ValueMode::None),
0x08 => Operation::new(cbx88, 8, "RES 1, B", ValueMode::None),
0x09 => Operation::new(cbx89, 8, "RES 1, C", ValueMode::None),
0x0A => Operation::new(cbx8A, 8, "RES 1, D", ValueMode::None),
0x0B => Operation::new(cbx8B, 8, "RES 1, E", ValueMode::None),
0x0C => Operation::new(cbx8C, 8, "RES 1, H", ValueMode::None),
0x0D => Operation::new(cbx8D, 8, "RES 1, L", ValueMode::None),
0x0E => Operation::new(cbx8E, 8, "RES 1, (HL)", ValueMode::None),
0x0F => Operation::new(cbx8F, 8, "RES 1, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0x90 => {
match lcode {
0x00 => Operation::new(cbx90, 8, "RES 2, B", ValueMode::None),
0x01 => Operation::new(cbx91, 8, "RES 2, C", ValueMode::None),
0x02 => Operation::new(cbx92, 8, "RES 2, D", ValueMode::None),
0x03 => Operation::new(cbx93, 8, "RES 2, E", ValueMode::None),
0x04 => Operation::new(cbx94, 8, "RES 2, H", ValueMode::None),
0x05 => Operation::new(cbx95, 8, "RES 2, L", ValueMode::None),
0x06 => Operation::new(cbx96, 8, "RES 2, (HL)", ValueMode::None),
0x07 => Operation::new(cbx97, 8, "RES 2, A", ValueMode::None),
0x08 => Operation::new(cbx98, 8, "RES 3, B", ValueMode::None),
0x09 => Operation::new(cbx99, 8, "RES 3, C", ValueMode::None),
0x0A => Operation::new(cbx9A, 8, "RES 3, D", ValueMode::None),
0x0B => Operation::new(cbx9B, 8, "RES 3, E", ValueMode::None),
0x0C => Operation::new(cbx9C, 8, "RES 3, H", ValueMode::None),
0x0D => Operation::new(cbx9D, 8, "RES 3, L", ValueMode::None),
0x0E => Operation::new(cbx9E, 8, "RES 3, (HL)", ValueMode::None),
0x0F => Operation::new(cbx9F, 8, "RES 3, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xA0 => {
match lcode {
0x00 => Operation::new(cbxA0, 8, "RES 4, B", ValueMode::None),
0x01 => Operation::new(cbxA1, 8, "RES 4, C", ValueMode::None),
0x02 => Operation::new(cbxA2, 8, "RES 4, D", ValueMode::None),
0x03 => Operation::new(cbxA3, 8, "RES 4, E", ValueMode::None),
0x04 => Operation::new(cbxA4, 8, "RES 4, H", ValueMode::None),
0x05 => Operation::new(cbxA5, 8, "RES 4, L", ValueMode::None),
0x06 => Operation::new(cbxA6, 8, "RES 4, (HL)", ValueMode::None),
0x07 => Operation::new(cbxA7, 8, "RES 4, A", ValueMode::None),
0x08 => Operation::new(cbxA8, 8, "RES 5, B", ValueMode::None),
0x09 => Operation::new(cbxA9, 8, "RES 5, C", ValueMode::None),
0x0A => Operation::new(cbxAA, 8, "RES 5, D", ValueMode::None),
0x0B => Operation::new(cbxAB, 8, "RES 5, E", ValueMode::None),
0x0C => Operation::new(cbxAC, 8, "RES 5, H", ValueMode::None),
0x0D => Operation::new(cbxAD, 8, "RES 5, L", ValueMode::None),
0x0E => Operation::new(cbxAE, 8, "RES 5, (HL)", ValueMode::None),
0x0F => Operation::new(cbxAF, 8, "RES 5, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xB0 => {
match lcode {
0x00 => Operation::new(cbxB0, 8, "RES 6, B", ValueMode::None),
0x01 => Operation::new(cbxB1, 8, "RES 6, C", ValueMode::None),
0x02 => Operation::new(cbxB2, 8, "RES 6, D", ValueMode::None),
0x03 => Operation::new(cbxB3, 8, "RES 6, E", ValueMode::None),
0x04 => Operation::new(cbxB4, 8, "RES 6, H", ValueMode::None),
0x05 => Operation::new(cbxB5, 8, "RES 6, L", ValueMode::None),
0x06 => Operation::new(cbxB6, 8, "RES 6, (HL)", ValueMode::None),
0x07 => Operation::new(cbxB7, 8, "RES 6, A", ValueMode::None),
0x08 => Operation::new(cbxB8, 8, "RES 7, B", ValueMode::None),
0x09 => Operation::new(cbxB9, 8, "RES 7, C", ValueMode::None),
0x0A => Operation::new(cbxBA, 8, "RES 7, D", ValueMode::None),
0x0B => Operation::new(cbxBB, 8, "RES 7, E", ValueMode::None),
0x0C => Operation::new(cbxBC, 8, "RES 7, H", ValueMode::None),
0x0D => Operation::new(cbxBD, 8, "RES 7, L", ValueMode::None),
0x0E => Operation::new(cbxBE, 8, "RES 7, (HL)", ValueMode::None),
0x0F => Operation::new(cbxBF, 8, "RES 7, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
0xF0 => {
match lcode {
// 0x00 => Operation::new(cbxF0, 8, "SET 6, B", ValueMode::None),
// 0x01 => Operation::new(cbxF1, 8, "SET 6, C", ValueMode::None),
// 0x02 => Operation::new(cbxF2, 8, "SET 6, D", ValueMode::None),
// 0x03 => Operation::new(cbxF3, 8, "SET 6, E", ValueMode::None),
// 0x04 => Operation::new(cbxF4, 8, "SET 6, H", ValueMode::None),
// 0x05 => Operation::new(cbxF5, 8, "SET 6, L", ValueMode::None),
// 0x06 => Operation::new(cbxF6, 8, "SET 6, (HL)", ValueMode::None),
// 0x07 => Operation::new(cbxF7, 8, "SET 6, A", ValueMode::None),
0x08 => Operation::new(cbxF8, 8, "SET 7, B", ValueMode::None),
0x09 => Operation::new(cbxF9, 8, "SET 7, C", ValueMode::None),
0x0A => Operation::new(cbxFA, 8, "SET 7, D", ValueMode::None),
0x0B => Operation::new(cbxFB, 8, "SET 7, E", ValueMode::None),
0x0C => Operation::new(cbxFC, 8, "SET 7, H", ValueMode::None),
0x0D => Operation::new(cbxFD, 8, "SET 7, L", ValueMode::None),
0x0E => Operation::new(cbxFE, 8, "SET 7, (HL)", ValueMode::None),
0x0F => Operation::new(cbxFF, 8, "SET 7, A", ValueMode::None),
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
_ => panic!(format!("Opcode 0x{:04x} is not yet implemented.", code)),
}
}
_ => panic!("0x{:04X} is not a valid opcode.", code),
}
}
pub fn panic(cpu: &mut Cpu, mmu: &mut Mmu) {
panic!("THIS CODE NOT IMPLEMENTED!")
}
pub fn opx00(cpu: &mut Cpu, mmu: &mut Mmu) {
/* NOP */
}
pub fn opx01(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD BC, d16
// Load d16 into the address specified at HL
let d16 = cpu.immediate_u16_pc(mmu);
cpu.regs.set_bc(d16);
}
pub fn opx02(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD (BC), A
let a = cpu.regs.a;
let addr = cpu.regs.bc() as usize;
mmu.write(addr, a);
}
pub fn opx03(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.bc();
cpu.regs.set_bc(val.wrapping_add(1));
}
pub fn opx04(cpu: &mut Cpu, mmu: &mut Mmu) {
inc_x(&mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn opx05(cpu: &mut Cpu, mmu: &mut Mmu) {
dec_x(&mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn opx06(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.immediate_u8_pc(mmu);
ld_x_y(&mut cpu.regs.b, v)
}
pub fn opx07(cpu: &mut Cpu, mmu: &mut Mmu) {
let a = cpu.regs.a;
let c = (a >> 7) & 1;
cpu.regs.a = a << 1;
cpu.regs.a |= c;
cpu.regs.flags.c = c == 1;
}
pub fn opx08(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD (a16), SP
// Load the 2-byte sp into 2-bytes of memory located at
// the value specified by immediate_u16_pc
let addr = cpu.immediate_u16_pc(mmu) as usize;
mmu.write_u16(addr, cpu.regs.sp as u16);
}
pub fn opx09(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.regs.bc();
add_hl(cpu, v)
}
pub fn opx0A(cpu: &mut Cpu, mmu: &mut Mmu) {
let bc = cpu.regs.bc() as usize;
cpu.regs.a = mmu.read(bc);
}
pub fn opx0B(cpu: &mut Cpu, mmu: &mut Mmu) {
let bc = cpu.regs.bc();
cpu.regs.set_bc(bc.wrapping_sub(1))
}
pub fn opx0C(cpu: &mut Cpu, mmu: &mut Mmu) {
inc_x(&mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn opx0D(cpu: &mut Cpu, mmu: &mut Mmu) {
dec_x(&mut cpu.regs.c, &mut cpu.regs.flags);
info!("Decremented Register C to 0x{:04X}", cpu.regs.c);
}
pub fn opx0E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.immediate_u8_pc(mmu);
ld_x_y(&mut cpu.regs.c, v)
}
pub fn opx0F(cpu: &mut Cpu, mmu: &mut Mmu) {
let c = cpu.regs.flags.c;
cpu.regs.flags.c = cpu.regs.a & 1 == 1;
cpu.regs.a = cpu.regs.a >> 1;
cpu.regs.a |= (c as u8) << 7;
}
pub fn opx18(cpu: &mut Cpu, mmu: &mut Mmu) {
// JR r8
let signed = cpu.immediate_u8_pc(mmu) as i8;
match signed > 0 {
true => cpu.regs.pc += signed.abs() as usize,
_ => cpu.regs.pc -= signed.abs() as usize,
};
}
pub fn opx20(cpu: &mut Cpu, mmu: &mut Mmu) {
// JR NZ, r8
// Jump Relative if not zero (signed immediate 8-bit)
let signed = cpu.immediate_u8_pc(mmu) as i8;
if cpu.regs.flags.z == true {
return {};
};
// TODO: problem?
match signed > 0 {
true => cpu.regs.pc += signed.abs() as usize,
_ => cpu.regs.pc -= signed.abs() as usize,
};
}
pub fn opx30(cpu: &mut Cpu, mmu: &mut Mmu) {
// JR NZ, r8
// Jump Relative if not zero (signed immediate 8-bit)
let signed = cpu.immediate_u8_pc(mmu) as i8;
if cpu.regs.flags.c == true {
return {};
};
match signed > 0 {
true => cpu.regs.pc += signed.abs() as usize,
_ => cpu.regs.pc -= signed.abs() as usize,
};
}
pub fn opx21(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD HL, d16
let new = cpu.immediate_u16_pc(mmu);
cpu.regs.set_hl(new);
}
pub fn opx22(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD (HL+), A
// Load the value of register A into mem address HL
// Increment HL
let hl = cpu.regs.hl() as usize;
mmu.write(hl, cpu.regs.a);
cpu.regs.set_hl((hl + 1) as u16);
}
pub fn opx23(cpu: &mut Cpu, mmu: &mut Mmu) {
// INC HL
// Increment HL by one.
let new = cpu.regs.hl().wrapping_add(1);
cpu.regs.set_hl(new);
}
pub fn opx13(cpu: &mut Cpu, mmu: &mut Mmu) {
// INC DE
// Increment DE by one.
let new = cpu.regs.de().wrapping_add(1);
cpu.regs.set_de(new);
}
pub fn opx32(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD (HL-), A
// Load the value of register A into mem address HL
// Decrement HL
let addr = cpu.regs.hl() as usize;
let a = cpu.regs.a;
mmu.write(addr, a);
cpu.regs.set_hl((addr as u16).wrapping_sub(1));
info!("\n\nH: 0b{:08b}\n", cpu.regs.h);
}
pub fn opx33(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.sp;
cpu.regs.sp = val.wrapping_add(1)
}
pub fn opx31(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD SP, d16
// Load immediate 16-bit into Stack Pointer
let pc = cpu.regs.pc;
let sp = cpu.immediate_u16_pc(mmu) as usize;
cpu.regs.sp = sp;
}
pub fn opxE2(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD (C), A
// Load value from register A into mem at address specified by register C
let c = cpu.regs.c as usize + 0xFF00;
mmu.write(c as usize, cpu.regs.a);
}
pub fn opxEA(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD (a16), A
// Load the value of register A into memory at address specified by immediate 16
let addr = cpu.immediate_u16_pc(mmu) as usize;
mmu.write(addr, cpu.regs.a);
}
pub fn opxE0(cpu: &mut Cpu, mmu: &mut Mmu) {
// LDH (a8), A
// Load the value of register A into mem at 0xFF00 + immediate 8-bit
let addr = (0xFF00 + cpu.immediate_u8_pc(mmu) as u16) as usize;
mmu.write(addr, cpu.regs.a);
}
pub fn opx11(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD DE, d16
// Load immediate 16-bit into register DE
let d16 = cpu.immediate_u16_pc(mmu);
cpu.regs.set_de(d16);
}
pub fn opx1A(cpu: &mut Cpu, mmu: &mut Mmu) {
// MARK
// "LD A, (DE)"
// Load value of memory at address specified in DE into register A
let addr = mmu.read(cpu.regs.de() as usize);
cpu.regs.a = addr;
}
pub fn opxCD(cpu: &mut Cpu, mmu: &mut Mmu) {
// Call a16
// Set pc to value of immediate 16-bit
// push both bytes of pc onto the stack
// increment the sp by two
let a16 = cpu.immediate_u16_pc(mmu);
let pc = cpu.regs.pc as u16;
cpu.stack_push_u16(pc, mmu);
cpu.regs.pc = a16 as usize;
}
pub fn opxCC(cpu: &mut Cpu, mmu: &mut Mmu) {
// Call Z, a16
// Set pc to value of immediate 16-bit
// push both bytes of pc onto the stack
// increment the sp by two
if cpu.regs.flags.z == true {
opxCD(cpu, mmu);
} else {
cpu.regs.pc += 2;
}
}
pub fn opxC2(cpu: &mut Cpu, mmu: &mut Mmu) {
// JP NZ,a16
cpu.regs.pc = cpu.immediate_u16_pc(mmu) as usize;
}
pub fn opxC3(cpu: &mut Cpu, mmu: &mut Mmu) {
let addr = cpu.immediate_u16_pc(mmu) as usize;
cpu.regs.pc = addr;
}
pub fn opxC6(cpu: &mut Cpu, mmu: &mut Mmu) {
let d8 = cpu.immediate_u8_pc(mmu);
let hc = add_hc_u8(cpu.regs.a, d8);
let c = add_c_u8(cpu.regs.a, d8);
cpu.regs.a = cpu.regs.a.wrapping_add(d8);
cpu.regs.flags.z = cpu.regs.a == 0;
cpu.regs.flags.n = false;
cpu.regs.flags.h = hc;
cpu.regs.flags.c = c;
}
pub fn opxE9(cpu: &mut Cpu, mmu: &mut Mmu) {
// JP (HL)
let hl = cpu.regs.hl() as usize;
cpu.regs.pc = hl;
}
pub fn opxE6(cpu: &mut Cpu, mmu: &mut Mmu) {
// AND d8
let d8 = cpu.immediate_u8_pc(mmu);
cpu.regs.a &= d8;
cpu.regs.flags.z = cpu.regs.a == 0;
cpu.regs.flags.h = true;
}
pub fn opx17(cpu: &mut Cpu, mmu: &mut Mmu) {
// RLA - Shift A left, place lost bit into carry, and move carry to bit 0.
let msb = cpu.regs.a >> 7;
cpu.regs.a = cpu.regs.a << 1;
cpu.regs.a |= cpu.regs.flags.c as u8;
cpu.regs.flags.c = msb == 1;
}
pub fn opxC9(cpu: &mut Cpu, mmu: &mut Mmu) {
// RET
cpu.regs.pc = cpu.stack_pop_u16(mmu) as usize;
}
pub fn opxC0(cpu: &mut Cpu, mmu: &mut Mmu) {
if cpu.regs.flags.z == false {
let popped = cpu.stack_pop_u16(mmu) as usize;
cpu.regs.pc = popped;
}
}
pub fn opxFE(cpu: &mut Cpu, mmu: &mut Mmu) {
// CP d8
// Compare A with d8
// set flags Z, H and C as required
// set N flag to 1
let a = cpu.regs.a;
let d8 = cpu.immediate_u8_pc(mmu);
let hc = sub_hc_u8(a, d8);
cpu.regs.flags.z = a - d8 == 0;
cpu.regs.flags.c = a < d8;
cpu.regs.flags.n = true;
cpu.regs.flags.h = hc;
}
pub fn opxCE(cpu: &mut Cpu, mmu: &mut Mmu) {
// ADC A, d8
// Z 0 H C
let ac = cpu.regs.flags.c as u8 + cpu.immediate_u8_pc(mmu);
let a = cpu.regs.a;
let c = add_c_u8(a, ac);
let hc = add_hc_u8(a, ac);
cpu.regs.a = a.wrapping_add(ac);
cpu.regs.flags.z = cpu.regs.a == 0;
cpu.regs.flags.n = false;
cpu.regs.flags.h = hc;
cpu.regs.flags.c = c;
}
pub fn cbx11(cpu: &mut Cpu, mmu: &mut Mmu) {
let reg = &mut cpu.regs.c;
let flags = &mut cpu.regs.flags;
rl_n(reg, flags);
}
fn rl_n(reg: &mut u8, flags: &mut FlagRegister) {
// RL n
// Rotate register n one bit to the left
// MSB goes into carry flag
// carry flag goes into lsbit of C
// if the result is zero, set the zero flag to 1 else 0
let msb = *reg >> 7;
let carry = flags.c as u8;
*reg = *reg << 1;
*reg |= carry;
flags.c = msb == 1;
flags.z = match *reg {
0 => true,
_ => false,
};
}
fn bit_x_n(bit_no: usize, reg: &mut u8, flags: &mut FlagRegister) {
// BIT x, n
// Clear the zero flag if bit x of register n == 1
// set N flag to 0 and H flag to 1
flags.z = reg.get_bit(bit_no) == 1;
info!("Z: {}", flags.z);
flags.n = false;
flags.h = true;
}
pub fn cbx40(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(0, &mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx41(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(0, &mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx42(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(0, &mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx43(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(0, &mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx44(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(0, &mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx45(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(0, &mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx47(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(0, &mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn cbx48(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(1, &mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx49(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(1, &mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx4A(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(1, &mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx4B(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(1, &mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx4C(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(1, &mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx4D(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(1, &mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx4F(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(1, &mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn cbx50(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(2, &mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx51(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(2, &mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx52(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(2, &mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx53(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(2, &mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx54(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(2, &mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx55(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(2, &mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx57(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(2, &mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn cbx58(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(3, &mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx59(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(3, &mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx5A(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(3, &mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx5B(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(3, &mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx5C(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(3, &mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx5D(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(3, &mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx5F(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(3, &mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn cbx60(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(4, &mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx61(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(4, &mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx62(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(4, &mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx63(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(4, &mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx64(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(4, &mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx65(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(4, &mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx67(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(4, &mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn cbx68(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(5, &mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx69(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(5, &mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx6A(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(5, &mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx6B(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(5, &mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx6C(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(5, &mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx6D(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(5, &mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx6F(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(5, &mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn cbx70(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(6, &mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx71(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(6, &mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx72(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(6, &mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx73(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(6, &mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx74(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(6, &mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx75(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(6, &mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx77(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(6, &mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn cbx78(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(7, &mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx79(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(7, &mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx7A(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(7, &mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx7B(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(7, &mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx7C(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(7, &mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx7D(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(7, &mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx7E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = &mut mmu.read(cpu.regs.hl() as usize);
bit_x_n(7, v, &mut cpu.regs.flags)
}
pub fn cbx7F(cpu: &mut Cpu, mmu: &mut Mmu) {
bit_x_n(7, &mut cpu.regs.a, &mut cpu.regs.flags)
}
fn dec_x(reg: &mut u8, flags: &mut FlagRegister) {
let hc = sub_hc_u8(*reg, 1);
*reg = reg.wrapping_sub(1);
flags.h = hc;
flags.n = true;
flags.z = *reg == 0;
}
fn inc_x(reg: &mut u8, flags: &mut FlagRegister) {
let hc = add_hc_u8(*reg, 1);
*reg = reg.wrapping_add(1);
flags.z = *reg == 0;
flags.n = false;
flags.h = hc;
}
pub fn opx14(cpu: &mut Cpu, mmu: &mut Mmu) {
inc_x(&mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn opx24(cpu: &mut Cpu, mmu: &mut Mmu) {
inc_x(&mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn opx1C(cpu: &mut Cpu, mmu: &mut Mmu) {
inc_x(&mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn opx2C(cpu: &mut Cpu, mmu: &mut Mmu) {
inc_x(&mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn opx3C(cpu: &mut Cpu, mmu: &mut Mmu) {
inc_x(&mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn opx15(cpu: &mut Cpu, mmu: &mut Mmu) {
dec_x(&mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn opx25(cpu: &mut Cpu, mmu: &mut Mmu) {
dec_x(&mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn opx1D(cpu: &mut Cpu, mmu: &mut Mmu) {
dec_x(&mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn opx2D(cpu: &mut Cpu, mmu: &mut Mmu) {
dec_x(&mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn opx3D(cpu: &mut Cpu, mmu: &mut Mmu) {
dec_x(&mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn opx34(cpu: &mut Cpu, mmu: &mut Mmu) {
// INC (HL)
let addr = cpu.regs.hl() as usize;
let mut v = mmu.read(addr);
let hc = add_hc_u8(v, 1);
v = v.wrapping_add(1);
mmu.write(addr, v);
cpu.regs.flags.n = false;
cpu.regs.flags.h = hc;
cpu.regs.flags.z = v == 0;
}
pub fn opx35(cpu: &mut Cpu, mmu: &mut Mmu) {
// DEC (HL)
let addr = cpu.regs.hl() as usize;
let mut v = mmu.read(addr);
let hc = sub_hc_u8(v, 1);
v = v.wrapping_sub(1);
mmu.write(addr, v);
cpu.regs.flags.h = hc;
cpu.regs.flags.n = true;
cpu.regs.flags.z = v == 0;
}
pub fn opx28(cpu: &mut Cpu, mmu: &mut Mmu) {
// JR Z, r8
// Jump relative if Z flag == true
let signed = cpu.immediate_u8_pc(mmu) as i8;
if cpu.regs.flags.z == false {
return {};
};
match signed > 0 {
true => cpu.regs.pc += signed.abs() as usize,
_ => cpu.regs.pc -= signed.abs() as usize,
};
}
pub fn opx27(cpu: &mut Cpu, mmu: &mut Mmu) {
let mut newa = cpu.regs.a as u16;
if cpu.regs.flags.n == false {
if cpu.regs.flags.h == true || (newa & 0xF) > 9 {
newa += 0x6;
}
if cpu.regs.flags.c == true || newa > 0x9F {
newa += 0x60;
}
} else {
if cpu.regs.flags.h {
newa = (newa - 6) & 0xFF;
}
if cpu.regs.flags.c {
newa -= 0x60;
}
}
if (newa & 0x100) == 0x100 {
cpu.regs.flags.c = true;
}
cpu.regs.flags.h = false;
cpu.regs.flags.z = false;
newa &= 0xFF;
if newa == 0 {
cpu.regs.flags.z = true;
}
cpu.regs.a = newa as u8;
}
pub fn opxF3(cpu: &mut Cpu, mmu: &mut Mmu) {
mmu.ime = false;
}
pub fn opxFB(cpu: &mut Cpu, mmu: &mut Mmu) {
mmu.ime = true;
}
pub fn ld_x_y(regx: &mut u8, regy: u8) {
*regx = regy
}
pub fn opx1E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.immediate_u8_pc(mmu);
ld_x_y(&mut cpu.regs.e, v)
}
pub fn opx2E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.immediate_u8_pc(mmu);
ld_x_y(&mut cpu.regs.l, v)
}
pub fn opx3E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.immediate_u8_pc(mmu);
ld_x_y(&mut cpu.regs.a, v)
}
pub fn opx16(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.immediate_u8_pc(mmu);
ld_x_y(&mut cpu.regs.d, v)
}
pub fn opx26(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.immediate_u8_pc(mmu);
ld_x_y(&mut cpu.regs.h, v)
}
pub fn opxF0(cpu: &mut Cpu, mmu: &mut Mmu) {
let a = 0xFF00 + cpu.immediate_u8_pc(mmu) as usize;
ld_x_y(&mut cpu.regs.a, mmu.read(a))
}
fn sub_a_x(val: u8, cpu: &mut Cpu) {
let hc = sub_hc_u8(cpu.regs.a, val);
let c = sub_c_u8(cpu.regs.a, val);
cpu.regs.a = cpu.regs.a.wrapping_sub(val);
cpu.regs.flags.z = cpu.regs.a == 0;
cpu.regs.flags.n = true;
cpu.regs.flags.h = hc;
cpu.regs.flags.c = c;
}
pub fn opxD6(cpu: &mut Cpu, mmu: &mut Mmu) {
let d8 = cpu.immediate_u8_pc(mmu);
sub_a_x(d8, cpu);
}
pub fn opx40(cpu: &mut Cpu, mmu: &mut Mmu) {}
pub fn opx41(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.b, cpu.regs.c)
}
pub fn opx42(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.b, cpu.regs.d)
}
pub fn opx43(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.b, cpu.regs.e)
}
pub fn opx44(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.b, cpu.regs.h)
}
pub fn opx45(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.b, cpu.regs.l)
}
pub fn opx46(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = mmu.read(cpu.regs.hl() as usize);
ld_x_y(&mut cpu.regs.b, v)
}
pub fn opx47(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.b, cpu.regs.a)
}
pub fn opx48(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.b, cpu.regs.a)
}
pub fn opx49(cpu: &mut Cpu, mmu: &mut Mmu) {}
pub fn opx4A(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.c, cpu.regs.d)
}
pub fn opx4B(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.c, cpu.regs.e)
}
pub fn opx4C(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.c, cpu.regs.h)
}
pub fn opx4D(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.c, cpu.regs.l)
}
pub fn opx4E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = mmu.read(cpu.regs.hl() as usize);
ld_x_y(&mut cpu.regs.c, v)
}
pub fn opx4F(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.c, cpu.regs.a)
}
pub fn opx50(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.d, cpu.regs.b)
}
pub fn opx51(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.d, cpu.regs.c)
}
pub fn opx52(cpu: &mut Cpu, mmu: &mut Mmu) {}
pub fn opx53(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.d, cpu.regs.e)
}
pub fn opx54(cpu: &mut Cpu, mmu: &mut Mmu) {}
pub fn opx55(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.d, cpu.regs.l)
}
pub fn opx56(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = mmu.read(cpu.regs.hl() as usize);
ld_x_y(&mut cpu.regs.d, v)
}
pub fn opx57(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.d, cpu.regs.a)
}
pub fn opx58(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.e, cpu.regs.b)
}
pub fn opx59(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.e, cpu.regs.c)
}
pub fn opx5A(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.e, cpu.regs.d)
}
pub fn opx5B(cpu: &mut Cpu, mmu: &mut Mmu) {}
pub fn opx5C(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.e, cpu.regs.h)
}
pub fn opx5D(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.e, cpu.regs.l)
}
pub fn opx5E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = mmu.read(cpu.regs.hl() as usize);
ld_x_y(&mut cpu.regs.e, v)
}
pub fn opx5F(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.e, cpu.regs.a)
}
pub fn opx60(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.h, cpu.regs.b)
}
pub fn opx61(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.h, cpu.regs.c)
}
pub fn opx62(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.h, cpu.regs.d)
}
pub fn opx63(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.h, cpu.regs.e)
}
pub fn opx64(cpu: &mut Cpu, mmu: &mut Mmu) {}
pub fn opx65(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.h, cpu.regs.l)
}
pub fn opx66(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = mmu.read(cpu.regs.hl() as usize);
ld_x_y(&mut cpu.regs.h, v)
}
pub fn opx67(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.h, cpu.regs.a)
}
pub fn opx68(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.l, cpu.regs.b)
}
pub fn opx69(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.l, cpu.regs.c)
}
pub fn opx6A(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.l, cpu.regs.d)
}
pub fn opx6B(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.l, cpu.regs.e)
}
pub fn opx6C(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.l, cpu.regs.h)
}
pub fn opx6D(cpu: &mut Cpu, mmu: &mut Mmu) {}
pub fn opx6E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = mmu.read(cpu.regs.hl() as usize);
ld_x_y(&mut cpu.regs.l, v)
}
pub fn opx6F(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.l, cpu.regs.a)
}
pub fn opx70(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = cpu.regs.b;
mmu.write(cpu.regs.hl() as usize, r)
}
pub fn opx71(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = cpu.regs.c;
mmu.write(cpu.regs.hl() as usize, r)
}
pub fn opx72(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = cpu.regs.d;
mmu.write(cpu.regs.hl() as usize, r)
}
pub fn opx73(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = cpu.regs.e;
mmu.write(cpu.regs.hl() as usize, r)
}
pub fn opx74(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = cpu.regs.h;
mmu.write(cpu.regs.hl() as usize, r)
}
pub fn opx75(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = cpu.regs.l;
mmu.write(cpu.regs.hl() as usize, r)
}
pub fn opx77(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = cpu.regs.a;
mmu.write(cpu.regs.hl() as usize, r)
}
pub fn opx78(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.a, cpu.regs.b)
}
pub fn opx79(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.a, cpu.regs.c)
}
pub fn opx7A(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.a, cpu.regs.d)
}
pub fn opx7B(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.a, cpu.regs.e)
}
pub fn opx7C(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.a, cpu.regs.h)
}
pub fn opx7D(cpu: &mut Cpu, mmu: &mut Mmu) {
ld_x_y(&mut cpu.regs.a, cpu.regs.l)
}
pub fn opx7E(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = mmu.read(cpu.regs.hl() as usize);
ld_x_y(&mut cpu.regs.a, v)
}
pub fn opx7F(cpu: &mut Cpu, mmu: &mut Mmu) {}
pub fn opx80(cpu: &mut Cpu, mmu: &mut Mmu) {
add_a_x(cpu.regs.b, cpu)
}
pub fn opx81(cpu: &mut Cpu, mmu: &mut Mmu) {
add_a_x(cpu.regs.c, cpu)
}
pub fn opx82(cpu: &mut Cpu, mmu: &mut Mmu) {
add_a_x(cpu.regs.d, cpu)
}
pub fn opx83(cpu: &mut Cpu, mmu: &mut Mmu) {
add_a_x(cpu.regs.e, cpu)
}
pub fn opx84(cpu: &mut Cpu, mmu: &mut Mmu) {
add_a_x(cpu.regs.h, cpu)
}
pub fn opx85(cpu: &mut Cpu, mmu: &mut Mmu) {
add_a_x(cpu.regs.l, cpu)
}
pub fn opx86(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = mmu.read(cpu.regs.hl() as usize);
add_a_x(v, cpu)
}
pub fn opx87(cpu: &mut Cpu, mmu: &mut Mmu) {
add_a_x(cpu.regs.a, cpu)
}
pub fn add_a_x(val: u8, cpu: &mut Cpu) {
let c = add_c_u8(cpu.regs.a, val);
let hc = add_hc_u8(cpu.regs.a, val);
cpu.regs.flags.h = hc;
cpu.regs.a = cpu.regs.a.wrapping_add(val);
cpu.regs.flags.z = val == val;
cpu.regs.flags.c = c;
cpu.regs.flags.n = false;
}
pub fn opx90(cpu: &mut Cpu, mmu: &mut Mmu) {
sub_a_x(cpu.regs.b, cpu)
}
pub fn opx91(cpu: &mut Cpu, mmu: &mut Mmu) {
sub_a_x(cpu.regs.c, cpu)
}
pub fn opx92(cpu: &mut Cpu, mmu: &mut Mmu) {
sub_a_x(cpu.regs.d, cpu)
}
pub fn opx93(cpu: &mut Cpu, mmu: &mut Mmu) {
sub_a_x(cpu.regs.e, cpu)
}
pub fn opx94(cpu: &mut Cpu, mmu: &mut Mmu) {
sub_a_x(cpu.regs.h, cpu)
}
pub fn opx95(cpu: &mut Cpu, mmu: &mut Mmu) {
sub_a_x(cpu.regs.l, cpu)
}
pub fn opx97(cpu: &mut Cpu, mmu: &mut Mmu) {
sub_a_x(cpu.regs.a, cpu)
}
fn cp_x(val: u8, cpu: &mut Cpu) {
let a = cpu.regs.a;
let hc = sub_hc_u8(a, val);
cpu.regs.flags.z = a == val;
cpu.regs.flags.c = a < val;
cpu.regs.flags.n = true;
cpu.regs.flags.h = hc;
}
pub fn opxB8(cpu: &mut Cpu, mmu: &mut Mmu) {
cp_x(cpu.regs.b, cpu)
}
pub fn opxB9(cpu: &mut Cpu, mmu: &mut Mmu) {
cp_x(cpu.regs.c, cpu)
}
pub fn opxBA(cpu: &mut Cpu, mmu: &mut Mmu) {
cp_x(cpu.regs.d, cpu)
}
pub fn opxBB(cpu: &mut Cpu, mmu: &mut Mmu) {
cp_x(cpu.regs.e, cpu)
}
pub fn opxBC(cpu: &mut Cpu, mmu: &mut Mmu) {
cp_x(cpu.regs.h, cpu)
}
pub fn opxBD(cpu: &mut Cpu, mmu: &mut Mmu) {
cp_x(cpu.regs.l, cpu)
}
pub fn opxBF(cpu: &mut Cpu, mmu: &mut Mmu) {
cp_x(cpu.regs.a, cpu)
}
pub fn opxBE(cpu: &mut Cpu, mmu: &mut Mmu) {
let a = cpu.regs.hl() as usize;
cp_x(mmu.read(a), cpu)
}
pub fn opx2A(cpu: &mut Cpu, mmu: &mut Mmu) {
let addr = cpu.regs.hl();
let hl = mmu.read(addr as usize);
ld_x_y(&mut cpu.regs.a, hl);
cpu.regs.set_hl(addr.wrapping_add(1));
}
pub fn opx3A(cpu: &mut Cpu, mmu: &mut Mmu) {
let addr = cpu.regs.hl();
let hl = mmu.read(addr as usize);
ld_x_y(&mut cpu.regs.a, hl);
cpu.regs.set_hl(addr.wrapping_sub(1));
}
pub fn opx12(cpu: &mut Cpu, mmu: &mut Mmu) {
let addr = cpu.regs.de() as usize;
mmu.write(addr, cpu.regs.a);
}
pub fn opx36(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD (HL), d8
// Load d8 into the address specified at HL
let addr = cpu.regs.hl() as usize;
let d8 = cpu.immediate_u8_pc(mmu);
mmu.write(addr, d8);
}
pub fn or_x(val: u8, cpu: &mut Cpu) {
cpu.regs.a = cpu.regs.a | val;
cpu.regs.flags.z = cpu.regs.a == 0;
cpu.regs.flags.n = false;
cpu.regs.flags.h = false;
cpu.regs.flags.c = false;
}
pub fn opxB0(cpu: &mut Cpu, mmu: &mut Mmu) {
or_x(cpu.regs.b, cpu)
}
pub fn opxB1(cpu: &mut Cpu, mmu: &mut Mmu) {
or_x(cpu.regs.c, cpu)
}
pub fn opxB2(cpu: &mut Cpu, mmu: &mut Mmu) {
or_x(cpu.regs.d, cpu)
}
pub fn opxB3(cpu: &mut Cpu, mmu: &mut Mmu) {
or_x(cpu.regs.e, cpu)
}
pub fn opxB4(cpu: &mut Cpu, mmu: &mut Mmu) {
or_x(cpu.regs.h, cpu)
}
pub fn opxB5(cpu: &mut Cpu, mmu: &mut Mmu) {
or_x(cpu.regs.l, cpu)
}
pub fn opxB6(cpu: &mut Cpu, mmu: &mut Mmu) {
let hl = cpu.regs.hl() as usize;
or_x(mmu.read(hl), cpu)
}
pub fn opxB7(cpu: &mut Cpu, mmu: &mut Mmu) {
or_x(cpu.regs.a, cpu)
}
pub fn opx2F(cpu: &mut Cpu, mmu: &mut Mmu) {
// CPL - Complement A (flip all bits)
let a = cpu.regs.a;
cpu.regs.a = !a;
cpu.regs.flags.n = true;
cpu.regs.flags.h = true;
}
pub fn cbx30(cpu: &mut Cpu, mmu: &mut Mmu) {
swap(&mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx31(cpu: &mut Cpu, mmu: &mut Mmu) {
swap(&mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx32(cpu: &mut Cpu, mmu: &mut Mmu) {
swap(&mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx33(cpu: &mut Cpu, mmu: &mut Mmu) {
swap(&mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx34(cpu: &mut Cpu, mmu: &mut Mmu) {
swap(&mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx35(cpu: &mut Cpu, mmu: &mut Mmu) {
swap(&mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx37(cpu: &mut Cpu, mmu: &mut Mmu) {
swap(&mut cpu.regs.a, &mut cpu.regs.flags)
}
pub fn swap(reg: &mut u8, flags: &mut FlagRegister) {
*reg = (*reg << 4) | (*reg >> 4);
flags.z = *reg == 0;
flags.n = false;
flags.h = false;
flags.c = false;
}
pub fn opxA8(cpu: &mut Cpu, mmu: &mut Mmu) {
xor_a(cpu.regs.b, cpu)
}
pub fn opxA9(cpu: &mut Cpu, mmu: &mut Mmu) {
xor_a(cpu.regs.c, cpu)
}
pub fn opxAA(cpu: &mut Cpu, mmu: &mut Mmu) {
xor_a(cpu.regs.d, cpu)
}
pub fn opxAB(cpu: &mut Cpu, mmu: &mut Mmu) {
xor_a(cpu.regs.e, cpu)
}
pub fn opxAC(cpu: &mut Cpu, mmu: &mut Mmu) {
xor_a(cpu.regs.h, cpu)
}
pub fn opxAD(cpu: &mut Cpu, mmu: &mut Mmu) {
xor_a(cpu.regs.l, cpu)
}
pub fn opxAE(cpu: &mut Cpu, mmu: &mut Mmu) {
let x = mmu.read(cpu.regs.hl() as usize);
xor_a(x, cpu)
}
pub fn opxAF(cpu: &mut Cpu, mmu: &mut Mmu) {
xor_a(cpu.regs.a, cpu)
}
pub fn xor_a(val: u8, cpu: &mut Cpu) {
cpu.regs.a ^= val;
cpu.regs.flags.z = cpu.regs.a == 0;
cpu.regs.flags.n = false;
cpu.regs.flags.h = false;
cpu.regs.flags.c = false;
}
pub fn opxEE(cpu: &mut Cpu, mmu: &mut Mmu) {
let d = cpu.immediate_u8_pc(mmu);
xor_a(d, cpu)
}
pub fn opxA0(cpu: &mut Cpu, mmu: &mut Mmu) {
and_x(cpu.regs.b, cpu)
}
pub fn opxA1(cpu: &mut Cpu, mmu: &mut Mmu) {
and_x(cpu.regs.c, cpu)
}
pub fn opxA2(cpu: &mut Cpu, mmu: &mut Mmu) {
and_x(cpu.regs.d, cpu)
}
pub fn opxA3(cpu: &mut Cpu, mmu: &mut Mmu) {
and_x(cpu.regs.e, cpu)
}
pub fn opxA4(cpu: &mut Cpu, mmu: &mut Mmu) {
and_x(cpu.regs.h, cpu)
}
pub fn opxA5(cpu: &mut Cpu, mmu: &mut Mmu) {
and_x(cpu.regs.l, cpu)
}
pub fn opxA6(cpu: &mut Cpu, mmu: &mut Mmu) {
let x = mmu.read(cpu.regs.hl() as usize);
and_x(x, cpu)
}
pub fn opxA7(cpu: &mut Cpu, mmu: &mut Mmu) {
and_x(cpu.regs.a, cpu)
}
pub fn and_x(val: u8, cpu: &mut Cpu) {
cpu.regs.a &= val;
cpu.regs.flags.z = cpu.regs.a == 0;
cpu.regs.flags.n = false;
cpu.regs.flags.h = true;
cpu.regs.flags.c = false;
}
pub fn opxC7(cpu: &mut Cpu, mmu: &mut Mmu) {
restart(cpu, mmu, 0x00)
}
pub fn opxCF(cpu: &mut Cpu, mmu: &mut Mmu) {
restart(cpu, mmu, 0x08)
}
pub fn opxDF(cpu: &mut Cpu, mmu: &mut Mmu) {
restart(cpu, mmu, 0x18)
}
pub fn opxEF(cpu: &mut Cpu, mmu: &mut Mmu) {
restart(cpu, mmu, 0x28)
}
pub fn opxFF(cpu: &mut Cpu, mmu: &mut Mmu) {
restart(cpu, mmu, 0x38)
}
pub fn restart(cpu: &mut Cpu, mmu: &mut Mmu, addr: usize) {
let pc = cpu.regs.pc as u16;
cpu.stack_push_u16(pc, mmu);
cpu.regs.pc = addr;
}
pub fn opxC1(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.stack_pop_u16(mmu);
cpu.regs.set_bc(v)
}
pub fn opxD1(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.stack_pop_u16(mmu);
cpu.regs.set_de(v)
}
pub fn opxE1(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.stack_pop_u16(mmu);
cpu.regs.set_hl(v)
}
pub fn opxF1(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.stack_pop_u16(mmu);
cpu.regs.set_af(v)
}
pub fn add_hl(cpu: &mut Cpu, val: u16) {
let hl = cpu.regs.hl();
let hc = add_hc_u16(hl, val);
let c = add_c_u16(hl, val);
cpu.regs.set_hl(hl.wrapping_add(val));
cpu.regs.flags.n = false;
cpu.regs.flags.h = hc;
cpu.regs.flags.c = c;
}
pub fn opx19(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.regs.de();
add_hl(cpu, v)
}
pub fn opx29(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.regs.hl();
add_hl(cpu, v)
}
pub fn opx39(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.regs.sp as u16;
add_hl(cpu, v)
}
fn push_r16(cpu: &mut Cpu, mmu: &mut Mmu, val: u16) {
cpu.stack_push_u16(val, mmu);
}
pub fn opxC5(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.regs.bc();
push_r16(cpu, mmu, v)
}
pub fn opxD5(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.regs.de();
push_r16(cpu, mmu, v)
}
pub fn opxE5(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.regs.hl();
push_r16(cpu, mmu, v)
}
pub fn opxF5(cpu: &mut Cpu, mmu: &mut Mmu) {
let v = cpu.regs.af();
push_r16(cpu, mmu, v)
}
pub fn add_hc_u16(a: u16, b: u16) -> bool {
(((a & 0xFF) + (b & 0xFF)) > 0xFF)
}
pub fn add_hc_u8(a: u8, b: u8) -> bool {
(((a & 0xF) + (b & 0xF)) > 0xF)
}
pub fn add_c_u16(a: u16, b: u16) -> bool {
let biga: u32 = a as u32;
let bigb: u32 = b as u32;
(biga + bigb) > 0xFFFF
}
pub fn add_c_u8(a: u8, b: u8) -> bool {
let biga: u16 = a as u16;
let bigb: u16 = b as u16;
(biga + bigb) > 0xFF
}
fn sub_hc_u8(a: u8, b: u8) -> bool {
(b & 0xF) < (b & 0xF)
}
// fn sub_hc_u16(a: u16, b: u16) -> bool {
// (b & 0xFF) < (b & 0xFF)
// }
fn sub_c_u8(a: u8, b: u8) -> bool {
a < b
}
pub fn opxF9(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD SP, HL
let hl = cpu.regs.hl();
cpu.regs.sp = hl as usize;
}
pub fn opxFA(cpu: &mut Cpu, mmu: &mut Mmu) {
// LD A, (a16)
let addr = cpu.immediate_u16_pc(mmu) as usize;
cpu.regs.a = mmu.read(addr);
}
pub fn opxCA(cpu: &mut Cpu, mmu: &mut Mmu) {
// JP Z, a16
let addr = cpu.immediate_u16_pc(mmu) as usize;
if cpu.regs.flags.z {
cpu.regs.pc = addr;
}
}
pub fn opxDA(cpu: &mut Cpu, mmu: &mut Mmu) {
// JP C, a16
let addr = cpu.immediate_u16_pc(mmu) as usize;
if cpu.regs.flags.c {
cpu.regs.pc = addr;
}
}
pub fn opxC8(cpu: &mut Cpu, mmu: &mut Mmu) {
// RET Z
if cpu.regs.flags.z {
cpu.regs.pc = cpu.stack_pop_u16(mmu) as usize;
}
}
pub fn opxD8(cpu: &mut Cpu, mmu: &mut Mmu) {
// RET C
if cpu.regs.flags.c {
cpu.regs.pc = cpu.stack_pop_u16(mmu) as usize;
}
}
pub fn opxD9(cpu: &mut Cpu, mmu: &mut Mmu) {
// RETI - return from interrupt
cpu.regs.pc = cpu.stack_pop_u16(mmu) as usize;
mmu.ime = true;
}
pub fn opxC4(cpu: &mut Cpu, mmu: &mut Mmu) {
let addr = cpu.immediate_u16_pc(mmu) as usize;
let pc = cpu.regs.pc as u16;
cpu.stack_push_u16(pc, mmu);
if cpu.regs.flags.z == false {
cpu.regs.pc = addr;
}
}
pub fn srl(reg: &mut u8, flags: &mut FlagRegister) {
let val = *reg;
*reg = *reg >> 1;
flags.z = *reg == 0;
flags.c = val & 1 != 0;
flags.n = false;
flags.h = false;
}
pub fn cbx38(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
srl(&mut cpu.regs.b, f)
}
pub fn cbx39(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
srl(&mut cpu.regs.c, f)
}
pub fn cbx3A(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
srl(&mut cpu.regs.d, f)
}
pub fn cbx3B(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
srl(&mut cpu.regs.e, f)
}
pub fn cbx3C(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
srl(&mut cpu.regs.h, f)
}
pub fn cbx3D(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
srl(&mut cpu.regs.l, f)
}
pub fn cbx3F(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
srl(&mut cpu.regs.a, f)
}
pub fn cbx80(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.b, 0)
}
pub fn cbx81(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.c, 0)
}
pub fn cbx82(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.d, 0)
}
pub fn cbx83(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.e, 0)
}
pub fn cbx84(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.h, 0)
}
pub fn cbx85(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.l, 0)
}
pub fn cbx86(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = &mut mmu.read(cpu.regs.hl() as usize);
cb_res(r, 0)
}
pub fn cbx87(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.a, 0);
}
pub fn cbx88(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.b, 1)
}
pub fn cbx89(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.c, 1)
}
pub fn cbx8A(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.d, 1)
}
pub fn cbx8B(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.e, 1)
}
pub fn cbx8C(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.h, 1)
}
pub fn cbx8D(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.l, 1)
}
pub fn cbx8E(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = &mut mmu.read(cpu.regs.hl() as usize);
cb_res(r, 1)
}
pub fn cbx8F(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.a, 1)
}
pub fn cbx90(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.b, 2)
}
pub fn cbx91(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.c, 2)
}
pub fn cbx92(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.d, 2)
}
pub fn cbx93(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.e, 2)
}
pub fn cbx94(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.h, 2)
}
pub fn cbx95(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.l, 2)
}
pub fn cbx96(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = &mut mmu.read(cpu.regs.hl() as usize);
cb_res(r, 2)
}
pub fn cbx97(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.a, 2)
}
pub fn cbx98(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.b, 3)
}
pub fn cbx99(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.c, 3)
}
pub fn cbx9A(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.d, 3)
}
pub fn cbx9B(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.e, 3)
}
pub fn cbx9C(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.h, 3)
}
pub fn cbx9D(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.l, 3)
}
pub fn cbx9E(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = &mut mmu.read(cpu.regs.hl() as usize);
cb_res(r, 3)
}
pub fn cbx9F(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.a, 3)
}
pub fn cbxA0(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.b, 4)
}
pub fn cbxA1(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.c, 4)
}
pub fn cbxA2(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.d, 4)
}
pub fn cbxA3(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.e, 4)
}
pub fn cbxA4(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.h, 4)
}
pub fn cbxA5(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.l, 4)
}
pub fn cbxA6(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = &mut mmu.read(cpu.regs.hl() as usize);
cb_res(r, 4)
}
pub fn cbxA7(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.a, 4)
}
pub fn cbxA8(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.b, 5)
}
pub fn cbxA9(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.c, 5)
}
pub fn cbxAA(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.d, 5)
}
pub fn cbxAB(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.e, 5)
}
pub fn cbxAC(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.h, 5)
}
pub fn cbxAD(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.l, 5)
}
pub fn cbxAE(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = &mut mmu.read(cpu.regs.hl() as usize);
cb_res(r, 5)
}
pub fn cbxAF(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.a, 5)
}
pub fn cbxB0(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.b, 6)
}
pub fn cbxB1(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.c, 6)
}
pub fn cbxB2(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.d, 6)
}
pub fn cbxB3(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.e, 6)
}
pub fn cbxB4(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.h, 6)
}
pub fn cbxB5(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.l, 6)
}
pub fn cbxB6(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = &mut mmu.read(cpu.regs.hl() as usize);
cb_res(r, 6)
}
pub fn cbxB7(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.a, 6)
}
pub fn cbxB8(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.b, 7)
}
pub fn cbxB9(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.c, 7)
}
pub fn cbxBA(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.d, 7)
}
pub fn cbxBB(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.e, 7)
}
pub fn cbxBC(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.h, 7)
}
pub fn cbxBD(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.l, 7)
}
pub fn cbxBE(cpu: &mut Cpu, mmu: &mut Mmu) {
let r = &mut mmu.read(cpu.regs.hl() as usize);
cb_res(r, 7)
}
pub fn cbxBF(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_res(&mut cpu.regs.a, 7)
}
fn cb_res(reg: &mut u8, bit: usize) {
*reg &= !(1 << bit);
}
pub fn cbx18(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
cb_rr(&mut cpu.regs.b, f)
}
pub fn cbx19(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
cb_rr(&mut cpu.regs.c, f)
}
pub fn cbx1A(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
cb_rr(&mut cpu.regs.d, f)
}
pub fn cbx1B(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
cb_rr(&mut cpu.regs.e, f)
}
pub fn cbx1C(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
cb_rr(&mut cpu.regs.h, f)
}
pub fn cbx1D(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
cb_rr(&mut cpu.regs.l, f)
}
pub fn cbx1E(cpu: &mut Cpu, mmu: &mut Mmu) {
let h = cpu.regs.hl() as usize;
let f = &mut cpu.regs.flags;
cb_rr(&mut mmu.read(h), f)
}
pub fn cbx1F(cpu: &mut Cpu, mmu: &mut Mmu) {
let f = &mut cpu.regs.flags;
cb_rr(&mut cpu.regs.a, f)
}
fn cb_rr(x: &mut u8, flags: &mut FlagRegister) {
let r = *x;
let c = r & 1;
*x = (r >> 1) | ((flags.c as u8) << 7);
flags.c = c == 1;
flags.z = *x == 0;
flags.h = false;
flags.n = false;
}
pub fn cbx20(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_sla(&mut cpu.regs.b, &mut cpu.regs.flags)
}
pub fn cbx21(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_sla(&mut cpu.regs.c, &mut cpu.regs.flags)
}
pub fn cbx22(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_sla(&mut cpu.regs.d, &mut cpu.regs.flags)
}
pub fn cbx23(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_sla(&mut cpu.regs.e, &mut cpu.regs.flags)
}
pub fn cbx24(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_sla(&mut cpu.regs.h, &mut cpu.regs.flags)
}
pub fn cbx25(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_sla(&mut cpu.regs.l, &mut cpu.regs.flags)
}
pub fn cbx27(cpu: &mut Cpu, mmu: &mut Mmu) {
cb_sla(&mut cpu.regs.a, &mut cpu.regs.flags)
}
fn cb_sla(reg: &mut u8, flags: &mut FlagRegister) {
let val = *reg << 1;
let c = *reg >> 7;
*reg = val;
flags.c = c == 1;
flags.n = false;
flags.h = false;
flags.z = val == 0;
}
pub fn opx1F(cpu: &mut Cpu, mmu: &mut Mmu) {
let carry = cpu.regs.a & 0b1;
cpu.regs.a = cpu.regs.a >> 1;
cpu.regs.a = cpu.regs.a | ((cpu.regs.flags.c as u8) << 7);
cpu.regs.flags.c = carry == 1;
}
pub fn opx88(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.b;
op_adc(val, cpu)
}
pub fn opx89(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.c;
op_adc(val, cpu)
}
pub fn opx8A(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.d;
op_adc(val, cpu)
}
pub fn opx8B(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.e;
op_adc(val, cpu)
}
pub fn opx8C(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.h;
op_adc(val, cpu)
}
pub fn opx8D(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.l;
op_adc(val, cpu)
}
pub fn opx8E(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = mmu.read(cpu.regs.hl() as usize);
op_adc(val, cpu)
}
pub fn opx8F(cpu: &mut Cpu, mmu: &mut Mmu) {
let val = cpu.regs.a;
op_adc(val, cpu)
}
fn op_adc(val: u8, cpu: &mut Cpu) {
let c = cpu.regs.flags.c as u8;
let a = cpu.regs.a;
let hc = add_hc_u8(a, val + c);
let car = add_c_u8(a, val + c);
cpu.regs.a = cpu.regs.a.wrapping_add(c + val);
cpu.regs.flags.n = false;
cpu.regs.flags.z = cpu.regs.a == 0;
cpu.regs.flags.c = car;
cpu.regs.flags.h = hc;
}
pub fn cbxF8(cpu: &mut Cpu, mmu: &mut Mmu) {
set_bit(&mut cpu.regs.b, 7)
}
pub fn cbxF9(cpu: &mut Cpu, mmu: &mut Mmu) {
set_bit(&mut cpu.regs.c, 7)
}
pub fn cbxFA(cpu: &mut Cpu, mmu: &mut Mmu) {
set_bit(&mut cpu.regs.d, 7)
}
pub fn cbxFB(cpu: &mut Cpu, mmu: &mut Mmu) {
set_bit(&mut cpu.regs.e, 7)
}
pub fn cbxFC(cpu: &mut Cpu, mmu: &mut Mmu) {
set_bit(&mut cpu.regs.h, 7)
}
pub fn cbxFD(cpu: &mut Cpu, mmu: &mut Mmu) {
set_bit(&mut cpu.regs.l, 7)
}
pub fn cbxFE(cpu: &mut Cpu, mmu: &mut Mmu) {
let mut set = mmu.read(cpu.regs.hl() as usize);
set.set_bit(7, 1);
mmu.write(cpu.regs.hl() as usize, set);
}
pub fn cbxFF(cpu: &mut Cpu, mmu: &mut Mmu) {
set_bit(&mut cpu.regs.a, 7)
}
fn set_bit(reg: &mut u8, bitno: u8) {
*reg |= 1 << bitno;
}
| true |
44098a3c7355910bf4d420e1b84bd7a6a31ac60e
|
Rust
|
dprentiss/caddis
|
/caddis/src/geometry.rs
|
UTF-8
| 10,922 | 2.59375 | 3 |
[] |
no_license
|
use std::ops::{
Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign,
};
use std::f64;
use std::f64::consts;
use num_traits::identities::{One, Zero};
pub use alga::linear::{
AffineSpace, EuclideanSpace, FiniteDimInnerSpace, FiniteDimVectorSpace, InnerSpace,
NormedSpace, VectorSpace,
};
use alga::general::AbstractGroup;
use alga::general::AbstractGroupAbelian;
use alga::general::AbstractLoop;
use alga::general::AbstractMagma;
use alga::general::AbstractModule;
use alga::general::AbstractMonoid;
use alga::general::AbstractQuasigroup;
use alga::general::AbstractSemigroup;
use alga::general::Additive;
use alga::general::Identity;
use alga::general::Module;
use alga::general::TwoSidedInverse;
use rgsl::linear_algebra::SV_decomp;
use rgsl::types::matrix::MatrixF64;
use rgsl::types::vector::VectorF64;
type VectorType = VectorF64;
#[derive(Debug)]
pub struct Vector(VectorType);
type Scalar = f64;
impl Vector {
const N: usize = 3;
fn project(&self, other: &Self) -> Self {
let mut v = other.0.clone().unwrap();
v.scale(self.dot(other) / other.dot(other));
Vector(v)
}
pub fn from_slice(s: &[Scalar]) -> Self {
Vector(VectorType::from_slice(s).unwrap())
}
pub fn new() -> Self {
Vector(VectorType::new(Self::N).unwrap())
}
}
impl Clone for Vector {
fn clone(&self) -> Self {
Self(self.0.clone().unwrap())
}
}
impl PartialEq for Vector {
fn eq(&self, other: &Self) -> bool {
self.0.equal(&other.0)
}
}
impl Add for Vector {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
let mut v = VectorF64::from_slice(self.0.as_slice().unwrap()).unwrap();
v.add(&other.0);
Self(v)
}
}
impl Sub for Vector {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
let mut v = VectorF64::from_slice(self.0.as_slice().unwrap()).unwrap();
v.sub(&other.0);
Self(v)
}
}
impl Mul<<Vector as EuclideanSpace>::RealField> for Vector {
type Output = Self;
fn mul(self, s: Scalar) -> Self::Output {
let mut v = VectorF64::from_slice(self.0.as_slice().unwrap()).unwrap();
v.scale(s);
Self(v)
}
}
impl Div<<Vector as EuclideanSpace>::RealField> for Vector {
type Output = Self;
fn div(self, s: Scalar) -> Self::Output {
let mut v = VectorF64::from_slice(self.0.as_slice().unwrap()).unwrap();
v.scale(s.recip());
Self(v)
}
}
impl Neg for Vector {
type Output = Self;
fn neg(self) -> Self::Output {
let mut v = VectorF64::from_slice(self.0.as_slice().unwrap()).unwrap();
v.scale(-1.0);
Vector(v)
}
}
impl AddAssign for Vector {
fn add_assign(&mut self, other: Self) {
self.0.add(&other.0);
}
}
impl SubAssign for Vector {
fn sub_assign(&mut self, other: Self) {
self.0.sub(&other.0);
}
}
impl MulAssign<<Vector as EuclideanSpace>::RealField> for Vector {
fn mul_assign(&mut self, s: Scalar) {
self.0.scale(s);
}
}
impl DivAssign<<Vector as EuclideanSpace>::RealField> for Vector {
fn div_assign(&mut self, s: Scalar) {
self.0.scale(s.recip());
}
}
impl EuclideanSpace for Vector {
type Coordinates = Vector;
type RealField = Scalar;
fn origin() -> Self {
Vector::new()
}
}
impl AffineSpace for Vector {
type Translation = <Self as EuclideanSpace>::Coordinates;
}
impl VectorSpace for Vector {
type Field = <Self as EuclideanSpace>::RealField;
}
impl Module for Vector {
type Ring = <Self as VectorSpace>::Field;
}
impl AbstractModule for Vector {
type AbstractRing = <Self as Module>::Ring;
fn multiply_by(&self, ring: Self::AbstractRing) -> Self {
let mut v = self.0.clone().unwrap();
v.scale(ring);
Vector(v)
}
}
impl AbstractGroupAbelian<Additive> for Vector {}
impl AbstractGroup<Additive> for Vector {}
impl AbstractLoop<Additive> for Vector {}
impl AbstractQuasigroup<Additive> for Vector {}
impl AbstractMagma<Additive> for Vector {
fn operate(&self, other: &Self) -> Self {
let mut v = self.0.clone().unwrap();
v.add(&other.0);
Vector(v)
}
}
impl TwoSidedInverse<Additive> for Vector {
fn two_sided_inverse(&self) -> Self {
-Vector(self.0.clone().unwrap())
}
}
impl Identity<Additive> for Vector {
fn identity() -> Self {
Vector(VectorType::new(Self::dimension()).unwrap())
}
}
impl AbstractMonoid<Additive> for Vector {}
impl AbstractSemigroup<Additive> for Vector {}
impl Zero for Vector {
fn zero() -> Self {
Self::new()
}
fn is_zero(&self) -> bool {
*self == Self::zero()
}
}
impl FiniteDimInnerSpace for Vector {
fn orthonormalize(vs: &mut [Self]) -> usize {
let len = vs.len();
let mut chosen = 0usize;
let mut discarded = 0usize;
//println!("{}, {}, {}, {:?}", len, chosen, discarded, vs);
while chosen < Self::dimension() && chosen + discarded < len {
//println!("{}, {}, {}, {:?}", len, chosen, discarded, vs);
for i in chosen..(len - discarded) {
//println!("{}, {}, {}, {:?}", len, chosen, discarded, vs);
if vs[i].is_zero() {
discarded += 1;
if chosen + discarded > 1 {
vs.swap(i, len - discarded);
}
break;
} else {
for j in 0..chosen {
println!("{}, {}, {}, {}, {}, {:?}", len, chosen, discarded, i, j, vs);
vs[i] -= vs[i].project(&vs[j]);
println!("{}, {}, {}, {}, {}, {:?}", len, chosen, discarded, i, j, vs);
}
if vs[i].is_zero() {
discarded += 1;
if chosen + discarded > 1 {
vs.swap(i, len - discarded);
}
break;
} else {
chosen += 1;
vs[i].normalize_mut();
break;
}
}
}
//println!("{}, {}, {}, {:?}", len, chosen, discarded, vs);
}
//println!("{}, {}, {}, {:?}", len, chosen, discarded, vs);
chosen
}
/// Applies the given closure to each element of the orthonormal basis of
/// the subspace orthogonal to free family of vectors 'vs'. If vs is not a
/// free family, the result is unspecified.
fn orthonormal_subspace_basis<F: FnMut(&Self) -> bool>(vs: &[Self], _f: F) {
let mut a = MatrixF64::new(vs.len(), Self::dimension()).unwrap();
let mut r = 0;
for i in vs {
let mut v = VectorType::new(Self::dimension()).unwrap();
for j in 0..v.len() {
v.set(j, i[j]);
}
a.set_row(r, &mut v);
r += 1;
}
println!("a: {:?}", a);
let mut v = MatrixF64::new(Self::dimension(), Self::dimension()).unwrap();
let mut s = VectorType::new(Self::dimension()).unwrap();
let mut work = VectorType::new(Self::dimension()).unwrap();
SV_decomp(&mut a, &mut v, &mut s, &mut work);
println!("vs: {:?}", vs);
println!("a: {:?}", a);
println!("v: {:?}", v);
println!("s: {:?}", s);
}
}
impl InnerSpace for Vector {
fn inner_product(&self, other: &Self) -> Self::ComplexField {
let mut v = self.0.clone().unwrap();
let mut p = Scalar::zero();
v.mul(&other.0);
for i in v.as_slice().unwrap() {
p += i;
}
p
}
}
impl NormedSpace for Vector {
type RealField = <Self as EuclideanSpace>::RealField;
type ComplexField = Self::RealField;
fn norm_squared(&self) -> Self::RealField {
self.dot(&self)
}
fn norm(&self) -> Self::RealField {
self.dot(&self).sqrt()
}
fn normalize(&self) -> Self {
let v = Vector(self.0.clone().unwrap());
let n = v.norm();
v / n
}
fn normalize_mut(&mut self) -> Self::RealField {
let norm = self.norm();
*self /= norm;
norm
}
fn try_normalize(&self, eps: Self::RealField) -> Option<Self> {
let norm = self.norm();
if norm <= eps {
return None;
} else {
Some(self.normalize())
}
}
fn try_normalize_mut(&mut self, eps: Self::RealField) -> Option<Self::RealField> {
let norm = self.norm();
if norm <= eps {
return None;
} else {
Some(self.normalize_mut())
}
}
}
impl FiniteDimVectorSpace for Vector {
fn dimension() -> usize {
3usize
}
fn canonical_basis_element(i: usize) -> Self {
let mut v = VectorType::new(Vector::dimension()).unwrap();
v.set(i, Scalar::one());
Vector(v)
}
fn dot(&self, other: &Self) -> Self::Field {
self.inner_product(other)
}
unsafe fn component_unchecked(&self, i: usize) -> &Self::Field {
&self[i]
}
unsafe fn component_unchecked_mut(&mut self, i: usize) -> &mut Self::Field {
&mut self[i]
}
}
impl Index<usize> for Vector {
type Output = <Self as EuclideanSpace>::RealField;
fn index(&self, index: usize) -> &Self::Output {
&self.0.as_slice().unwrap()[index]
}
}
impl IndexMut<usize> for Vector {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0.as_slice_mut().unwrap()[index]
}
}
pub struct Sphere {
center: Option<Vector>,
#[allow(dead_code)]
nose: Option<Vector>,
radius: Option<Scalar>,
}
impl Sphere {
pub fn from_nose(center: &Vector, nose: &Vector) -> Self {
Sphere {
center: Some(center.clone()),
nose: Some(nose.clone()),
radius: Some(nose.norm()),
}
}
pub fn from_radius(center: &Vector, radius: Scalar) -> Self {
Sphere {
center: Some(center.clone()),
nose: None,
radius: Some(radius),
}
}
pub fn volume(&self) -> Scalar {
self.radius.unwrap().powi(3) * consts::FRAC_PI_3 * 4.0
}
pub fn area(&self) -> Scalar {
self.radius.unwrap().powi(2) * consts::PI * 4.0
}
pub fn contains(self, point: Vector) -> bool {
(point - self.center.unwrap()).norm() <= self.radius.unwrap()
}
pub fn height(self, point: Vector) -> Scalar {
(point - self.center.unwrap()).norm() - self.radius.unwrap()
}
}
#[allow(dead_code)]
struct Circle {
center: Vector,
normal: Vector,
radius: Scalar,
area: Scalar,
}
#[cfg(test)]
mod tests {
}
| true |
260d115edbd0b27b60bb77db9fc8b2eb5cbfcccc
|
Rust
|
gbersac/computorv1-42
|
/src/solver.rs
|
UTF-8
| 7,051 | 3.203125 | 3 |
[] |
no_license
|
use solution::Solution;
use parser::Parser;
use std::fmt::Write;
use std::cmp::Ordering;
use x_part::{XPart};
use nbr_complex::NbrComplex;
pub struct Solver
{
pub xs: Vec<XPart>,
pub discriminant: Option<f32>,
pub sol: Solution,
pub degree: f32,
}
impl Solver
{
pub fn new(equ_str: &str) -> Solver
{
let _xs = Parser::parse(&equ_str.to_string());
let mut solver = Solver{
xs: _xs,
discriminant: None,
sol: Solution::NoSolution,
degree: 0.,
};
solver.solve();
solver
}
fn analyze_xparts(&mut self) -> (f32, f32, f32)
{
let (mut a, mut b, mut c) = (0., 0., 0.);
for x in &self.xs {
match x.power {
0. => c = x.multiply,
1. => b = x.multiply,
2. => a = x.multiply,
_ => self.sol = Solution::NotComputable,
};
if self.degree < x.power{
self.degree = x. power;
}
}
(a, b, c)
}
#[allow(unused_variables)]
fn solve_degree_0(&mut self, a: f32, b: f32, c: f32)
{
if c != 0.{
self.sol = Solution::NoSolution
}else{
self.sol = Solution::Infinite
}
}
#[allow(unused_variables)]
fn solve_degree_1(&mut self, a: f32, b: f32, c: f32)
{
self.sol = Solution::Simple(-c / b);
}
fn solve_degree_2(&mut self, a: f32, b: f32, c: f32)
{
let discriminant = b * b - 4. * a * c;
self.discriminant = Some(discriminant);
match discriminant.partial_cmp(&0.).unwrap(){
Ordering::Equal => {
let x = -b / (2. * a);
self.sol = Solution::Simple(x);
},
Ordering::Greater => {
let x1 = (-b - discriminant.sqrt()) / (2. * a);
let x2 = (-b + discriminant.sqrt()) / (2. * a);
self.sol = Solution::Double(x1, x2);
},
Ordering::Less => {
let absolute = discriminant.abs().sqrt();
self.sol = Solution::Complex(
NbrComplex::new(-b, absolute, 2. * a),
NbrComplex::new(-b, -absolute, 2. * a),
);
},
}
}
pub fn solve(&mut self)
{
let (a, b, c) = self.analyze_xparts();
if self.degree == 0.{
self.solve_degree_0(a, b, c);
}else if self.degree == 1.{
self.solve_degree_1(a, b, c);
}else if self.degree == 2.{
self.solve_degree_2(a, b, c);
}
}
#[allow(unused_must_use)]
fn xpart_to_string(x: &XPart, is_first: bool) -> String
{
let mut to_return = String::new();
if !is_first{
write!(&mut to_return, " + ");
}
match x.power{
0. => {
write!(&mut to_return, "{}", x.multiply);
},
1. => {
write!(&mut to_return, "{} * X", x.multiply);
},
_ => {
write!(&mut to_return, "{} * X^{}", x. multiply, x.power);
},
}
to_return
}
fn print_discriminant(&self)
{
if self.discriminant.is_none(){
return ;
}
let discriminant = self.discriminant.unwrap();
match discriminant.partial_cmp(&0.).unwrap(){
Ordering::Equal => {
println!("Discriminant is equal to 0, the solution is:");
},
Ordering::Greater => {
println!("Discriminant is strictly positive, the two solutions are:");
},
Ordering::Less => {
println!("Discriminant is strictly negative, the two solutions are:");
},
}
}
/// Function to print a list of xparts as an equation equaling 0.
/// Return only for the tests
#[allow(unused_must_use)]
pub fn print(&self) -> String
{
let mut to_return = String::new();
let mut is_first = true;
for x in &self.xs{
if x.multiply != 0.{
to_return.push_str(&Solver::xpart_to_string(&x, is_first));
is_first = false;
}
}
if to_return.is_empty(){
write!(&mut to_return, "0");
}
println!("{} = 0", to_return);
println!("Polynomial degree: {}", self.degree);
self.print_discriminant();
println!("{}", self.sol);
to_return
}
}
#[cfg(test)]
mod test
{
use super::*;
use parser::Parser;
use nbr_complex::NbrComplex;
use solution::Solution;
fn cmp_solve(equation: &str, sol: Solution)
{
let solver = Solver::new(equation);
println!("{:?}", solver.xs);
println!("{:?} -> {:?} must be {:?}",
equation, solver.sol, sol);
assert!(solver.sol == sol);
}
#[test]
fn test_solve()
{
// degree 0
cmp_solve("42 * X^0 = 42 * X^0", Solution::Infinite);
cmp_solve("4 * X^0 = 8 * X^0", Solution::NoSolution);
// degree 1
cmp_solve("10 * X^0 = 4 * X^0 + 3 * X^1", Solution::Simple(2.));
cmp_solve("5 * X^0 + 4 * X^1 = 4 * X^0", Solution::Simple(-0.25));
cmp_solve("-5 * X^0 + 4 * X^1 = - 4 * X^0", Solution::Simple(0.25));
cmp_solve("-5 * X^0 + 4 * X^1 + 0 * X^2 = - 4 * X^0", Solution::Simple(0.25));
// degree 2
cmp_solve("6 + 1 * X^1 - 1 * X^2 = 0", Solution::Double(3., -2.));
cmp_solve("6 * X^0 + 11 * X^1 + 5 * X^2 = 1 * X^0 + 1 * X^1", Solution::Simple(-1.));
// cmp_solve("5 * X^0 + 13 * X^1 + 3 * X^2 = 1 * X^0 + 1 * X^1",
// Solution::Double(-3.632993, -0.367007));
cmp_solve("3 * X^0 + 6 * X^1 + 5 * X^2 = 1 * X^0",
Solution::Complex(
NbrComplex::new(-6., 2., 10.),
NbrComplex::new(-6., -2., 10.),
)
);
// degree 3
cmp_solve("8 * X^0 - 6 * X^1 + 0 * X^2 - 5.6 * X^3 = 3 * X^0",
Solution::NotComputable);
}
fn test_simple_formatting()
{
cmp_solve("6 + 11 * X + 5 * X^2 = 1 + 1 * X", Solution::Simple(-1.));
cmp_solve("6 + X^1 - X^2 = 0", Solution::Double(3., -2.));
cmp_solve("- X^2 + X^1 + 6 = 0", Solution::Double(3., -2.));
}
fn cmp_print(l: &str, r: &str)
{
let solver = Solver::new(l);
let s = solver.print();
println!("result: {}", s);
assert!(s == r);
}
#[test]
fn test_print()
{
cmp_print("5 * X^0 + 4 * X^1 - 9.3 * X^2 = 1 * X^0",
"4 + 4 * X + -9.3 * X^2");
cmp_print("5 * X^0 + 4 * X^1 = 4 * X^0",
"1 + 4 * X");
cmp_print("8 * X^0 - 6 * X^1 + 0 * X^2 - 5.6 * X^3 = 3 * X^0",
"5 + -6 * X + -5.6 * X^3");
}
}
| true |
05757c97a7d9462da64c3bc946adbbb8bd2b0bc4
|
Rust
|
x37v/puredata-rust
|
/external/src/atom.rs
|
UTF-8
| 4,866 | 2.59375 | 3 |
[] |
no_license
|
use crate::symbol::Symbol;
use std::convert::TryInto;
#[repr(transparent)]
pub struct Atom(pub pd_sys::t_atom);
impl Atom {
pub fn slice_from_raw_parts(
argv: *const pd_sys::t_atom,
argc: std::os::raw::c_int,
) -> &'static [Atom] {
unsafe {
let (argv, argc) = if argv.is_null() {
(std::ptr::null(), 0)
} else {
(
std::mem::transmute::<_, *const crate::atom::Atom>(argv),
if argc < 0 as std::os::raw::c_int {
0usize
} else {
argc as usize
},
)
};
std::slice::from_raw_parts(argv, argc)
}
}
pub fn get_type(&self) -> pd_sys::t_atomtype::Type {
self.0.a_type
}
pub fn is_type(&self, t: pd_sys::t_atomtype::Type) -> bool {
self.get_type() == t
}
pub fn as_ptr(&self) -> *const pd_sys::t_atom {
&self.0 as *const pd_sys::t_atom
}
pub fn get_symbol(&self) -> Option<Symbol> {
assert!(!self.as_ptr().is_null());
unsafe {
match self.0.a_type {
pd_sys::t_atomtype::A_DEFSYM | pd_sys::t_atomtype::A_SYMBOL => {
pd_sys::atom_getsymbol(self.as_ptr()).try_into().ok()
}
_ => None,
}
}
}
pub fn get_float(&self) -> Option<pd_sys::t_float> {
assert!(!self.as_ptr().is_null());
unsafe {
match self.0.a_type {
pd_sys::t_atomtype::A_DEFFLOAT | pd_sys::t_atomtype::A_FLOAT => {
Some(pd_sys::atom_getfloat(self.as_ptr()))
}
_ => None,
}
}
}
pub fn get_int(&self) -> Option<pd_sys::t_int> {
assert!(!self.as_ptr().is_null());
unsafe {
match self.0.a_type {
//pd does the cast
pd_sys::t_atomtype::A_DEFFLOAT | pd_sys::t_atomtype::A_FLOAT => {
Some(pd_sys::atom_getint(self.as_ptr()))
}
_ => None,
}
}
}
pub fn set_semi(&mut self) {
self.0.a_type = pd_sys::t_atomtype::A_SEMI;
self.0.a_w.w_index = 0;
}
pub fn set_comma(&mut self) {
self.0.a_type = pd_sys::t_atomtype::A_COMMA;
self.0.a_w.w_index = 0;
}
pub fn set_pointer(&mut self, v: &mut pd_sys::t_gpointer) {
self.0.a_type = pd_sys::t_atomtype::A_POINTER;
self.0.a_w.w_gpointer = v as *mut pd_sys::t_gpointer;
}
pub fn set_float(&mut self, v: pd_sys::t_float) {
self.0.a_type = pd_sys::t_atomtype::A_FLOAT;
self.0.a_w.w_float = v;
}
pub fn set_symbol(&mut self, v: Symbol) {
self.0.a_type = pd_sys::t_atomtype::A_SYMBOL;
self.0.a_w.w_symbol = v.inner();
}
pub fn set_dollar(&mut self, v: std::os::raw::c_int) {
self.0.a_type = pd_sys::t_atomtype::A_DOLLAR;
self.0.a_w.w_index = v;
}
pub fn set_dollarsym(&mut self, v: Symbol) {
self.0.a_type = pd_sys::t_atomtype::A_DOLLSYM;
self.0.a_w.w_symbol = v.inner();
}
}
impl Copy for Atom {}
impl Clone for Atom {
fn clone(&self) -> Self {
let a = pd_sys::_atom {
a_type: self.0.a_type,
a_w: self.0.a_w,
};
Self(a)
}
}
impl std::convert::From<usize> for Atom {
fn from(v: usize) -> Self {
let mut s = Self::default();
s.set_float(v as pd_sys::t_float);
s
}
}
impl std::convert::From<f64> for Atom {
fn from(v: f64) -> Self {
let mut s = Self::default();
s.set_float(v as pd_sys::t_float);
s
}
}
impl std::convert::From<f32> for Atom {
fn from(v: f32) -> Self {
let mut s = Self::default();
s.set_float(v as pd_sys::t_float);
s
}
}
impl std::convert::From<crate::symbol::Symbol> for Atom {
fn from(v: crate::symbol::Symbol) -> Self {
let mut s = Self::default();
s.set_symbol(v);
s
}
}
impl std::convert::TryInto<String> for Atom {
type Error = String;
fn try_into(self) -> Result<String, Self::Error> {
if let Some(s) = self.get_symbol() {
Ok(s.into())
} else if let Some(f) = self.get_float() {
Ok(f.to_string())
} else {
Err(format!(
"don't know how to convert {} to string",
self.0.a_type
))
}
}
}
impl Default for Atom {
fn default() -> Self {
let a = pd_sys::_atom {
a_type: pd_sys::t_atomtype::A_FLOAT,
a_w: {
pd_sys::word {
w_float: 0f32.into(),
}
},
};
Self(a)
}
}
| true |
506080ebb12a0146fc3c879bc55a830c9fc07ba4
|
Rust
|
weiwei-lin/fieldmask-rs
|
/fieldmask/tests/one_of.rs
|
UTF-8
| 3,901 | 3.0625 | 3 |
[] |
no_license
|
use std::convert::TryFrom;
use fieldmask::{FieldMask, FieldMaskInput, Maskable};
#[derive(Debug, PartialEq, Maskable)]
enum OneOf {
A(String),
B(String),
AnotherCase(String),
}
impl Default for OneOf {
fn default() -> Self {
Self::A(String::default())
}
}
#[derive(Debug, PartialEq, Maskable)]
struct Parent {
#[fieldmask(flatten)]
one_of: Option<OneOf>,
c: u32,
}
#[test]
fn one_of() {
let mut struct1 = Parent {
one_of: Some(OneOf::A("a".into())),
c: 1,
};
let struct2 = Parent {
one_of: Some(OneOf::B("b".into())),
c: 2,
};
let expected_struct = Parent {
one_of: Some(OneOf::B("b".into())),
c: 2,
};
FieldMask::try_from(FieldMaskInput(vec!["b", "c"].into_iter()))
.expect("unable to deserialize mask")
.apply(&mut struct1, struct2);
assert_eq!(struct1, expected_struct);
}
#[test]
fn different_variant() {
let mut struct1 = Parent {
one_of: Some(OneOf::A("a".into())),
c: 1,
};
let struct2 = Parent {
one_of: Some(OneOf::B("b".into())),
c: 2,
};
let expected_struct = Parent { one_of: None, c: 2 };
FieldMask::try_from(FieldMaskInput(vec!["a", "c"].into_iter()))
.expect("unable to deserialize mask")
.apply(&mut struct1, struct2);
assert_eq!(struct1, expected_struct);
}
#[test]
fn different_variant_both_in_mask() {
let mut struct1 = Parent {
one_of: Some(OneOf::A("a".into())),
c: 1,
};
let struct2 = Parent {
one_of: Some(OneOf::B("b".into())),
c: 2,
};
let expected_struct = Parent {
one_of: Some(OneOf::B("b".into())),
c: 2,
};
FieldMask::try_from(FieldMaskInput(vec!["a", "b", "c"].into_iter()))
.expect("unable to deserialize mask")
.apply(&mut struct1, struct2);
assert_eq!(struct1, expected_struct);
}
#[test]
fn no_field() {
let mut struct1 = Parent {
one_of: Some(OneOf::A("a".into())),
c: 1,
};
let struct2 = Parent {
one_of: Some(OneOf::A("a2".into())),
c: 2,
};
let expected_struct = Parent { one_of: None, c: 2 };
FieldMask::try_from(FieldMaskInput(vec!["b", "c"].into_iter()))
.expect("unable to deserialize mask")
.apply(&mut struct1, struct2);
assert_eq!(struct1, expected_struct);
}
#[test]
fn matched_field() {
let mut struct1 = Parent {
one_of: Some(OneOf::A("a".into())),
c: 1,
};
let struct2 = Parent {
one_of: Some(OneOf::A("a2".into())),
c: 2,
};
let expected_struct = Parent {
one_of: Some(OneOf::A("a2".into())),
c: 2,
};
FieldMask::try_from(FieldMaskInput(vec!["a", "c"].into_iter()))
.expect("unable to deserialize mask")
.apply(&mut struct1, struct2);
assert_eq!(struct1, expected_struct);
}
#[test]
fn self_none() {
let mut struct1 = Parent { one_of: None, c: 1 };
let struct2 = Parent {
one_of: Some(OneOf::A("a2".into())),
c: 2,
};
let expected_struct = Parent {
one_of: Some(OneOf::A("a2".into())),
c: 2,
};
FieldMask::try_from(FieldMaskInput(vec!["a", "c"].into_iter()))
.expect("unable to deserialize mask")
.apply(&mut struct1, struct2);
assert_eq!(struct1, expected_struct);
}
#[test]
fn snake_case() {
let mut struct1 = Parent { one_of: None, c: 1 };
let struct2 = Parent {
one_of: Some(OneOf::AnotherCase("a2".into())),
c: 2,
};
let expected_struct = Parent {
one_of: Some(OneOf::AnotherCase("a2".into())),
c: 2,
};
FieldMask::try_from(FieldMaskInput(vec!["another_case", "c"].into_iter()))
.expect("unable to deserialize mask")
.apply(&mut struct1, struct2);
assert_eq!(struct1, expected_struct);
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.