tweak memory management

This commit is contained in:
Henry Hiles 2026-11-05 20:51:28 -05:00
commit ea29889e5c
Signed by: Henry-Hiles
SSH key fingerprint: SHA256:VKQUdS31Q90KvX7EkKMHMBpUspcmItAh86a+v7PGiIs
2 changed files with 26 additions and 32 deletions

View file

@ -79,34 +79,26 @@ class ClientController(final String? accountId) extends AsyncNotifier<int> {
final environment = await _environment(account);
debugPrint("Setting Gomuks env for $account...");
using((arena) {
for (final MapEntry(:key, :value) in environment.entries) {
final keyPtr = key.toNativeUtf8().cast<Char>();
final valuePtr = value.toNativeUtf8().cast<Char>();
try {
GomuksSetEnv(keyPtr, valuePtr);
} finally {
calloc
..free(keyPtr)
..free(valuePtr);
}
GomuksSetEnv(
key.toNativeUtf8(allocator: arena).cast(),
value.toNativeUtf8(allocator: arena).cast(),
);
}
}, malloc);
debugPrint("Initializing Gomuks...");
final bufferPointer = GomuksConfig(
final config = GomuksConfig(
matrix: .new(
initialDeviceDisplayName:
"Nexus on ${toBeginningOfSentenceCase(Platform.operatingSystem)}",
),
).toJson().toGomuksBufferPtr();
final int handle;
try {
handle = GomuksInit(bufferPointer.ref);
} finally {
calloc
..free(bufferPointer.ref.base)
..free(bufferPointer);
}
).toJson();
final handle = using(
(arena) => GomuksInit(config.toGomuksBufferPtr(arena).ref),
malloc,
);
if (!ref.mounted) {
GomuksDestroy(handle);
@ -233,13 +225,16 @@ class ClientController(final String? accountId) extends AsyncNotifier<int> {
String command, [
Map<String, dynamic> data = const {},
]) => callGomuksMethod(data, (handle, data, callback) {
final commandPointer = command.toNativeUtf8().cast<Char>();
try {
GomuksSubmitCommandAsync(handle, commandPointer, data, callback);
} finally {
// gomuks copies the command name before returning
calloc.free(commandPointer);
}
using(
(arena) => GomuksSubmitCommandAsync(
handle,
command.toNativeUtf8(allocator: arena).cast(),
data,
callback,
),
malloc,
);
});
Future<void> redactEvent(RedactEventRequest report) =>

View file

@ -2,7 +2,6 @@ import "dart:convert";
import "dart:ffi";
import "dart:typed_data";
import "package:ffi/ffi.dart";
import "package:nexus/src/third_party/gomuks.g.dart";
extension GomuksOwnedBufferToX on GomuksOwnedBuffer {
@ -29,13 +28,13 @@ extension JsonToGomuksBuffer on Map<String, dynamic> {
return buffer;
}
Pointer<GomuksBorrowedBuffer> toGomuksBufferPtr() {
Pointer<GomuksBorrowedBuffer> toGomuksBufferPtr(Allocator allocator) {
final bytes = utf8.encode(json.encode(this));
final dataPtr = calloc<Uint8>(bytes.length);
final dataPtr = allocator<Uint8>(bytes.length);
dataPtr.asTypedList(bytes.length).setAll(0, bytes);
return calloc<GomuksBorrowedBuffer>()
return allocator<GomuksBorrowedBuffer>()
..ref.base = dataPtr
..ref.length = bytes.length;
}