all ints were supposed to be signed
This commit is contained in:
parent
f10de4e655
commit
cb9a570ad1
1 changed files with 18 additions and 10 deletions
|
@ -2,14 +2,14 @@ use std::{io::{Read, Write}, net::TcpListener};
|
|||
|
||||
#[derive(PartialEq, Debug)]
|
||||
struct InsertData {
|
||||
timestamp: u32, // seconds since 00:00, 1st Jan 1970.
|
||||
timestamp: i32, // seconds since 00:00, 1st Jan 1970.
|
||||
price: i32, // price in pennies
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
struct QueryData {
|
||||
mintime: u32,
|
||||
maxtime: u32,
|
||||
mintime: i32,
|
||||
maxtime: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
|
@ -39,12 +39,12 @@ impl Message {
|
|||
|
||||
match t {
|
||||
b'I' => Ok(Message::Insert(InsertData {
|
||||
timestamp: u32::from_be_bytes(u),
|
||||
timestamp: i32::from_be_bytes(u),
|
||||
price: i32::from_be_bytes(v),
|
||||
})),
|
||||
b'Q' => Ok(Message::Query(QueryData {
|
||||
mintime: u32::from_be_bytes(u),
|
||||
maxtime: u32::from_be_bytes(v),
|
||||
mintime: i32::from_be_bytes(u),
|
||||
maxtime: i32::from_be_bytes(v),
|
||||
})),
|
||||
_ => Err(ParseError::UnknownType),
|
||||
}
|
||||
|
@ -52,15 +52,20 @@ impl Message {
|
|||
}
|
||||
|
||||
fn get_mean_price(insertions: &Vec<InsertData>, query: &QueryData) -> i32 {
|
||||
let prices: Vec<i32> = insertions
|
||||
println!("querying for mintime: {}, maxtime: {}", query.mintime, query.maxtime);
|
||||
let prices: Vec<isize> = insertions
|
||||
.iter()
|
||||
.filter(|i| i.timestamp >= query.mintime && i.timestamp <= query.maxtime)
|
||||
.map(|i| i.price)
|
||||
.map(|i| i.price as isize)
|
||||
.collect();
|
||||
|
||||
|
||||
let len = prices.len() as isize;
|
||||
let sum = prices.iter().sum::<isize>();
|
||||
let avg = if prices.len() > 0 { sum / len } else { 0 };
|
||||
println!("query: sum: {}, len: {}, avg: {}", sum, len, avg);
|
||||
// safe?
|
||||
if prices.len() > 0 { prices.iter().sum::<i32>() / prices.len() as i32 } else { 0 }
|
||||
avg as i32
|
||||
}
|
||||
|
||||
const PORT: usize = 10001;
|
||||
|
@ -81,7 +86,10 @@ fn main() -> std::io::Result<()> {
|
|||
inserts.push(i);
|
||||
},
|
||||
Ok(Message::Query(q)) => {
|
||||
let _ = stream.write(&i32::to_be_bytes(get_mean_price(&inserts, &q)));
|
||||
let p = get_mean_price(&inserts, &q);
|
||||
let p_bytes = i32::to_be_bytes(p);
|
||||
println!("sending bytes: {:?}", p_bytes);
|
||||
let _ = stream.write(&p_bytes);
|
||||
},
|
||||
Err(e) => {
|
||||
panic!("{:?}", e);
|
||||
|
|
Loading…
Add table
Reference in a new issue