Last active
October 19, 2023 08:57
-
-
Save blaugold/8cc27c7d303048655b2be0c0abdf5c6d to your computer and use it in GitHub Desktop.
interned_bytes.dart
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 'dart:typed_data'; | |
import 'package:collection/collection.dart'; | |
import 'package:json_annotation/json_annotation.dart'; | |
import 'package:meta/meta.dart'; | |
@immutable | |
class InternedBytes { | |
static final _internedInstances = <WeakReference<InternedBytes>>[]; | |
factory InternedBytes(Uint8List bytes) { | |
InternedBytes? result; | |
final newInstance = InternedBytes._(bytes); | |
final deadReferences = <WeakReference<InternedBytes>>[]; | |
for (final reference in _internedInstances) { | |
final existingInstance = reference.target; | |
if (existingInstance == null) { | |
deadReferences.add(reference); | |
} else if (newInstance._equals(existingInstance)) { | |
result = existingInstance; | |
break; | |
} | |
} | |
deadReferences.forEach(_internedInstances.remove); | |
if (result == null) { | |
result = newInstance; | |
_internedInstances.add(WeakReference(newInstance)); | |
} | |
return result; | |
} | |
InternedBytes._(this.bytes) : hashCode = const DeepCollectionEquality().hash(bytes); | |
final Uint8List bytes; | |
bool _equals(InternedBytes other) => | |
hashCode == other.hashCode && const DeepCollectionEquality().equals(bytes, other.bytes); | |
@override | |
bool operator ==(Object other) => identical(this, other); | |
@override | |
final int hashCode; | |
} | |
class InternedBytesBase64Converter implements JsonConverter<InternedBytes, String> { | |
const InternedBytesBase64Converter(); | |
@override | |
InternedBytes fromJson(String json) => InternedBytes(base64Decode(json)); | |
@override | |
String toJson(InternedBytes object) => base64Encode(object.bytes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment