Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
//! The code a script, module or function was compiled from, which functions keep to compile themselves lazily and to
//! recover their [[SourceText]].
use std::rc::Rc;
use std::sync::Arc;
use ak::Utf16String;
use crate::source_text::SourceText;
use crate::utf16::Utf16View;
pub struct SourceCode {
filename: Utf16String,
code: Arc<SourceText>,
}
impl SourceCode {
pub fn create(filename: Utf16String, code: Utf16String) -> Rc<SourceCode> {
Rc::new(Self {
filename,
code: SourceText::of(&code),
})
}
/// Source code under `filename` that shares the code of `other`, parked or not.
pub fn create_sharing_code(filename: Utf16String, other: &SourceCode) -> Rc<SourceCode> {
Rc::new(Self {
filename,
code: Arc::clone(&other.code),
})
}
pub fn filename(&self) -> &Utf16String {
&self.filename
}
/// The code, which is decompressed first if nothing asked for it in a while (see [`SourceText`]).
pub fn code(&self) -> Utf16String {
self.code.get()
}
pub fn length_in_code_units(&self) -> usize {
self.code.length_in_code_units()
}
pub fn source_text_from_offsets(&self, start_offset: usize, length: usize) -> Utf16String {
if length == 0 {
return Utf16String::default();
}
assert!(start_offset <= usize::MAX - length);
Utf16View::of_string(&self.code.get())
.substring_view(start_offset, length)
.to_utf16_string()
}
}