base62
A fast, zero-dependency base62 encoder/decoder library for Rust, typically used in URL shorteners. It supports both standard [0-9A-Za-z] and alternative [0-9a-zA-Z] variants.
Features
no_stdcompatible with optionalallocandstdsupport- Encodes integers up to
u128 - Zero-copy decoding
- Efficient string handling
- Two encoding variants:
- Standard [0-9A-Za-z]
- Alternative [0-9a-zA-Z]
Usage
Add this to your Cargo.toml:
[]
= "2"
Basic Example
use base62;
// Encoding
let encoded = encode;
assert_eq!;
// Decoding
let decoded = decode.unwrap;
assert_eq!;
No-std Usage
The crate works in no_std environments by default:
use base62;
// Encode into a fixed buffer
let mut buf = ; // Maximum size needed for u128
let len = encode_bytes.unwrap;
assert_eq!;
// Decode from bytes
let decoded = decode.unwrap;
assert_eq!;
Feature Flags
alloc: Enables String allocation support (enabled by default)std: Enables std::io traits support
Performance
The library is optimized for both encoding and decoding performance:
- Zero-copy decoding
- Efficient buffer management
- Direct string manipulation for optimal performance when appending
- Pair-at-a-time encoding, with fixed-width chunks for larger integers
- Byte-indexed decoding tables and a short-input path without wide arithmetic
- Separate encoding and decoding tables, so decode-only binaries can discard encoding tables
Comparing performance
The by_digits Criterion group measures both alphabets at every width from 1 to
22 digits, plus mixed-length inputs. Each iteration processes 128 seeded,
precomputed inputs. Criterion reports time per 128-value batch and throughput in
values per second; divide the batch time by 128 to obtain time per value.
Random-number generation, allocation, and input destruction are outside these
core-operation timings.
Both runs must use identical corpus generation; regenerate baselines whenever
benchmark inputs change.
Record a baseline before changing the implementation, then compare against it:
# After changing the implementation:
Use the same compiler, build flags, and CPU affinity for both runs, without other
CPU-intensive jobs. On Linux, taskset -c <cpu> pins the command to one logical CPU.
The existing encode and decode groups also cover allocation and fixed inputs.
License
Licensed under the MIT license. See LICENSE for details.