ion/string/
external.rs

1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 */
6
7use std::ffi::c_void;
8
9use mozjs::glue::{CreateJSExternalStringCallbacks, JSExternalStringCallbacksTraps};
10use mozjs::jsapi::JSExternalStringCallbacks;
11
12mod latin1 {
13	use std::ffi::c_void;
14
15	use mozjs::jsapi::MallocSizeOf;
16
17	use crate::utils::BoxExt as _;
18
19	pub(crate) unsafe extern "C" fn finalise(data: *const c_void, chars: *mut u8) {
20		let _ = unsafe { Box::from_raw_parts(chars, data as usize) };
21	}
22
23	pub(crate) extern "C" fn size_of(data: *const c_void, _: *const u8, _: MallocSizeOf) -> usize {
24		data as usize
25	}
26}
27
28mod utf16 {
29	use std::ffi::c_void;
30
31	use mozjs::jsapi::MallocSizeOf;
32
33	use crate::utils::BoxExt as _;
34
35	pub(crate) unsafe extern "C" fn finalise(data: *const c_void, chars: *mut u16) {
36		let _ = unsafe { Box::from_raw_parts(chars.cast::<u8>(), data as usize * 2) };
37	}
38
39	pub(crate) extern "C" fn size_of(data: *const c_void, _: *const u16, _: MallocSizeOf) -> usize {
40		data as usize
41	}
42}
43
44static EXTERNAL_STRING_CALLBACKS_TRAPS: JSExternalStringCallbacksTraps = JSExternalStringCallbacksTraps {
45	latin1Finalize: Some(latin1::finalise),
46	latin1SizeOfBuffer: Some(latin1::size_of),
47	utf16Finalize: Some(utf16::finalise),
48	utf16SizeOfBuffer: Some(utf16::size_of),
49};
50
51pub(super) fn create_callbacks(len: usize) -> *mut JSExternalStringCallbacks {
52	unsafe { CreateJSExternalStringCallbacks(&raw const EXTERNAL_STRING_CALLBACKS_TRAPS, len as *mut c_void) }
53}