Crate base64id_core
source ·Expand description
This crate allows for fixed length 64, 32 and 16 bit integers to be represented as base64url encoded strings. This is useful for exchanging unique identifiers in a web based contexts; eg. sending an SQL primary key to a client with as few character as possible.
This crate is #![no_std]
by default.
You can use the std
cargo feature flag to enable support for the standard library
Quick Start
Add the following to your Cargo.toml
file.
[dependencies]
base64id = { version = "0.3", features = ["std", "rand"] }
Encoding
You can use the rand
feature flag to generate a random ID like so.
use base64id_core::Id64;
fn main() {
let id: Id64 = rand::random();
println!("{id}"); // 3Zohppb9XMw
}
Decoding
You can decode a string into an Id64
using it’s FromStr
impl.
use std::str::FromStr;
use base64id_core::{Error, Id64};
fn main() -> Result<(), Error> {
let id = Id64::from_str("AAAAAAAAAAE")?;
assert_eq!(id, Id64::from(1u64));
Ok(())
}
Refer to the Error enum regarding decode errors.
Serde
You can use the serde
feature flag to derive Serialize
and Deserialize
on Id64
, Id32
and Id16
.
Examples
Deserializing a json string into an Id32
let id: Id32 = serde_json::from_str(r#""CyRWFA""#)?;
assert_eq!(id, Id32::from(186930708));
Serializing a struct containing an Id64
#[derive(Serialize)]
struct Record {
pub id: Id64,
}
let record = Record { id: Id64::from(5869384017340884593i64) };
assert_eq!(
serde_json::to_string(&record)?,
r#"{"id":"UXQ9qpv1ZnE"}"#
);
SQLx
You can use the sqlx
feature flag to derive Type
and FromRow
on Id64
, Id32
and Id16
.
This will allow you to add, update or query values from any SQLx supported database without manual type conversion.
Values are converted to and from SQL data types based on their i64
, i32
and i16
representations.
Random Values for Development
From the command line you can quickly generate your own random values, along with their corosponding signed and unsigned integers.
cargo run --example random_sample ([64|32|16])
Warning! The output of this command is not guarentted to be stable, and may change at anytime.
Modules
Structs
- 16 bit container with methods for base64url encoding
- 32 bit container with methods for base64url encoding
- 64 bit container with methods for base64url encoding
Enums
- Error enum for base64url decoding