-
Notifications
You must be signed in to change notification settings - Fork 6
Description
Needs to support two major use cases:
- Allocating the required space with a given allocator.
- Taking a byte slice, filling as much as possible.
This is similar to how printing works. Having a reader may also be a good call.
Error handling for allocator errors or slice being too small is a requirement.
I'm considering two different approaches:
- Change the return type argument in the various methods into a union. For the already existing types, they would be void type. Then add values for strings with take an allocator or a slice. The return type would match to (roughly)
![]u8. There are two considerations: The slice usage, knowing how many utf16 characters were encoded, and how many bytes of utf8 were written to the slice is occasionally important info that makes usage more awkward here, since an error would need to be returned in addition to these values. Secondly, I haven't dug into the details of how to actually do the string writing, especially for the allocator version which requires some back and forth between Zig and Js. This approach would require a cast method being added to Handle, which would operate like Handle.get, but operating on the Handle itself instead of a field. This is because sometimes a Zig function might be called with a Javascript string object as one of the arguments. - The other approach is to add specific methods which copy from a handle to a string into Zig. This would have a lot less impact on the rest of the library, but would require the creation and release of Handles whenever accessing a string field. Bleh.
Finally, the implementation should be considering JS's TextEncoder methods of encode vs enocdeInto. EncodeInto obviously works better for the use case of sending to a slice. However, the better method for allocated strings is less clear. Using encode creates a whole copy of the string which is immediately discarded. However encodeInto requires the length to already be known, which requires a JS function that goes over the string counting the utf8 length. Alternatively it's safe to just allocate 3 times the utf16 length, which is always enough but also often very wasteful.
Convenient methods to do similar actions with Uint8Array should also be considered, and possibly leveraged in the allocator case.