Skip to content

Instantly share code, notes, and snippets.

@blaugold
Last active October 19, 2023 08:57
Show Gist options
  • Save blaugold/8cc27c7d303048655b2be0c0abdf5c6d to your computer and use it in GitHub Desktop.
Save blaugold/8cc27c7d303048655b2be0c0abdf5c6d to your computer and use it in GitHub Desktop.
interned_bytes.dart
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