Compare commits

...

2 Commits

Author SHA1 Message Date
5c28458afd saving 2021-03-14 21:47:02 -04:00
d837b60327 saving 2021-03-14 19:41:33 -04:00
10 changed files with 379 additions and 39 deletions

63
Cargo.lock generated
View File

@ -7,6 +7,7 @@ name = "act"
version = "0.1.0"
dependencies = [
"async-stream",
"clap",
"csv",
"serde",
"strum",
@ -16,6 +17,15 @@ dependencies = [
"tokio-test",
]
[[package]]
name = "ansi_term"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
dependencies = [
"winapi",
]
[[package]]
name = "async-stream"
version = "0.3.0"
@ -37,6 +47,17 @@ dependencies = [
"syn",
]
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
]
[[package]]
name = "autocfg"
version = "1.0.1"
@ -79,6 +100,21 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "2.33.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002"
dependencies = [
"ansi_term",
"atty",
"bitflags",
"strsim",
"textwrap",
"unicode-width",
"vec_map",
]
[[package]]
name = "csv"
version = "1.1.6"
@ -349,6 +385,12 @@ dependencies = [
"winapi",
]
[[package]]
name = "strsim"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "strum"
version = "0.20.0"
@ -381,6 +423,15 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "textwrap"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
dependencies = [
"unicode-width",
]
[[package]]
name = "tokio"
version = "1.3.0"
@ -442,12 +493,24 @@ version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0d2e7be6ae3a5fa87eed5fb451aff96f2573d2694942e40543ae0bbe19c796"
[[package]]
name = "unicode-width"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "winapi"
version = "0.3.9"

View File

@ -14,6 +14,7 @@ tokio-stream = "0.1"
async-stream = "0.3"
csv = "1.1.5"
strum_macros = "0.20.1"
clap = "2.33.3"
[dev-dependencies]
tokio-test = "0.4.0"

6
input.csv Normal file
View File

@ -0,0 +1,6 @@
type,client,tx,amount
deposit,1,1,1.0
deposit,2,2,2.0
deposit,1,3,2.0
withdrawal,1,4,1.5
withdrawal,2,5,3.0
1 type client tx amount
2 deposit 1 1 1.0
3 deposit 2 2 2.0
4 deposit 1 3 2.0
5 withdrawal 1 4 1.5
6 withdrawal 2 5 3.0

29
src/bin/act.rs Normal file
View File

@ -0,0 +1,29 @@
use clap::{App, Arg};
use std::io::{BufReader, BufRead, stdin};
use std::fs;
use act::parse;
use act::stores::ActStore;
use act::stores::MemActStore;
use tokio_stream::StreamExt;
#[tokio::main]
async fn main() {
let matches = App::new("act")
.version("0.1")
.about("Merges transactions into account state")
.author("Lewis Diamond")
.arg(Arg::with_name("input").required(false).index(1).help("Input file, stdin if omitted or -"))
.get_matches();
let input: Box<dyn BufRead> = match matches.value_of("input") {
Some("-")|Some("")|None => Box::new(BufReader::new(stdin())),
Some(f) => Box::new(BufReader::new(fs::File::open(f).unwrap())),
};
let s = parse(input);
tokio::pin!(s);
while let Some(v) = s.next().await {
println!("{:?}", v);
}
}

View File

@ -1,4 +1,5 @@
pub mod types;
pub mod stores;
use async_stream::stream;
use std::io::Read;
use tokio_stream::Stream;
@ -41,11 +42,18 @@ deposit,1,3,2.0
withdrawal,1,4,1.5
withdrawal,2,5,3.0";
let expected = vec![Transaction {tx_type: TransactionType::Deposit, amount: 10000, client: 1, tx: 1}];
let expected = vec![
Transaction {tx_type: TransactionType::Deposit, amount: 10000, client: 1, tx: 1},
Transaction {tx_type: TransactionType::Deposit, amount: 20000, client: 2, tx: 2},
Transaction {tx_type: TransactionType::Deposit, amount: 20000, client: 1, tx: 3},
Transaction {tx_type: TransactionType::Withdrawal, amount: 15000, client: 1, tx: 4},
Transaction {tx_type: TransactionType::Withdrawal, amount: 30000, client: 2, tx: 5},
];
let txs = parse(data.as_bytes()).collect::<Vec<Transaction>>().await;
assert_eq!(expected, txs);
});
}
#[test]
fn valid_csv_with_whitespaces_is_parsed() {
block_on(async {
@ -57,9 +65,61 @@ deposit, 1, 3, 2.0
withdrawal, 1, 4, 1.5
withdrawal, 2, 5, 3.0";
let txs = parse(data.as_bytes());
let result: Vec<Transaction> = txs.collect::<Vec<Transaction>>().await;
result.iter().for_each(|t| eprintln!("{:?}", t));
let expected = vec![
Transaction {tx_type: TransactionType::Deposit, amount: 10000, client: 1, tx: 1},
Transaction {tx_type: TransactionType::Deposit, amount: 20000, client: 2, tx: 2},
Transaction {tx_type: TransactionType::Deposit, amount: 20000, client: 1, tx: 3},
Transaction {tx_type: TransactionType::Withdrawal, amount: 15000, client: 1, tx: 4},
Transaction {tx_type: TransactionType::Withdrawal, amount: 30000, client: 2, tx: 5},
];
let txs = parse(data.as_bytes()).collect::<Vec<Transaction>>().await;
assert_eq!(expected, txs);
});
}
#[test]
fn amounts_are_parsed_correctly() {
block_on(async {
let data = "\
type,client,tx,amount
deposit,1,1,1.0001
deposit,2,2,2.0010
deposit,1,3,10.01
withdrawal,1,4,01.10
withdrawal,2,5,10.0110101";
let expected = vec![
Transaction {tx_type: TransactionType::Deposit, amount: 10001, client: 1, tx: 1},
Transaction {tx_type: TransactionType::Deposit, amount: 20010, client: 2, tx: 2},
Transaction {tx_type: TransactionType::Deposit, amount: 100100, client: 1, tx: 3},
Transaction {tx_type: TransactionType::Withdrawal, amount: 11000, client: 1, tx: 4},
Transaction {tx_type: TransactionType::Withdrawal, amount: 100110, client: 2, tx: 5},
];
let txs = parse(data.as_bytes()).collect::<Vec<Transaction>>().await;
assert_eq!(expected, txs);
});
}
#[test]
fn invalid_amounts_are_filtered() {
block_on(async {
let data = "\
type,client,tx,amount
deposit,1,1,99999999999999999
deposit,2,2,18446744073709551615
deposit,1,3,18446744073709551616
withdrawal,1,4,0
withdrawal,2,5,-1
withdrawal,1,6,-99999999999999999
withdrawal,1,6,-18446744073709551615
withdrawal,1,7,-18446744073709551616";
let expected = vec![
Transaction {tx_type: TransactionType::Withdrawal, amount: 0, client: 1, tx: 4},
];
let txs = parse(data.as_bytes()).collect::<Vec<Transaction>>().await;
assert_eq!(expected, txs);
});
}
}

121
src/stores/mem.rs Normal file
View File

@ -0,0 +1,121 @@
use super::ActStore;
use crate::types::Account;
use std::collections::HashMap;
pub struct MemActStore(HashMap<u16, Account>);
impl MemActStore {
pub fn new() -> MemActStore {
MemActStore(HashMap::new())
}
fn add_or_sub_balance(&mut self, client: &u16, amnt: usize, sub: bool) -> usize {
let act = self
.0
.entry(*client)
.or_insert_with(|| Account::new(*client));
if sub {
act.balance -= amnt
} else {
act.balance += amnt
};
act.balance
}
}
impl ActStore for MemActStore {
fn add_to_balance(&mut self, client: &u16, amnt: usize) -> usize {
self.add_or_sub_balance(client, amnt, false)
}
fn sub_from_balance(&mut self, client: &u16, amnt: usize) -> usize {
self.add_or_sub_balance(client, amnt, true)
}
fn hold_amount(&mut self, client: u16, amnt: usize) {
todo!()
}
fn lock_account(&mut self, client: u16) {
todo!()
}
fn unlock_account(&mut self, client: u16) {
todo!()
}
fn get_account(&self, client: &u16) -> Option<&Account> {
self.0.get(client)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add_balance() {
let mut store = MemActStore::new();
let client_id = 200;
store.add_to_balance(&client_id, 200);
if let Some(act) = store.get_account(&client_id) {
assert_eq!(200, act.id);
assert_eq!(200, act.balance);
} else {
panic!("Could not get account from store");
}
let balance = store.add_to_balance(&client_id, 50);
if let Some(act) = store.get_account(&client_id) {
assert_eq!(200, act.id);
assert_eq!(250, act.balance);
assert_eq!(250, balance);
} else {
panic!("Could not get account from store");
}
}
#[test]
fn test_sub_balance() {
let mut store = MemActStore::new();
let client_id = 1;
store.add_to_balance(&client_id, 200);
if let Some(act) = store.get_account(&client_id) {
assert_eq!(1, act.id);
assert_eq!(200, act.balance);
} else {
panic!("Could not get account from store");
}
let balance = store.sub_from_balance(&client_id, 50);
if let Some(act) = store.get_account(&client_id) {
assert_eq!(1, act.id);
assert_eq!(150, act.balance);
assert_eq!(150, balance);
} else {
panic!("Could not get account from store");
}
}
#[test]
fn test_lock_negative_balance() {
let mut store = MemActStore::new();
let client_id = 1;
store.sub_from_balance(&client_id, 1);
if let Some(act) = store.get_account(&client_id) {
assert_eq!(1, act.id);
assert_eq!(-1, act.balance);
} else {
panic!("Could not get account from store");
}
let balance = store.sub_from_balance(&client_id, 50);
if let Some(act) = store.get_account(&client_id) {
assert_eq!(1, act.id);
assert_eq!(150, act.balance);
assert_eq!(150, balance);
} else {
panic!("Could not get account from store");
}
}
}

15
src/stores/mod.rs Normal file
View File

@ -0,0 +1,15 @@
pub mod mem;
pub use mem::MemActStore;
use crate::types::Account;
pub trait ActStore {
fn get_account(&self, client: &u16) -> Option<&Account>;
fn add_to_balance(&mut self, client: &u16, amnt: usize) -> usize;
fn sub_from_balance(&mut self, client: &u16, amnt: usize) -> usize;
fn hold_amount(&mut self, client:u16, amnt: usize);
fn lock_account(&mut self, client: u16);
fn unlock_account(&mut self, client: u16);
}

29
src/types/account.rs Normal file
View File

@ -0,0 +1,29 @@
use serde::Serialize;
#[derive(Debug, Serialize, PartialEq)]
pub struct Account {
pub id: u16,
pub balance: isize,
pub held: usize,
pub locked: bool,
}
impl Account {
pub fn new(client_id: u16) -> Account {
Account {
id: client_id,
balance: 0,
held: 0,
locked: false,
}
}
pub fn with_balance(client_id: u16, seed_balance: isize) -> Account {
Account {
id: client_id,
balance: seed_balance,
held: 0,
locked: false,
}
}
}

View File

@ -1,35 +1,5 @@
use serde::{Deserialize, Deserializer};
use serde::de;
#[derive(Eq, PartialEq, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
Deposit,
Withdrawal,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct Transaction {
#[serde(rename = "type")]
pub tx_type: TransactionType,
pub client: usize,
pub tx: usize,
/// Amount of the smallest unit, e.g. 0.0001 as per the specification
#[serde(deserialize_with = "de_amount")]
pub amount: usize,
}
fn de_amount<'de, D>(deserializer: D) -> Result<usize, D::Error> where D: Deserializer<'de> {
//TODO validate for input such as `.100` so it doesn't give 100
let deserialized = String::deserialize(deserializer)?;
let mut splitted = deserialized.split('.');
let mut ret: usize = 0;
let mut factor = 4;
while let Some(s) = splitted.next() {
ret += s.parse::<usize>().map_err(de::Error::custom)? * 10usize.pow(factor);
if factor < 1 { break;}
factor -= 4;
};
Ok(ret)
}
pub mod transaction;
pub use transaction::Transaction;
pub use transaction::TransactionType;
pub mod account;
pub use account::Account;

46
src/types/transaction.rs Normal file
View File

@ -0,0 +1,46 @@
use serde::de;
use serde::{Deserialize, Deserializer};
const PRECISION: u32 = 4;
#[derive(Eq, PartialEq, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
Deposit,
Withdrawal,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct Transaction {
#[serde(rename = "type")]
pub tx_type: TransactionType,
pub client: u16,
pub tx: usize,
/// Amount of the smallest unit, e.g. 0.0001 as per the specification
#[serde(deserialize_with = "de_amount")]
pub amount: usize,
}
fn de_amount<'de, D>(deserializer: D) -> Result<usize, D::Error>
where
D: Deserializer<'de>,
{
//TODO validate for input such as `.100` so it doesn't give 100
let deserialized = String::deserialize(deserializer)?;
let mut splitted = deserialized.split('.');
let units = splitted
.next()
.map_or(Ok(0usize), |v| v.parse::<usize>())
.map_err(de::Error::custom)?
.checked_mul(10usize.pow(PRECISION))
.ok_or_else(|| de::Error::custom("Value too large"))?;
//TODO improve this to avoid `format!`
let dec = splitted
.next()
.map_or(Ok(0usize), |v| format!("{:0<4.4}", v).parse::<usize>())
.map_err(de::Error::custom)?;
Ok(units + dec)
}