37 lines
1.2 KiB
Dart
37 lines
1.2 KiB
Dart
// ignore_for_file: public_member_api_docs
|
|
|
|
enum Status { ok, error }
|
|
|
|
class ShrinkRay {
|
|
static const shrinkLength = 6;
|
|
static const String shrinkChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
|
|
static ({Status status, String content}) shrinkUrl(String urlStr) {
|
|
try {
|
|
final uri = Uri.parse(urlStr);
|
|
if (!uri.isScheme('HTTP') && !uri.isScheme('HTTPS') || uri.hasPort) {
|
|
throw const FormatException();
|
|
}
|
|
|
|
final hash = uri.hashCode;
|
|
return (status: Status.ok, content: _translate(hash));
|
|
} on FormatException {
|
|
return (status: Status.error, content: 'Invalid Uri');
|
|
} catch (err, st) {
|
|
print('Unknown error occurred: $err');
|
|
print(st);
|
|
return (status: Status.error, content: 'Unknown error occurred');
|
|
}
|
|
}
|
|
|
|
static String _translate(int hash, {String builtTranslation = ''}) {
|
|
if (builtTranslation.length == shrinkLength) return builtTranslation;
|
|
final index = hash % shrinkChars.length;
|
|
final translation = builtTranslation + shrinkChars.substring(index, index + 1);
|
|
final shiftedHash = hash << 1;
|
|
return _translate(shiftedHash, builtTranslation: translation);
|
|
}
|
|
}
|
|
|
|
Map<String, String> shrunkUrls = {};
|