Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SourceText.hpp

43 lines1.3 KB

1#pragma once
2​
3#include <NitroModules/JSIConverter.hpp>
4#include <string>
5​
6#include "Utf16ToUtf8.hpp"
7​
8namespace margelo::nitro::t3highlights {
9​
10/** A JS string as the UTF-8 bytes the lexer reads. */
11struct SourceText {
12 std::string utf8;
13};
14​
15} // namespace margelo::nitro::t3highlights
16​
17namespace margelo::nitro {
18​
19// Hermes' own utf8() is several times slower than this for strings it stores as
20// UTF-16, which is any string with one non-ASCII character in it.
21template <>
22struct JSIConverter<t3highlights::SourceText> final {
23 static inline t3highlights::SourceText fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
24 t3highlights::SourceText source;
25 auto read = [&source](bool ascii, const void* data, size_t length) {
26 if (ascii) {
27 source.utf8.append(static_cast<const char*>(data), length);
28 } else {
29 t3highlights::appendUtf16AsUtf8(source.utf8, static_cast<const char16_t*>(data), length);
30 }
31 };
32 arg.asString(runtime).getStringData(runtime, read);
33 return source;
34 }
35 static inline jsi::Value toJSI(jsi::Runtime& runtime, const t3highlights::SourceText& arg) {
36 return jsi::String::createFromUtf8(runtime, arg.utf8);
37 }
38 static inline bool canConvert(jsi::Runtime&, const jsi::Value& value) {
39 return value.isString();
40 }
41};
42​
43} // namespace margelo::nitro