@@ -7,6 +7,7 @@ import 'dart:convert';
77import 'dart:ffi' ;
88import 'dart:ffi' as ffi;
99import 'dart:io' ;
10+ import 'dart:typed_data' ;
1011
1112import 'package:dylib/dylib.dart' ;
1213import 'package:ffi/ffi.dart' ;
@@ -76,13 +77,13 @@ base class Parser implements Finalizable {
7677 /// Parses out a tree from the given string
7778 Tree parse (String program, {int ? encoding}) {
7879 _contents = program;
79- final pProgram = program.toNativeUtf8 (). cast < Char > ();
80+ final ( pProgram, len) = program.toNativeUtf8Len ();
8081 if (encoding == null ) {
8182 return Tree (treeSitterApi.ts_parser_parse_string (
82- parser, nullptr, pProgram, program.length ));
83+ parser, nullptr, pProgram. cast (), len ));
8384 } else {
8485 return Tree (treeSitterApi.ts_parser_parse_string_encoding (
85- parser, nullptr, pProgram, program.length , encoding));
86+ parser, nullptr, pProgram. cast (), len , encoding));
8687 }
8788 }
8889
@@ -160,13 +161,12 @@ base class Query implements Finalizable {
160161
161162 Query .fromSource (
162163 {required Pointer <TSLanguage > language, required String source}) {
163- final pSource = source.toNativeUtf8 ().cast <Char >();
164- final length = utf8.encode (source).length;
164+ final (pSource, len) = source.toNativeUtf8Len ();
165165 using ((alloc) {
166166 final errorOffset = alloc <Uint32 >(1 );
167167 final errorType = alloc <Int32 >(1 );
168168 query = treeSitterApi.ts_query_new (
169- language, pSource, length , errorOffset, errorType);
169+ language, pSource. cast (), len , errorOffset, errorType);
170170 if (query == nullptr) {
171171 final errOff = errorOffset.value;
172172 final errType = errorType.value;
@@ -286,10 +286,10 @@ extension TSNodeX on TSNode {
286286
287287 int get namedChildCount => treeSitterApi.ts_node_named_child_count (this );
288288
289- TSNode childByFieldName (String fieldName, int fieldNameLength ) {
290- final pFieldName = fieldName.toNativeUtf8 (). cast < Char > ();
289+ TSNode childByFieldName (String fieldName) {
290+ final ( pFieldName, nameLength) = fieldName.toNativeUtf8Len ();
291291 final result = treeSitterApi.ts_node_child_by_field_name (
292- this , pFieldName, fieldNameLength );
292+ this , pFieldName. cast (), nameLength );
293293 malloc.free (pFieldName);
294294 return result;
295295 }
@@ -303,3 +303,14 @@ extension TSNodeX on TSNode {
303303 TSNode get nextNamedSibling => treeSitterApi.ts_node_next_named_sibling (this );
304304 TSNode get prevNamedSibling => treeSitterApi.ts_node_prev_named_sibling (this );
305305}
306+
307+ extension on String {
308+ (Pointer <Utf8 >, int ) toNativeUtf8Len ({Allocator allocator = malloc}) {
309+ final units = utf8.encode (this );
310+ final Pointer <Uint8 > result = allocator <Uint8 >(units.length + 1 );
311+ final Uint8List nativeString = result.asTypedList (units.length + 1 );
312+ nativeString.setAll (0 , units);
313+ nativeString[units.length] = 0 ;
314+ return (result.cast (), units.length);
315+ }
316+ }
0 commit comments