dylanhart / ulid-rs

This is a Rust implementation of the ulid project
https://crates.io/crates/ulid
MIT License
389 stars 37 forks source link

Add MIN/MAX Ulid constants #36

Closed rakanalh closed 3 years ago

rakanalh commented 3 years ago

Hello,

Adding Min and Max constants would be very useful to making range queries.

The implementation would be similar to this:

https://github.com/ahawker/ulid/blob/c17c3bb7a87ebcb0df6715675049e3130aa4eb7e/ulid/consts.py#L12-L32

dylanhart commented 3 years ago

Those constants don't really look like they would be that helpful since they are just 0 or (1 << N) - 1 where N is the bit-width of the field in question. This library does have those N values but they are not currently public. That being said, the python constants don't really solve much of the problem since you would still need to do your own bit-math for range queries.

I think that we should instead design an API that returns std::ops::Range or something similar. Can you explain your use-case some more so that we can come up with an interface that works well?

rakanalh commented 3 years ago

Hi @dylanhart,

Sure... basically i am storing records in sqlite where the identifiers are ULIDs. By range queries, i meant that i would like to query a certain table whose identifier is a ULID with identifier BETWEEN X and Y or identifier <= {max_ulid_identifier}.

This is why i think the constants might be useful if you want to get records with identifiers greater or smaller than min/max ULIDs respectively.

Would you say that:

use chrono::{MAX_DATETIME, MIN_DATETIME};
use ulid:: Generator;

let mut generator = Generator::new();
let max_ulid = generator.generate_from_datetime(MAX_DATETIME).unwrap();
let min_ulid = generator.generate_from_datetime(MIN_DATETIME).unwrap();

would properly calculate the min and max values?

dylanhart commented 3 years ago

In that case you can use u128::MAX for now. The min/max datetime would not work at all, so a new API could be added to get ulid value sub-ranges for date ranges along with ulid-specific min/max datetime.

rakanalh commented 3 years ago

I see... could you elaborate on using u128::MAX please? Do you mean that i could use u128::MAX to generate a ULID?

dylanhart commented 3 years ago

ulids are 128-bit identifiers, so the maximum value of u128 is the same as the maximum value of a Ulid. This library implements the From conversion trait to and from u128.