- java.lang.Object
-
- com.github.f4b6a3.uuid.codec.other.SlugCodec
-
public final class SlugCodec extends Object implements UuidCodec<String>
Codec for UUID Slugs.A UUID Slug is a shorter string representation that can be safely included in URLs and file names.
The
SlugCodecturns a UUID into a string that does not start with digits (0-9). Due to the default base-64-url alphabet, it is case sensitive and may contain '-' and '_'.The
Base32Codeccan be passed to theSlugCodecconstructor to generate base-32 slugs. Due to the base-32 alphabet, it is case insensitive and it contains only letters (a-zA-Z) and digits (2-7). This encoding substitution can be done to avoid the characters '-' and '_' of the base-64-url encoding, but it makes the slug case insensitive.To turn a UUID into a slug, the version and variant nibbles are are moved to the first position of the UUID byte array. The slugs generated of the same UUID version show a constant letter in the first position of the base-64-url string.
This is how the UUID bits are rearranged:
aaaaaaaa-bbbb-Vccc-Rddd-eeeeeeeeeeee | | ^ ,-------------' | encode | |,-----------------' | decode || v VRaaaaaa-aabb-bbcc-cddd-eeeeeeeeeeee shift >>| V: version nibble or character R: variant nibble or characterThis table shows the slug prefixes for each UUID version:
VERSON PREFIX EXAMPLE 1 G GxA1e7vco3Ib6_mjtptP3w 2 K KryezRARVgTHLQ3zJpAXIw 3 O O9JfSS1IqIabkEWC-uXWNA 4 S S5iPSZYDt7q2w0qiIFZVwQ 5 W WY-Uv6WAY5os7Gfv4ILnvQ 6 a aMKkEoaymw0FSQNJRDL7GwIf you don't like the change in the bytes layout before the encoding to base-64-url, use the
Base64UrlCodecinstead ofSlugCodecto generate slugs.SlugCodecandNcnameCodecare very similar. The difference between the two is the bit shift they do with the original UUID to transform it into a string.In the case someone is interested in implementing this type of slug in another language, the change in the bytes layout don't have to be done with bit shifting. Since a base-16 character corresponds to a nibble, the layout change could be easily done by moving characters instead of by shifting bits. See
SlugCodecTest#moveCharacters().- See Also:
- UUID Slugs
-
-
Constructor Summary
Constructors Constructor Description SlugCodec()SlugCodec(BaseNCodec codec)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description UUIDdecode(String slug)Get a UUID from a Slug.Stringencode(UUID uuid)Get a Slug from a UUID.
-
-
-
Field Detail
-
INSTANCE
public static final SlugCodec INSTANCE
A shared immutable instance using `base64url`
-
-
Constructor Detail
-
SlugCodec
public SlugCodec()
-
SlugCodec
public SlugCodec(BaseNCodec codec)
- Parameters:
codec- a base-n codec to be used (the default is base-64-url)
-
-