Skip to content

Instantly share code, notes, and snippets.

@lukepighetti
Last active June 2, 2023 12:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukepighetti/9158aac52c402e243be5d09b2b69f988 to your computer and use it in GitHub Desktop.
Save lukepighetti/9158aac52c402e243be5d09b2b69f988 to your computer and use it in GitHub Desktop.
Need UUIDs that are shorter and URL safe? UUID -> hex bytes -> Base64Url
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);
}
}
@Skhendle
Copy link

Skhendle commented Jun 1, 2023

Dope

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment