Need UUIDs that are shorter and URL safe? UUID -> hex bytes -> Base64Url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:uuid/uuid.dart'; | |
void main(List<String> arguments) { | |
final uuid = "57290fdf-790f-4894-859e-3db0ae087f0e"; | |
final codec = ShortUuidCodec(); | |
final encodedUuid = codec.encode(uuid); | |
final decodedUuid = codec.decode(encodedUuid); | |
print(encodedUuid); // VykP33kPSJSFnj2wrgh_Dg== | |
print(decodedUuid); // 57290fdf-790f-4894-859e-3db0ae087f0e | |
} | |
/// Converts between a UUID and the shortest possible Base64Url String | |
class ShortUuidCodec extends Codec<String, String> { | |
static final _decoder = ShortUuidDecoder(); | |
static final _encoder = ShortUuidEncoder(); | |
@override | |
Converter<String, String> get decoder => _decoder; | |
@override | |
Converter<String, String> get encoder => _encoder; | |
} | |
/// Encodes a UUID to the shortest possible Base64Url String | |
class ShortUuidEncoder extends Converter<String, String> { | |
@override | |
String convert(String input) { | |
final bytes = Uuid.parse(input); | |
return base64Url.encode(bytes); | |
} | |
} | |
/// Decodes a "shortest possible" Base64Url encoded UUID String | |
class ShortUuidDecoder extends Converter<String, String> { | |
@override | |
String convert(String input) { | |
final decoded = base64Url.decode(input); | |
return Uuid.unparse(decoded); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dope