thymeleaf 0.1.0-beta.1

A framework-neutral Thymeleaf-compatible dynamic template engine for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::sync::{Arc, OnceLock, RwLock, RwLockReadGuard, RwLockWriteGuard};

use crate::templatemode::TemplateMode;
use crate::util::{Utf16String, case_fold_unit};

use super::{ElementName, ElementNameError, HTMLElementName, TextElementName, XMLElementName};

static HTML_REPOSITORY: OnceLock<RwLock<ElementNamesRepository>> = OnceLock::new();
static XML_REPOSITORY: OnceLock<RwLock<ElementNamesRepository>> = OnceLock::new();
static TEXT_REPOSITORY: OnceLock<RwLock<ElementNamesRepository>> = OnceLock::new();

/// `ElementNames` 返回的具体名称子类。
#[derive(Clone)]
/// 对应 Java 语义:`ElementNames` 的 Rust 侧类型 `ElementNameValue`。
pub enum ElementNameValue {
    /// HTML 名称。
    Html(Arc<HTMLElementName>),
    /// XML 名称。
    Xml(Arc<XMLElementName>),
    /// TEXT/JAVASCRIPT/CSS 名称。
    Text(Arc<TextElementName>),
}

impl ElementNameValue {
    /// 返回统一的 `ElementName` 基类视图。
    #[must_use]
    /// 对应 Java 语义:`ElementNames` 的 `as_element_name` 行为(Rust 侧辅助/私有路径)。
    pub fn as_element_name(&self) -> &ElementName {
        match self {
            Self::Html(value) => value.as_element_name(),
            Self::Xml(value) => value.as_element_name(),
            Self::Text(value) => value.as_element_name(),
        }
    }
}

/// 元素名称规范化或 repository 访问错误。
#[derive(Clone, Debug, Eq, PartialEq)]
/// 对应 Java 语义:`ElementNames` 的 Rust 侧类型 `ElementNamesError`。
pub enum ElementNamesError {
    /// 指定参数违反公开方法的 null/空规则。
    IllegalArgument(&'static str),
    /// UTF-16 buffer 范围非法。
    StringIndexOutOfBounds {
        /// 起始位置。
        offset: i32,
        /// 长度。
        length: i32,
        /// buffer 长度。
        buffer_length: usize,
    },
    /// RAW 不是结构化元素名称模式。
    UnknownTemplateMode(TemplateMode),
    /// 具体名称对象构造失败。
    ElementName(ElementNameError),
    /// 插入第二个 complete alias 时遇到已有 repository 项。
    RepositoryAliasCollision,
}

impl ElementNamesError {
    /// 返回对应 Java 异常全限定名。
    #[must_use]
    pub const fn class_name(&self) -> &'static str {
        match self {
            Self::IllegalArgument(_)
            | Self::UnknownTemplateMode(_)
            | Self::ElementName(ElementNameError::InvalidElementName) => {
                "java.lang.IllegalArgumentException"
            }
            Self::StringIndexOutOfBounds { .. } => "java.lang.StringIndexOutOfBoundsException",
            Self::ElementName(error) => error.class_name(),
            Self::RepositoryAliasCollision => "java.lang.IndexOutOfBoundsException",
        }
    }
}

impl Display for ElementNamesError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::IllegalArgument(message) => formatter.write_str(message),
            Self::StringIndexOutOfBounds {
                offset,
                length,
                buffer_length,
            } => write!(
                formatter,
                "offset {offset}, count {length}, length {buffer_length}"
            ),
            Self::UnknownTemplateMode(mode) => {
                write!(formatter, "Unknown template mode '{mode}'")
            }
            Self::ElementName(error) => Display::fmt(error, formatter),
            Self::RepositoryAliasCollision => {
                formatter.write_str("repository alias already exists")
            }
        }
    }
}

impl Error for ElementNamesError {}

impl From<ElementNameError> for ElementNamesError {
    fn from(value: ElementNameError) -> Self {
        Self::ElementName(value)
    }
}

/// 按 TemplateMode 规范化并复用元素名称的线程安全入口。
///
/// 对应 Java: `org.thymeleaf.engine.ElementNames`。
///
/// 三个静态 repository 分别服务 HTML、XML 与所有文本模式,同一 complete name
/// 的重复查询返回同一个 `Arc`,复现 Java 缓存对象身份。
pub struct ElementNames;

impl ElementNames {
    /// 从 UTF-16 buffer 子范围解析任意结构化模板模式的元素名。
    ///
    /// # 错误
    ///
    /// null mode、非法输入范围、RAW 模式或具体名称校验失败时返回对应 Java 错误。
    pub fn for_name_buffer(
        template_mode: Option<TemplateMode>,
        buffer: Option<&[u16]>,
        offset: i32,
        length: i32,
    ) -> Result<ElementNameValue, ElementNamesError> {
        let mode = require_mode(template_mode)?;
        if mode == TemplateMode::RAW {
            return Err(ElementNamesError::UnknownTemplateMode(mode));
        }
        let text = checked_buffer(buffer, offset, length, mode.is_text())?;
        Self::for_name(Some(mode), Some(&Utf16String::from_utf16(text.to_vec())))
    }

