base64id-rs
A pure rust library for representing 64 bit integers as base64url encoded strings.
base64url i64 u64
----------- -------------------- --------------------
B21CkMCtWZA 535157120202267024 535157120202267024
fHH_W21Typg 8967229101212682904 8967229101212682904
kjsG-f3NhxI -7909720649771415790 10537023423938135826
jHamKFSl5oM -8325284168998721917 10121459904710829699
A 64 bit integer (8 bytes) is efficiently stored and manipulated in memory. When the value needs to be sent to a web client over HTTP, the value is base64url encoded and sent as exactly 11 base64url characters (11 bytes).
For a video of the underlying concept in action, see here.
Benefits
- 64 bit integers are sent in a url safe manor
- Reduces the number of bytes needed to send the integer as compared to decimal, which would require up to 20 bytes.
- Allows users to easily copy/paste the integer as a string
Motivation
I've used this concept a number of times in personal and work projects as I find it very useful. The problem is I've had to reimplement the functionality everytime.
The motivation for this library was to design and implement the core concept once, while paying attention to metrics such as performance, correctness, and compatability. To that end:
- the library is
no_stdby default; with no heap allocation required, all execution is done on the stack - all base64 bit manipulation code is unit tested with fixed random values for compliance with RFC 4648
Installation
Add the following to your Cargo.toml file
[]
= { = "0.1", = ["std"] }
For #![no_std] environments the std cargo feature can be omitted.
Usage
All work is done using the Id64 struct.
Encoding
You can convert an i64 or u64 into a Id64 as follows
use Id64;
Decoding
You can also use FromStr to convert strings into an Id64
use ;
use FromStr;
Third Party Crates
Support for Serde, Rand and SQLx may be enabled through the use of optional cargo feature flags.
Rand
You can use the rand feature flag for working with the rand crate.
use Id64;
use random;
let id: Id64 = random;
println!; // 11 random base64url characters
Serde
You can use the serde feature flag to drive Serialize and Deserialize on Id64.
use Id64;
use ;
let record = Record ;
println!; // {"id":"AAAAAAAAAAA"}
SQLx
You can use the sqlx feature flag for using an Id64 with SQLx SQL commands.
use Id64;
use ;
use FromStr;
let id = from_str?;
let mut conn = connect.await?;
query
.execute
.await?;
query
.bind
.execute
.await?;
let output =
.fetch_one
.await?;
println!; // IkoY0lQYRrI
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.