Skip to content

Commit 6097bd6

Browse files
Add UTF-8 support to CString (#14)
1 parent b558ff3 commit 6097bd6

File tree

2 files changed

+20
-11
lines changed

2 files changed

+20
-11
lines changed

objectbox/lib/src/ffi/cstring.dart

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,33 @@
11
import "dart:ffi";
2+
import "package:utf/src/utf8.dart";
23

4+
// TODO check if revamp structs are relevant (https://github.com/dart-lang/sdk/issues/37229)
35
// wrapper for a null-terminated array of characters in memory ("c-style string")
46
class CString {
57
Pointer<Uint8> _ptr;
68

7-
CString(String dartStr) { // if this constructor is used, ".free" needs to be called on this instance
8-
_ptr = allocate(count: dartStr.length + 1);
9-
for(int i = 0; i < dartStr.length; ++i)
10-
_ptr.elementAt(i).store(dartStr.codeUnitAt(i));
11-
_ptr.elementAt(dartStr.length).store(0);
9+
// if this constructor is used, ".free" needs to be called on this instance
10+
CString(String dartStr) {
11+
final ints = encodeUtf8(dartStr);
12+
_ptr = allocate(count: ints.length + 1);
13+
for(int i = 0; i < ints.length; ++i) {
14+
_ptr.elementAt(i).store(ints.elementAt(i));
15+
}
16+
_ptr.elementAt(ints.length).store(0);
1217
}
1318

1419
CString.fromPtr(this._ptr);
1520

1621
String get val {
17-
String ret = "", c;
18-
int i = 0;
19-
while((c = String.fromCharCode(_ptr.elementAt(i++).load<int>())).codeUnitAt(0) != 0) // TODO: unicode support
20-
ret += c;
21-
return ret;
22+
List<int> utf8CodePoints = new List<int>();
23+
int element;
24+
25+
for(int i = 0; element != 0; i++) {
26+
element = _ptr.elementAt(i).load<int>();
27+
utf8CodePoints.add(element);
28+
}
29+
30+
return decodeUtf8(utf8CodePoints);
2231
}
2332

2433
String toString() => val;

objectbox_test/test/test.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ main() {
1818
var store = Store([[Note, Note_OBXDefs]]);
1919
var box = Box<Note>(store);
2020

21-
var note = Note.construct("Hello");
21+
var note = Note.construct("Hello 😄");
2222
note.id = box.put(note);
2323
print("new note got id ${note.id}");
2424
print("refetched note: ${box.getById(note.id)}");

0 commit comments

Comments
 (0)