    /// 从完整 Java String 解析任意结构化模板模式的元素名。
    /// 对应 Java: `ElementNames#forName()`。
    pub fn for_name(
        template_mode: Option<TemplateMode>,
        element_name: Option<&Utf16String>,
    ) -> Result<ElementNameValue, ElementNamesError> {
        let mode = require_mode(template_mode)?;
        match mode {
            TemplateMode::HTML => Self::for_html_name(element_name).map(ElementNameValue::Html),
            TemplateMode::XML => Self::for_xml_name(element_name).map(ElementNameValue::Xml),
            mode if mode.is_text() => Self::for_text_name(element_name).map(ElementNameValue::Text),
            mode => Err(ElementNamesError::UnknownTemplateMode(mode)),
        }
    }

    /// 从显式 prefix 与本地名解析任意结构化模板模式的元素名。
    /// 对应 Java 语义:`ElementNames` 的 `for_name_with_prefix` 行为(Rust 侧辅助/私有路径)。
    pub fn for_name_with_prefix(
        template_mode: Option<TemplateMode>,
        prefix: Option<&Utf16String>,
        element_name: Option<&Utf16String>,
    ) -> Result<ElementNameValue, ElementNamesError> {
        let mode = require_mode(template_mode)?;
        match mode {
            TemplateMode::HTML => {
                Self::for_html_name_with_prefix(prefix, element_name).map(ElementNameValue::Html)
            }
            TemplateMode::XML => {
                Self::for_xml_name_with_prefix(prefix, element_name).map(ElementNameValue::Xml)
            }
            mode if mode.is_text() => {
                Self::for_text_name_with_prefix(prefix, element_name).map(ElementNameValue::Text)
            }
            mode => Err(ElementNamesError::UnknownTemplateMode(mode)),
        }
    }

    /// 解析并缓存文本模式元素名;空字符串合法。
    /// 对应 Java: `ElementNames#forTextName()`。
    pub fn for_text_name(
        element_name: Option<&Utf16String>,
    ) -> Result<Arc<TextElementName>, ElementNamesError> {
        let element_name = element_name.ok_or(ElementNamesError::IllegalArgument(
            "Name cannot be null or empty",
        ))?;
        match repository_get_or_store(TemplateMode::TEXT, element_name, || {
            build_text(element_name)
        })? {
            ElementNameValue::Text(value) => Ok(value),
            _ => unreachable!("text repository contains only text names"),
        }
    }

    /// 解析并缓存 XML 元素名。
    /// 对应 Java 语义:`ElementNames` 的 `for_xml_name` 行为(Rust 侧辅助/私有路径)。
    pub fn for_xml_name(
        element_name: Option<&Utf16String>,
    ) -> Result<Arc<XMLElementName>, ElementNamesError> {
        let element_name = require_non_blank_name(element_name)?;
        match repository_get_or_store(TemplateMode::XML, element_name, || build_xml(element_name))?
        {
            ElementNameValue::Xml(value) => Ok(value),
            _ => unreachable!("xml repository contains only xml names"),
        }
    }

    /// 解析并缓存 HTML 元素名。
    /// 对应 Java 语义:`ElementNames` 的 `for_html_name` 行为(Rust 侧辅助/私有路径)。
    pub fn for_html_name(
        element_name: Option<&Utf16String>,
    ) -> Result<Arc<HTMLElementName>, ElementNamesError> {
        let element_name = require_non_blank_name(element_name)?;
        match repository_get_or_store(TemplateMode::HTML, element_name, || {
            build_html(element_name)
        })? {
            ElementNameValue::Html(value) => Ok(value),
            _ => unreachable!("html repository contains only html names"),
        }
    }

    /// 使用显式 prefix 解析文本模式元素名。
    /// 对应 Java 语义:`ElementNames` 的 `for_text_name_with_prefix` 行为(Rust 侧辅助/私有路径)。
    pub fn for_text_name_with_prefix(
        prefix: Option<&Utf16String>,
        element_name: Option<&Utf16String>,
    ) -> Result<Arc<TextElementName>, ElementNamesError> {
        let element_name = element_name.ok_or(ElementNamesError::IllegalArgument(
            "Name cannot be null (nor empty if prefix is not empty)",
        ))?;
        if trim_is_empty(element_name) && has_non_blank_prefix(prefix) {
            return Err(ElementNamesError::IllegalArgument(
                "Name cannot be null (nor empty if prefix is not empty)",
            ));
        }
        if !has_non_blank_prefix(prefix) {
            return Self::for_text_name(Some(element_name));
        }
        let lookup = namespaced(prefix.expect("non-blank prefix"), element_name);
        match repository_get_or_store(TemplateMode::TEXT, &lookup, || {
            Ok(ElementNameValue::Text(Arc::new(TextElementName::for_name(
                prefix.cloned(),
                Some(element_name.clone()),
            )?)))
        })? {
            ElementNameValue::Text(value) => Ok(value),
            _ => unreachable!("text repository contains only text names"),
        }
    }

