Skip to main content

ftml/tree/
clone.rs

1/*
2 * tree/clone.rs
3 *
4 * ftml - Library to parse Wikidot text
5 * Copyright (C) 2019-2026 Wikijump Team
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16 *
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21//! Utilities to help convert tree structures into owned versions.
22//!
23//! `SyntaxTree` and its child structures use `Cow` to enable both
24//! serialization and deserialization.
25//!
26//! However if you need to convert a referenced version into an owned
27//! version, that requires traversing all the child structures and
28//! using `to_owned()`.
29//!
30//! This module has helpers to make this process easier.
31
32use super::element::Element;
33use super::list::ListItem;
34use ref_map::*;
35use std::borrow::Cow;
36use std::collections::HashMap;
37
38#[inline]
39pub fn option_string_to_owned(
40    option_string: &Option<Cow<'_, str>>,
41) -> Option<Cow<'static, str>> {
42    option_string.ref_map(|s| string_to_owned(s))
43}
44
45#[inline]
46pub fn string_to_owned(string: &str) -> Cow<'static, str> {
47    Cow::Owned(str!(string))
48}
49
50pub fn elements_to_owned(elements: &[Element<'_>]) -> Vec<Element<'static>> {
51    elements.iter().map(|element| element.to_owned()).collect()
52}
53
54pub fn elements_lists_to_owned(
55    element_lists: &[Vec<Element<'_>>],
56) -> Vec<Vec<Element<'static>>> {
57    element_lists
58        .iter()
59        .map(|elements| elements_to_owned(elements.as_slice()))
60        .collect()
61}
62
63pub fn list_items_to_owned(list_items: &[ListItem<'_>]) -> Vec<ListItem<'static>> {
64    list_items
65        .iter()
66        .map(|list_item| list_item.to_owned())
67        .collect()
68}
69
70pub fn string_map_to_owned(
71    map: &HashMap<Cow<'_, str>, Cow<'_, str>>,
72) -> HashMap<Cow<'static, str>, Cow<'static, str>> {
73    map.iter()
74        .map(|(key, value)| {
75            let key = string_to_owned(key);
76            let value = string_to_owned(value);
77
78            (key, value)
79        })
80        .collect()
81}