Skip to main content

kobo_core/rendering/
common.rs

1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 Nayeem Bin Ahsan
3//! Shared rendering state and constants.
4
5use std::sync::atomic::{AtomicBool, Ordering};
6
7static IS_RTL: AtomicBool = AtomicBool::new(false);
8
9pub fn set_rtl(rtl: bool) {
10    IS_RTL.store(rtl, Ordering::Relaxed);
11}
12
13pub fn is_rtl() -> bool {
14    IS_RTL.load(Ordering::Relaxed)
15}
16
17/// Whether a BCP-47 language code (e.g. "ar-SA", "en-US") resolves to an RTL
18/// script. Complements [`crate::rendering::text_render::Script::is_rtl`], which
19/// works on text content; this works on a declared language tag.
20pub fn lang_is_rtl(lang: Option<&str>) -> bool {
21    let prefix = lang
22        .and_then(|l| l.split('-').next())
23        .unwrap_or("")
24        .to_ascii_lowercase();
25    matches!(
26        prefix.as_str(),
27        "ar" | "ur" | "fa" | "he" | "yi" | "ps" | "sd"
28    )
29}
30
31pub const BODY_PX: f32 = 36.0;
32
33/// Reinterpret a slice of any type as a shared `&[u8]`.
34///
35/// SAFETY: the slice covers exactly `size_of_val(buf)` bytes starting at the
36/// same address. `u8` has no alignment requirement, so any `T` is valid.
37pub fn slice_as_bytes<T>(buf: &[T]) -> &[u8] {
38    unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, std::mem::size_of_val(buf)) }
39}
40
41/// Reinterpret a mutable slice of any type as a `&mut [u8]`.
42///
43/// SAFETY: same as [`slice_as_bytes`], but with an exclusive `&mut` borrow.
44pub fn slice_as_bytes_mut<T>(buf: &mut [T]) -> &mut [u8] {
45    unsafe {
46        std::slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u8, std::mem::size_of_val(buf))
47    }
48}