    /// 使用显式 prefix 解析 XML 元素名。
    /// 对应 Java 语义:`ElementNames` 的 `for_xml_name_with_prefix` 行为(Rust 侧辅助/私有路径)。
    pub fn for_xml_name_with_prefix(
        prefix: Option<&Utf16String>,
        element_name: Option<&Utf16String>,
    ) -> Result<Arc<XMLElementName>, ElementNamesError> {
        let element_name = require_non_blank_name(element_name)?;
        if !has_non_blank_prefix(prefix) {
            return Self::for_xml_name(Some(element_name));
        }
        let lookup = namespaced(prefix.expect("non-blank prefix"), element_name);
        match repository_get_or_store(TemplateMode::XML, &lookup, || {
            Ok(ElementNameValue::Xml(Arc::new(XMLElementName::for_name(
                prefix.cloned(),
                Some(element_name.clone()),
            )?)))
        })? {
            ElementNameValue::Xml(value) => Ok(value),
            _ => unreachable!("xml repository contains only xml names"),
        }
    }

    /// 使用显式 prefix 解析 HTML 元素名。
    /// 对应 Java 语义:`ElementNames` 的 `for_html_name_with_prefix` 行为(Rust 侧辅助/私有路径)。
    pub fn for_html_name_with_prefix(
        prefix: Option<&Utf16String>,
        element_name: Option<&Utf16String>,
    ) -> Result<Arc<HTMLElementName>, ElementNamesError> {
        let element_name = require_non_blank_name(element_name)?;
        if !has_non_blank_prefix(prefix) {
            return Self::for_html_name(Some(element_name));
        }
        let lookup = namespaced(prefix.expect("non-blank prefix"), element_name);
        match repository_get_or_store(TemplateMode::HTML, &lookup, || {
            Ok(ElementNameValue::Html(Arc::new(HTMLElementName::for_name(
                prefix.cloned(),
                Some(element_name.clone()),
            )?)))
        })? {
            ElementNameValue::Html(value) => Ok(value),
            _ => unreachable!("html repository contains only html names"),
        }
    }
}

struct ElementNamesRepository {
    values: HashMap<Vec<u16>, ElementNameValue>,
}

fn repository_get_or_store(
    mode: TemplateMode,
    lookup: &Utf16String,
    builder: impl FnOnce() -> Result<ElementNameValue, ElementNamesError>,
) -> Result<ElementNameValue, ElementNamesError> {
    let repository = repository(mode);
    let key = repository_key(mode, lookup);
    if let Some(value) = read_recovering_poison(repository).values.get(&key) {
        return Ok(value.clone());
    }
    let mut repository = write_recovering_poison(repository);
    if let Some(value) = repository.values.get(&key) {
        return Ok(value.clone());
    }
    let value = builder()?;
    let names = value.as_element_name().get_complete_element_names();
    let names = read_recovering_poison(&names).clone();
    let mut keys = Vec::with_capacity(names.len());
    for name in names.into_iter().flatten() {
        let alias = repository_key(mode, &name);
        // 对应 Java `ElementNamesRepository` 的首注册者胜语义:任何 complete name 键
        // 已被不同对象占用时,返回既有绑定(Java 读路径 short-circuit),keep-first。
        if let Some(existing) = repository.values.get(&alias) {
            return Ok(existing.clone());
        }
        keys.push(alias);
    }
    for alias in keys {
        repository.values.insert(alias, value.clone());
    }
    Ok(value)
}

fn repository(mode: TemplateMode) -> &'static RwLock<ElementNamesRepository> {
    let slot = match mode {
        TemplateMode::HTML => &HTML_REPOSITORY,
        TemplateMode::XML => &XML_REPOSITORY,
        _ => &TEXT_REPOSITORY,
    };
    slot.get_or_init(|| {
        RwLock::new(ElementNamesRepository {
            values: HashMap::with_capacity(500),
        })
    })
}

fn repository_key(mode: TemplateMode, value: &Utf16String) -> Vec<u16> {
    if mode.is_case_sensitive() {
        value.as_utf16().to_vec()
    } else {
        value
            .as_utf16()
            .iter()
            .map(|unit| case_fold_unit(*unit))
            .collect()
    }
}

