ananoid 1.1.0

Edit this page

How-To: Work with Tagged NanoId strings

Ananoid can serve most uses cases via the NanoId type and its associates (Alphabet, et cetera). However, sometimes this is not desired (or at least, not optimal). For times when the a struct or class is just too much, Ananoid also provides its core functionality -- cryptographically-secure randomly-generated identifiers -- as functions which take simple inputs and just produce strings (as seen here). And, for F# consumers, there is one more option: tagged identifiers. This feature attempts to strike a balance between the performance of raw strings and safety of more robust types.


Attention!!!

This feature is only relevant to F# consumers... sorry ¯\(ツ)/¯ .


Effectively, instead of generating strings, the functions in the Tagged module (ab)use F#'s units of measure functionality to generate strings that have been "tagged" with a special measure, nanoid. This causes them to be typed-checked separately from ordinary string. However, as they are erased at run-time, they pose none of the overhead of full types (like NanoId). Usage can be as simple as:

F#
open pblasucci.Ananoid.Core.Tagged

let taggedDefaultId = nanoId' ()
let taggedNumericId = nanoIdOf' "0123456789" 12
Interative Session
> open pblasucci.Ananoid.Core.Taggd;;

> let taggeedDefaultId = nanoId' ();;
    taggedDefaultId: string<nanoid> = "SG0vBABewIRQxruwugpTD"

> let taggedNumericId = nanoIdOf' "0123456789" 12;;
    taggedNumericIdL string<nanoid> = "387443539896"

Ananoid further provides the tag function for converting simple strings into tagged strings. For converting in the opposite direction (from a tagged string into a simple string), simply use the built-in string function. The follow example helps to demonstrate the usage of tag and string:

F#
let simpleId = nanoId ()
let taggedId = nanoid.tag simpleId

let simpleId' = string taggedId
printfn $"%s{nameof simpleId} = %s{nameof simpleId'}? %b{simpleId = simpleId'}"
Interative Session
> dotnet fsi ~/scratches/taggednanoid.fsx

simpleId = simpleId'? true

Related Reading

Copyright

The library is available under the Mozilla Public License, Version 2.0. For more information see the project's License file.

val taggedDefaultId: obj
val taggedNumericId: obj
Multiple items
val string: value: 'T -> string

--------------------
type string = System.String
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
val nameof: 'T -> string