#base64-url #base64 #16-bit #64-bit #encoded-string

no-std base64id-core

Efficiently represent 64, 32 and 16 bit integers as base64url strings

1 unstable release

0.4.0-alpha.0 Nov 17, 2023

#5 in #base64-url


Used in base64id-derive

MIT/Apache

40KB
911 lines

base64id-core

This crate contains the core library code for base64id-rs. You shouldn't use this crate directly. See here instead.

License

Licensed under either of

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.


lib.rs:

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.

Dependencies

~0–10MB
~107K SLoC