fn build_text(name: &Utf16String) -> Result<ElementNameValue, ElementNamesError> {
    let (prefix, local) = split_first(name, &[u16::from(b':')], false);
    Ok(ElementNameValue::Text(Arc::new(TextElementName::for_name(
        prefix,
        Some(local),
    )?)))
}

fn build_xml(name: &Utf16String) -> Result<ElementNameValue, ElementNamesError> {
    let (prefix, local) = split_first(name, &[u16::from(b':')], false);
    Ok(ElementNameValue::Xml(Arc::new(XMLElementName::for_name(
        prefix,
        Some(local),
    )?)))
}

fn build_html(name: &Utf16String) -> Result<ElementNameValue, ElementNamesError> {
    let units = name.as_utf16();
    let split = units.iter().position(|unit| matches!(*unit, 0x3a | 0x2d));
    let (prefix, local) = match split {
        Some(0) | None => (None, name.clone()),
        Some(index) if units[index] == u16::from(b':') => {
            let candidate = &units[..=index];
            if equals_ascii_ignore_case(candidate, "xml:")
                || equals_ascii_ignore_case(candidate, "xmlns:")
            {
                (None, name.clone())
            } else {
                (
                    Some(Utf16String::from_utf16(units[..index].to_vec())),
                    Utf16String::from_utf16(units[index + 1..].to_vec()),
                )
            }
        }
        Some(index) => (
            Some(Utf16String::from_utf16(units[..index].to_vec())),
            Utf16String::from_utf16(units[index + 1..].to_vec()),
        ),
    };
    Ok(ElementNameValue::Html(Arc::new(HTMLElementName::for_name(
        prefix,
        Some(local),
    )?)))
}

fn split_first(
    name: &Utf16String,
    separators: &[u16],
    _unused: bool,
) -> (Option<Utf16String>, Utf16String) {
    let units = name.as_utf16();
    match units.iter().position(|unit| separators.contains(unit)) {
        Some(0) | None => (None, name.clone()),
        Some(index) => (
            Some(Utf16String::from_utf16(units[..index].to_vec())),
            Utf16String::from_utf16(units[index + 1..].to_vec()),
        ),
    }
}

fn require_mode(mode: Option<TemplateMode>) -> Result<TemplateMode, ElementNamesError> {
    mode.ok_or(ElementNamesError::IllegalArgument(
        "Template Mode cannot be null",
    ))
}

fn require_non_blank_name(name: Option<&Utf16String>) -> Result<&Utf16String, ElementNamesError> {
    let name = name.ok_or(ElementNamesError::IllegalArgument(
        "Name cannot be null or empty",
    ))?;
    if trim_is_empty(name) {
        return Err(ElementNamesError::IllegalArgument(
            "Name cannot be null or empty",
        ));
    }
    Ok(name)
}

fn checked_buffer(
    buffer: Option<&[u16]>,
    offset: i32,
    length: i32,
    allow_empty: bool,
) -> Result<&[u16], ElementNamesError> {
    let buffer = buffer.ok_or(ElementNamesError::IllegalArgument(
        "Name cannot be null or empty",
    ))?;
    if (!allow_empty && length == 0) || offset < 0 || length < 0 {
        return Err(ElementNamesError::IllegalArgument(if length == 0 {
            "Name cannot be null or empty"
        } else {
            "Both name offset and length must be equal to or greater than zero"
        }));
    }
    let start = usize::try_from(offset).unwrap_or(usize::MAX);
    let count = usize::try_from(length).unwrap_or(usize::MAX);
    if start > buffer.len() || count > buffer.len().saturating_sub(start) {
        return Err(ElementNamesError::StringIndexOutOfBounds {
            offset,
            length,
            buffer_length: buffer.len(),
        });
    }
    Ok(&buffer[start..start + count])
}

fn trim_is_empty(value: &Utf16String) -> bool {
    value.as_utf16().iter().all(|unit| *unit <= 0x20)
}

fn has_non_blank_prefix(prefix: Option<&Utf16String>) -> bool {
    prefix.is_some_and(|value| !trim_is_empty(value))
}

fn namespaced(prefix: &Utf16String, name: &Utf16String) -> Utf16String {
    let mut result = prefix.as_utf16().to_vec();
    result.push(u16::from(b':'));
    result.extend_from_slice(name.as_utf16());
    Utf16String::from_utf16(result)
}

fn equals_ascii_ignore_case(value: &[u16], expected: &str) -> bool {
    value.len() == expected.len()
        && value
            .iter()
            .zip(expected.bytes())
            .all(|(actual, expected)| {
                case_fold_unit(*actual) == case_fold_unit(u16::from(expected))
            })
}

fn read_recovering_poison<T>(lock: &RwLock<T>) -> RwLockReadGuard<'_, T> {
    lock.read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

fn write_recovering_poison<T>(lock: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
    lock.write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}