Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ bazel_dep(name = "platforms", version = "1.1.0")
# https://registry.bazel.build/modules/rules_cc
bazel_dep(name = "rules_cc", version = "0.2.0")

# https://registry.bazel.build/modules/rules_rust
bazel_dep(name = "rules_rust", version = "0.75.0")

# https://registry.bazel.build/modules/rules_shell
# Required by llvm-project's BUILD files.
bazel_dep(name = "rules_shell", version = "0.8.0")
Expand Down
13 changes: 13 additions & 0 deletions maldoca/js/ir/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ load("@llvm-project//mlir:tblgen.bzl", "gentbl_cc_library", "td_library")
load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
load("@rules_cc//cc:cc_library.bzl", "cc_library")
load("@rules_python//python:defs.bzl", "py_binary")
load("@rules_rust//rust:defs.bzl", "rust_static_library", "rust_test")
load("//maldoca/js:allowed_users.bzl", "JSIR_ALLOWED_USERS")

licenses(["notice"])
Expand Down Expand Up @@ -270,12 +271,24 @@ cc_library(
],
)

rust_static_library(
name = "utf16_rs",
srcs = ["utf16.rs"],
edition = "2021",
)

rust_test(
name = "utf16_rs_test",
crate = ":utf16_rs",
)

cc_library(
name = "utf16",
srcs = ["utf16.cc"],
hdrs = ["utf16.h"],
visibility = ["//maldoca/js:__subpackages__"],
deps = [
":utf16_rs",
"@abseil-cpp//absl/strings:string_view",
"@llvm-project//llvm:Support",
],
Expand Down
37 changes: 31 additions & 6 deletions maldoca/js/ir/utf16.cc
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

#include "maldoca/js/ir/utf16.h"

#include <cstddef>
#include <cstdint>
#include <string>
#include <string_view>

Expand All @@ -24,15 +26,38 @@
#include "absl/strings/string_view.h"

namespace maldoca {
namespace {

// LINT.IfChange(maldoca_utf8_to_utf16_lossy_ffi)
extern "C" {
size_t maldoca_utf8_to_utf16_lossy(const uint8_t* src, size_t src_len,
char16_t* dst, size_t dst_cap);
}
// LINT.ThenChange(utf16.rs:maldoca_utf8_to_utf16_lossy_ffi)

// Lossy UTF-8 -> UTF-16 decoding via Rust's `utf8_chunks()` (matching
// `String::from_utf8_lossy` and Node.js). Every UTF-8 byte produces at most
// one UTF-16 code unit, so `src.size()` is always a sufficient output bound.
std::u16string Utf8ToUtf16Lossy(absl::string_view src) {
std::u16string out(src.size(), u'\0');
size_t len =
maldoca_utf8_to_utf16_lossy(reinterpret_cast<const uint8_t*>(src.data()),
src.size(), out.data(), out.size());
out.resize(len);
return out;
}

} // namespace

std::u16string Utf8ToUtf16(absl::string_view src) {
llvm::StringRef src_ref(src.data(), src.size());
llvm::SmallVector<llvm::UTF16, 1024> dst;
if (!llvm::convertUTF8ToUTF16String(src_ref, dst)) {
return u"";
{
llvm::StringRef src_ref(src.data(), src.size());
llvm::SmallVector<llvm::UTF16, 1024> dst;
if (llvm::convertUTF8ToUTF16String(src_ref, dst)) {
return std::u16string(dst.begin(), dst.end());
}
}
return std::u16string(reinterpret_cast<const char16_t*>(dst.data()),
dst.size());
return Utf8ToUtf16Lossy(src);
}

std::string Utf16ToUtf8(std::u16string_view src) {
Expand Down
139 changes: 139 additions & 0 deletions maldoca/js/ir/utf16.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::mem::{self, MaybeUninit};
use std::slice;

/// Lossily decodes UTF-8 bytes into UTF-16 code units using Unicode
/// maximal-subpart `U+FFFD` replacement (matching `String::from_utf8_lossy`
/// and Node.js), writing at most `dst_cap` code units into `dst`.
///
/// Every UTF-8 byte produces at most one UTF-16 code unit, so `dst_cap >=
/// src_len` always suffices without truncation. When `dst_cap` is smaller,
/// decoding stops before writing a character whose UTF-16 encoding would not
/// fit (avoiding unpaired surrogates). Returns the number of UTF-16 code units
/// written.
///
/// # Safety
/// - If `src_len > 0`, `src` must be non-null and valid for reads of `src_len`
/// bytes, and `src_len <= isize::MAX as usize`.
/// - If `dst_cap > 0`, `dst` must be non-null, properly aligned for `u16`, and
/// valid for writes of `dst_cap` `u16`s (need not be initialized), with
/// `dst_cap <= (isize::MAX as usize) / mem::size_of::<u16>()`.
/// - `src` and `dst` must not overlap.
// LINT.IfChange(maldoca_utf8_to_utf16_lossy_ffi)
#[no_mangle]
pub unsafe extern "C" fn maldoca_utf8_to_utf16_lossy(
src: *const u8,
src_len: usize,
dst: *mut u16,
dst_cap: usize,
) -> usize {
// LINT.ThenChange(utf16.cc:maldoca_utf8_to_utf16_lossy_ffi)
if src_len == 0
|| src.is_null()
|| src_len > isize::MAX as usize
|| dst_cap == 0
|| dst.is_null()
|| !dst.is_aligned()
|| dst_cap > (isize::MAX as usize) / mem::size_of::<u16>()
{
return 0;
}
// SAFETY: Validated non-null, aligned, and within `isize::MAX` byte bounds
// above; caller guarantees read/write validity and non-overlap. Using
// `MaybeUninit<u16>` allows `dst` to point to uninitialized memory.
let input = unsafe { slice::from_raw_parts(src, src_len) };
let output = unsafe { slice::from_raw_parts_mut(dst.cast::<MaybeUninit<u16>>(), dst_cap) };

let mut written = 0;
let mut utf16_char_buf = [0u16; 2];
for chunk in input.utf8_chunks() {
for ch in chunk.valid().chars() {
let encoded = ch.encode_utf16(&mut utf16_char_buf);
if written + encoded.len() > output.len() {
return written;
}
for &u in encoded.iter() {
output[written].write(u);
written += 1;
}
}
if !chunk.invalid().is_empty() {
if written >= output.len() {
return written;
}
output[written].write(0xFFFD);
written += 1;
}
}
written
}

#[cfg(test)]
mod tests {
use super::*;

fn decode(bytes: &[u8]) -> Vec<u16> {
let mut out = vec![MaybeUninit::<u16>::uninit(); bytes.len()];
// SAFETY: `bytes` and `out` are valid, aligned, non-overlapping slices.
let n = unsafe {
maldoca_utf8_to_utf16_lossy(
bytes.as_ptr(),
bytes.len(),
out.as_mut_ptr().cast::<u16>(),
out.len(),
)
};
// SAFETY: `maldoca_utf8_to_utf16_lossy` initialized the first `n` slots.
out[..n].iter().map(|slot| unsafe { slot.assume_init() }).collect()
}

#[test]
fn test_lossy_latin1_and_surrogate_pair() {
let input = b"caf\xe9 \xc3\xa9 \xe4\xb8\xad \xf0\x9f\x98\x80";
let expected: Vec<u16> = "caf\u{FFFD} \u{00E9} \u{4E2D} \u{1F600}".encode_utf16().collect();
assert_eq!(decode(input), expected);
}

#[test]
fn test_truncated_sequences_maximal_subpart() {
assert_eq!(decode(b"\xc3"), vec![0xFFFD]);
assert_eq!(decode(b"\xe4\xb8"), vec![0xFFFD]);
assert_eq!(decode(b"\xf0\x9f\x98"), vec![0xFFFD]);
assert_eq!(decode(b"\xf0\x9f"), vec![0xFFFD]);
assert_eq!(decode(b"\xff\xff\xff"), vec![0xFFFD, 0xFFFD, 0xFFFD]);
}

#[test]
fn test_empty_small_cap_and_no_unpaired_surrogate() {
assert_eq!(decode(b""), Vec::<u16>::new());
let mut small = [0u16; 2];
// SAFETY: Valid non-overlapping buffers.
let n = unsafe { maldoca_utf8_to_utf16_lossy(b"abcd".as_ptr(), 4, small.as_mut_ptr(), 2) };
assert_eq!(n, 2);
assert_eq!(small, [b'a' as u16, b'b' as u16]);

// Capacity 2 for "a" (1 unit) + U+1F600 (2 units) must stop at 1 unit
// rather than emitting an unpaired high surrogate.
let emoji = "a\u{1F600}".as_bytes();
let mut buf = [0u16; 2];
// SAFETY: Valid non-overlapping buffers.
let written = unsafe {
maldoca_utf8_to_utf16_lossy(emoji.as_ptr(), emoji.len(), buf.as_mut_ptr(), buf.len())
};
assert_eq!(written, 1);
assert_eq!(buf[0], b'a' as u16);
}
}
Loading