Skip to content
This repository was archived by the owner on Sep 27, 2024. It is now read-only.

Add force option to mailbox.put #25

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
13 changes: 10 additions & 3 deletions lib/mailbox.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
10 changes: 10 additions & 0 deletions test/mailbox_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<StateError>()));
mailbox.put(Uint8List(0), force: true);
final value = mailbox.take();
expect(value, isA<Uint8List>());
expect(value.length, equals(0));
});
}