Struct nid::Nanoid

source ·
pub struct Nanoid<const N: usize = 21, A: Alphabet = Base64UrlAlphabet> { /* private fields */ }
Expand description

A Nano ID.

§Generic parameters

  • N: The length of the Nano ID. The default is 21.
  • A: The alphabet used in the Nano ID. The default is Base64UrlAlphabet.

§Generating

When you want a new Nano ID, you can generate one using the Nanoid::new.

use nid::Nanoid;
let id: Nanoid = Nanoid::new();

§Parsing

You can parse a string into a Nano ID using Nanoid::try_from_str, std::str::FromStr or TryFrom<String>.

use nid::Nanoid;
let id: Nanoid = Nanoid::try_from_str("K8N4Q7MNmeHJ-OHHoVDcz")?;
let id: Nanoid = "3hYR3muA_xvjMrrrqFWxF".parse()?;
let id: Nanoid = "iH26rJ8CpRz-gfIh7TSRu".to_string().try_into()?;

If you try to parse an invalid Nano ID, you will get an error.

use nid::{Nanoid, ParseError};

let result: Result<Nanoid, _> = "61psxw-too_short".parse();
assert!(matches!(result, Err(ParseError::InvalidLength { .. })));

let result: Result<Nanoid, _> = "6yt_invalid_char#####".to_string().try_into();
assert!(matches!(result, Err(ParseError::InvalidCharacter(_))));

§Converting to a string

You can get the string representation of the Nano ID using Nanoid::as_str, AsRef<str> or Display.

use nid::Nanoid;
let id: Nanoid = "Z9ifKfmBL7j69naN7hthu".parse()?;

// Convert to &str
assert_eq!(id.as_str(), "Z9ifKfmBL7j69naN7hthu");
assert_eq!(id.as_ref(), "Z9ifKfmBL7j69naN7hthu");

// Convert to String
assert_eq!(id.to_string(), "Z9ifKfmBL7j69naN7hthu");

§Examples

use nid::{alphabet::Base62Alphabet, Nanoid};

// Generate a new Nano ID and print it.
let id: Nanoid = Nanoid::new();
println!("{}", id);

// Parse a string into a Nano ID and convert it back to a string.
let id: Nanoid = "abcdefg1234567UVWXYZ_".parse()?;
let s = id.to_string();

// Parse a string into a Nano ID with a different length and alphabet.
let id: Nanoid<9, Base62Alphabet> = "abc123XYZ".parse()?;

Implementations§

source§

impl<const N: usize, A: Alphabet> Nanoid<N, A>

source

pub fn new() -> Self

Generate a new Nano ID using random number generator seeded by the system.

§Panics

The function will panic if the random number generator is not able to generate random numbers. This function also panics if the provided Alphabet produces non-ascii characters, but this never happens unless the alphabet is implemented incorrectly.

§Examples
use nid::Nanoid;
let id: Nanoid = Nanoid::new();
source

pub fn new_with(rng: impl Rng) -> Self

Generate a new Nano ID using the provided random number generator.

§Panics

The function will panic if the provided random number generator is not able to generate random numbers. This function also panics if the provided Alphabet produces non-ascii characters, but this never happens unless the alphabet is implemented incorrectly.

§Examples
use nid::Nanoid;
let id: Nanoid = Nanoid::new_with(rand::thread_rng());
source

pub const fn try_from_str(s: &str) -> Result<Self, ParseError>

Parse a string into a Nanoid.

§Errors
§Examples
use nid::Nanoid;
let id: Nanoid = Nanoid::try_from_str("r9p_QLd_9CD63JqQaGQ9I")?;
source

pub const fn try_from_bytes(buf: &[u8; N]) -> Result<Self, ParseError>

Parse a byte array into a Nanoid.

§Errors

If the byte array contains a character that is not in the alphabet, this method returns ParseError::InvalidCharacter.

§Examples
use nid::Nanoid;
let id: Nanoid = Nanoid::try_from_bytes(b"0tY_GxufiwmAxvmHR7G0R")?;
source

pub const fn as_str(&self) -> &str

Get the string representation of the Nanoid.

§Examples
use nid::Nanoid;
let id: Nanoid = "vsB2sq2PfhCdU6WCXk37s".parse()?;
assert_eq!(id.as_str(), "vsB2sq2PfhCdU6WCXk37s");

Trait Implementations§

source§

impl<const N: usize, A: Alphabet> AsRef<str> for Nanoid<N, A>

source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<const N: usize, A: Alphabet> Clone for Nanoid<N, A>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<const N: usize, A: Alphabet> Debug for Nanoid<N, A>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'de, const N: usize, A: Alphabet> Deserialize<'de> for Nanoid<N, A>

Available on crate feature serde only.
source§

fn deserialize<D>(deserializer: D) -> Result<Nanoid<N, A>, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl<const N: usize, A: Alphabet> Display for Nanoid<N, A>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<const N: usize, A: Alphabet> From<Nanoid<N, A>> for String

source§

fn from(id: Nanoid<N, A>) -> Self

Converts to this type from the input type.
source§

impl<const N: usize, A: Alphabet> FromStr for Nanoid<N, A>

§

type Err = ParseError

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
source§

impl<const N: usize, A: Alphabet> Hash for Nanoid<N, A>

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<const N: usize, A: Alphabet> Ord for Nanoid<N, A>

source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl<const N: usize, A: Alphabet> PartialEq for Nanoid<N, A>

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize, A: Alphabet> PartialOrd for Nanoid<N, A>

source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<const N: usize, A: Alphabet> Serialize for Nanoid<N, A>

Available on crate feature serde only.
source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl<const N: usize, A: Alphabet> TryFrom<String> for Nanoid<N, A>

§

type Error = ParseError

The type returned in the event of a conversion error.
source§

fn try_from(s: String) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl<const N: usize, A: Alphabet> Zeroize for Nanoid<N, A>

source§

fn zeroize(&mut self)

Zero out this object from memory using Rust intrinsics which ensure the zeroization operation is not “optimized away” by the compiler.
source§

impl<const N: usize, A: Alphabet> Copy for Nanoid<N, A>

source§

impl<const N: usize, A: Alphabet> Eq for Nanoid<N, A>

Auto Trait Implementations§

§

impl<const N: usize, A> Freeze for Nanoid<N, A>

§

impl<const N: usize, A> RefUnwindSafe for Nanoid<N, A>

§

impl<const N: usize, A> Send for Nanoid<N, A>

§

impl<const N: usize, A> Sync for Nanoid<N, A>

§

impl<const N: usize, A> Unpin for Nanoid<N, A>

§

impl<const N: usize, A> UnwindSafe for Nanoid<N, A>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,