diff --git a/CHANGELOG.md b/CHANGELOG.md index 9acca14..81b3933 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 0.3.0 + +- Add `force` option to `Mailbox`'s `put` method. + ## 0.2.0 - Lower SDK lower bound to 3.0.0. diff --git a/lib/mailbox.dart b/lib/mailbox.dart index 0871a7c..05ce900 100644 --- a/lib/mailbox.dart +++ b/lib/mailbox.dart @@ -67,12 +67,19 @@ class Mailbox { /// Place a message into the mailbox if has space for it. /// - /// If mailbox already contains a message then [put] will throw. - void put(Uint8List message) { + /// If mailbox already contains a message then [put] will throw, unless + /// [force] is set to `true`. + void put(Uint8List message, {bool force = false}) { final buffer = message.isEmpty ? nullptr : _toBuffer(message); _mutex.runLocked(() { if (_mailbox.ref.state != _stateEmpty) { - throw StateError('Mailbox is full'); + if (!force) { + throw StateError('Mailbox is full'); + } + + if (_mailbox.ref.bufferLength > 0) { + malloc.free(_mailbox.ref.buffer); + } } _mailbox.ref.state = _stateFull; diff --git a/pubspec.yaml b/pubspec.yaml index e16317f..bf93c3f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: native_synchronization description: Low level synchronization primitives built on dart:ffi. -version: 0.2.0 +version: 0.3.0 repository: https://github.com/dart-lang/native_synchronization environment: diff --git a/test/mailbox_test.dart b/test/mailbox_test.dart index 2400d56..ad1526e 100644 --- a/test/mailbox_test.dart +++ b/test/mailbox_test.dart @@ -29,4 +29,14 @@ void main() { expect(value[41], equals(42)); expect(await helperResult, equals('success')); }); + + test('mailbox throws', () { + final mailbox = Mailbox(); + mailbox.put(Uint8List(42)..[41] = 42); + expect(() => mailbox.put(Uint8List(0)), throwsA(TypeMatcher())); + mailbox.put(Uint8List(0), force: true); + final value = mailbox.take(); + expect(value, isA()); + expect(value.length, equals(0)); + }); }