Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update incr by precision #57

Merged
merged 3 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ uuid = { version = "1.8.0", features = ["v4"] }
strum = "0.26.2"
strum_macros = "0.26.2"
clap = { version = "4.5.7", features = ["derive", "env"] }
num-traits = "0.2.19"

[dev-dependencies]
rand = "0.8.5"
Expand Down
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,8 @@ test:
cargo test -- \
--nocapture \
--color=always


.PHONY: run
run:
cargo run
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@

Welcome to rustdis, a partial Redis server implementation written in Rust.

This project came to life out of pure curiosity, and because we wanted to learn more about Rust and Redis. So doing this project seemed like a good idea.
The primary goal of rustdis is to offer a straightforward and comprehensible implementation, with no optimization techniques to ensure the code remains accessible and easy to understand.
As of now, rustdis focuses exclusively on implementing Redis' String data type and its associated methods. You can find more about Redis strings here: [Redis Strings](https://redis.io/docs/data-types/strings/).
This project came to life out of pure curiosity, and because we wanted to learn
more about Rust and Redis. So doing this project seemed like a good idea. The
primary goal of rustdis is to offer a straightforward and comprehensible
implementation, with no optimization techniques to ensure the code remains
accessible and easy to understand. As of now, rustdis focuses exclusively on
implementing Redis' String data type and its associated methods. You can find
more about Redis strings here: [Redis
Strings](https://redis.io/docs/data-types/strings/).

This server is not production-ready; it is intended purely for educational purposes.
This server is not production-ready; it is intended purely for educational
purposes.

### Run
```shell
cargo run
make run
```
### Test
```shell
cargo test
make test
```
### Architecture

Expand Down
16 changes: 9 additions & 7 deletions src/commands/incrbyfloat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ pub struct IncrByFloat {
impl Executable for IncrByFloat {
fn exec(self, store: Store) -> Result<Frame, Error> {
let mut store = store.lock();
let res = store.incr_by(&self.key, self.increment);
let res = store.incr_by::<f64, String>(&self.key, self.increment);
match res {
Ok(res) => Ok(Frame::Simple(res.to_string())),
Ok(res) => Ok(Frame::Bulk(res.into())),
Err(msg) => Ok(Frame::Error(msg.to_string())),
}
}
Expand All @@ -56,6 +56,7 @@ mod tests {
#[tokio::test]
async fn existing_key() {
let store = Store::new();
store.lock().set(String::from("key1"), Bytes::from("10.50"));

let frame = Frame::Array(vec![
Frame::Bulk(Bytes::from("INCRBYFLOAT")),
Expand All @@ -72,12 +73,13 @@ mod tests {
})
);

store.lock().set(String::from("key1"), Bytes::from("10.50"));

let result = cmd.exec(store.clone()).unwrap();

assert_eq!(result, Frame::Simple("10.6".to_string()));
assert_eq!(store.lock().get("key1"), Some(Bytes::from("10.6")));
assert_eq!(result, Frame::Bulk(Bytes::from("10.59999999999999964")));
assert_eq!(
store.lock().get("key1"),
Some(Bytes::from("10.59999999999999964"))
);
}

#[tokio::test]
Expand All @@ -101,7 +103,7 @@ mod tests {

let result = cmd.exec(store.clone()).unwrap();

assert_eq!(result, Frame::Simple("10".to_string()));
assert_eq!(result, Frame::Bulk(Bytes::from("10")));
assert_eq!(store.lock().get("key1"), Some(Bytes::from("10")));
}

Expand Down
24 changes: 18 additions & 6 deletions src/store.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use bytes::Bytes;
use num_traits::{ToPrimitive, Zero};
use std::collections::{BTreeSet, HashMap};
use std::fmt::Display;
use std::ops::AddAssign;
use std::ops::Deref;
use std::str::FromStr;
Expand Down Expand Up @@ -147,9 +149,10 @@ impl<'a> InnerStoreLocked<'a> {
.map(|(key, value)| (key, &value.data))
}

pub fn incr_by<T>(&mut self, key: &str, increment: T) -> Result<T, String>
pub fn incr_by<T, R>(&mut self, key: &str, increment: T) -> Result<R, String>
where
T: FromStr + ToString + AddAssign + Default,
T: AddAssign + FromStr + Display + Zero + ToPrimitive,
R: FromStr,
{
let err = "value is not an integer or out of range";

Expand All @@ -158,16 +161,25 @@ impl<'a> InnerStoreLocked<'a> {
.map_err(|_| err.to_string())
.and_then(|s| s.parse::<T>().map_err(|_| err.to_string()))
{
Ok(value) => value,
Ok(v) => v,
Err(e) => return Err(e),
},
None => T::default(),
None => T::zero(),
};

value += increment;
self.set(key.to_string(), value.to_string().into());

Ok(value)
let value = match value.to_f64() {
Some(v) if v.fract() == 0.0 => format!("{:.0}", v), // Format as an integer if no fractional part.
Some(v) => format!("{:.17}", v), // Format as a float with up to 17 digits of precision.
// This shouldn't happen since we're only using ints and floats, but ideally, a trait
// would enforce this at compile time.
None => return Err(err.to_string()),
};
gillchristian marked this conversation as resolved.
Show resolved Hide resolved

self.set(key.to_string(), value.clone().into());

value.parse::<R>().map_err(|_| err.to_string())
Copy link
Owner Author

@ndelvalle ndelvalle Oct 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The precision-related tests are passing now, but I’m not completely convinced about this function. I think we should split the logic for integers and floats to make it more explicit.

}

fn remove_expired_keys(&mut self) -> Option<Instant> {
Expand Down
9 changes: 0 additions & 9 deletions tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,15 +226,6 @@ async fn test_incr_by_float() {
p.cmd("INCRBYFLOAT").arg("incr_by_float_key_3").arg("-1.2");
})
.await;

test_compare_err(|p| {
// Value is not an integer or out of range error.
p.cmd("SET")
.arg("incr_by_float_key_4")
.arg("234293482390480948029348230948");
p.cmd("INCRBYFLOAT").arg("incr_by_float_key_4").arg(1);
})
.await;
}

#[tokio::test]
Expand Down
Loading