Skip to main content

zumen_xml/
write.rs

1//! 元のバイト範囲だけを書き換える XML のトランザクション。
2
3mod encoding;
4
5use crate::{Document, Element, Encoding, Namespace, Node, name};
6use core::ops::Range;
7use encoding::{Writer, append};
8use zumen_base::{Code, Cx, Diagnostic, Error, Kind, Ref, codes};
9
10/// 追加する要素。属性と名前空間の宣言は、既存の親から変えない。
11#[derive(Clone, Debug, Default, PartialEq, Eq)]
12pub struct NewElement {
13    /// 接頭辞があれば含めた XML の名前。親で有効な名前空間を使う。
14    pub name: String,
15    /// 要素の初めに置く文字。文字参照にする前の値。
16    pub value: Option<String>,
17    /// 追加する子の要素。書く順。
18    pub children: Vec<NewElement>,
19}
20
21/// 元の文書の要素番号で指定する変更。同じ親への追加は指定の順に書く。
22#[derive(Clone, Copy, Debug)]
23pub enum Edit<'a> {
24    /// 子の要素を持たない項目の文字を置き換える。注記と処理命令は保つ。
25    SetText {
26        /// 元の文書の要素番号。
27        element: u64,
28        /// 文字参照にする前の値。
29        value: &'a str,
30    },
31    /// 親の末尾に要素を足す。
32    Append {
33        /// 元の文書の親の番号。
34        element: u64,
35        /// 追加する木。
36        child: &'a NewElement,
37    },
38}
39
40impl Edit<'_> {
41    fn element(&self) -> u64 {
42        match self {
43            Self::SetText { element, .. } | Self::Append { element, .. } => *element,
44        }
45    }
46}
47
48struct Patch {
49    range: Range<usize>,
50    bytes: Vec<u8>,
51}
52
53/// 指定した文字と挿入箇所だけを書き換える。文字コード・BOM・宣言・それ以外のバイトを保つ。
54/// 失敗時は何も返さず、元の文書は変えない。DTD と外部の実体は解決しない。
55pub fn write(doc: &Document, edits: &[Edit<'_>], cx: &mut Cx<'_>) -> Result<Vec<u8>, Error> {
56    let at = Ref::at_bytes(0, doc.src().len() as u64);
57    let writer = Writer::new(doc, cx, &at)?;
58    spend(cx, Kind::Work, (edits.len() as u64).saturating_mul(64), &at)?;
59    spend(
60        cx,
61        Kind::DecodedBytes,
62        (edits.len() as u64).saturating_mul(64),
63        &at,
64    )?;
65    let mut order: Vec<_> = edits.iter().enumerate().collect();
66    order.sort_unstable_by_key(|(index, edit)| (edit.element(), *index));
67    let mut patches = Vec::new();
68    for group in order.chunk_by(|a, b| a.1.element() == b.1.element()) {
69        let Some((_, first)) = group.first() else {
70            continue;
71        };
72        let number = first.element();
73        let Some(element) = usize::try_from(number).ok().and_then(|n| doc.element(n)) else {
74            cx.report(Diagnostic::new(codes::XML_EDIT_TARGET_MISSING).with("index", number));
75            return Err(Error::Rejected);
76        };
77        let at = place(element);
78        match first {
79            Edit::SetText { value, .. } if group.len() == 1 => {
80                replace(doc, element, value, &writer, &mut patches, cx)?
81            }
82            Edit::SetText { .. } => return Err(invalid(cx, codes::XML_EDIT_RANGE_INVALID, &at)),
83            Edit::Append { .. } => {
84                let mut bytes = Vec::new();
85                let closing = closing(doc, element, &writer, cx)?;
86                let indentation = indentation(doc, element, closing.start, &writer, cx)?;
87                let mut insert_at = closing.start;
88                if let Some((position, _)) = &indentation {
89                    insert_at = *position;
90                }
91                for (_, edit) in group {
92                    let Edit::Append { child, .. } = edit else {
93                        return Err(invalid(cx, codes::XML_EDIT_RANGE_INVALID, &at));
94                    };
95                    if let Some((_, indent)) = &indentation {
96                        append(&mut bytes, indent, cx, &at)?;
97                    }
98                    new_element(doc, element, child, &writer, &mut bytes, cx)?;
99                    if indentation.is_some() {
100                        writer.push(&mut bytes, writer.newline, cx, &at)?;
101                    }
102                }
103                if closing.end > closing.start {
104                    let mut expanded = writer.encode(">", cx, &at)?;
105                    append(&mut expanded, &bytes, cx, &at)?;
106                    close_tag(doc, element, &writer, &mut expanded, cx)?;
107                    patch(&mut patches, closing, expanded, cx, &at)?;
108                } else {
109                    patch(&mut patches, insert_at..insert_at, bytes, cx, &at)?;
110                }
111            }
112        }
113    }
114    spend(
115        cx,
116        Kind::Work,
117        (patches.len() as u64).saturating_mul(64),
118        &at,
119    )?;
120    patches.sort_unstable_by_key(|patch| (patch.range.start, patch.range.end));
121    let mut end = 0;
122    let mut length = doc.src().len() as u64;
123    for patch in &patches {
124        if patch.range.start < end {
125            return Err(invalid(cx, codes::XML_EDIT_RANGE_INVALID, &at));
126        }
127        end = patch.range.end;
128        length = length
129            .saturating_sub(patch.range.len() as u64)
130            .saturating_add(patch.bytes.len() as u64);
131    }
132    spend(cx, Kind::DecodedBytes, length, &at)?;
133    spend(cx, Kind::Work, length, &at)?;
134    let capacity =
135        usize::try_from(length).map_err(|_| invalid(cx, codes::XML_WRITE_FAILED, &at))?;
136    let mut output = Vec::new();
137    output
138        .try_reserve_exact(capacity)
139        .map_err(|_| invalid(cx, codes::XML_WRITE_FAILED, &at))?;
140    let mut cursor = 0;
141    for patch in patches {
142        output.extend_from_slice(
143            doc.src()
144                .get(cursor..patch.range.start)
145                .ok_or_else(|| invalid(cx, codes::XML_EDIT_RANGE_INVALID, &at))?,
146        );
147        output.extend_from_slice(&patch.bytes);
148        cursor = patch.range.end;
149    }
150    output.extend_from_slice(
151        doc.src()
152            .get(cursor..)
153            .ok_or_else(|| invalid(cx, codes::XML_EDIT_RANGE_INVALID, &at))?,
154    );
155    spend(cx, Kind::Work, 0, &at)?;
156    Ok(output)
157}
158
159fn patch(
160    patches: &mut Vec<Patch>,
161    range: Range<usize>,
162    bytes: Vec<u8>,
163    cx: &mut Cx<'_>,
164    at: &Ref,
165) -> Result<(), Error> {
166    spend(cx, Kind::DecodedBytes, 64, at)?;
167    patches.push(Patch { range, bytes });
168    Ok(())
169}
170
171/// 空要素なら / から末尾まで、通常の要素なら終了タグの初めの空範囲。
172fn closing(
173    doc: &Document,
174    element: &Element,
175    writer: &Writer,
176    cx: &mut Cx<'_>,
177) -> Result<Range<usize>, Error> {
178    let span = element.span();
179    spend(cx, Kind::Work, span.len() as u64, &place(element))?;
180    let width = writer.width();
181    if writer.ascii(doc.src(), span.end - 2 * width) == Some(b'/') {
182        return Ok(span.end - 2 * width..span.end);
183    }
184    let mut index = span.end - width;
185    while index > span.start {
186        if writer.ascii(doc.src(), index) == Some(b'<') {
187            return Ok(index..index);
188        }
189        index -= width;
190    }
191    Err(invalid(cx, codes::XML_EDIT_RANGE_INVALID, &place(element)))
192}
193
194fn close_tag(
195    doc: &Document,
196    element: &Element,
197    writer: &Writer,
198    out: &mut Vec<u8>,
199    cx: &mut Cx<'_>,
200) -> Result<(), Error> {
201    let at = place(element);
202    writer.push(out, "</", cx, &at)?;
203    append(out, doc.bytes(element.name().raw()), cx, &at)?;
204    writer.push(out, ">", cx, &at)
205}
206
207fn replace(
208    doc: &Document,
209    element: &Element,
210    value: &str,
211    writer: &Writer,
212    patches: &mut Vec<Patch>,
213    cx: &mut Cx<'_>,
214) -> Result<(), Error> {
215    let at = place(element);
216    spend(cx, Kind::Work, element.children().len() as u64, &at)?;
217    if element
218        .children()
219        .iter()
220        .any(|node| matches!(node, Node::Element(_)))
221    {
222        return Err(invalid(cx, codes::XML_EDIT_CHILDREN_UNSUPPORTED, &at));
223    }
224    let mut value = Some(writer.text(value, cx, &at)?);
225    let closing = closing(doc, element, writer, cx)?;
226    if closing.end > closing.start {
227        let mut expanded = writer.encode(">", cx, &at)?;
228        append(&mut expanded, value.as_deref().unwrap_or_default(), cx, &at)?;
229        close_tag(doc, element, writer, &mut expanded, cx)?;
230        return patch(patches, closing, expanded, cx, &at);
231    }
232    for node in element.children() {
233        let range = match node {
234            Node::Text(range) => range.clone(),
235            Node::CData(range) => range.start - 9 * writer.width()..range.end + 3 * writer.width(),
236            Node::Element(_) => continue,
237        };
238        patch(patches, range, value.take().unwrap_or_default(), cx, &at)?;
239    }
240    if let Some(value) = value {
241        patch(patches, closing, value, cx, &at)?;
242    }
243    Ok(())
244}
245
246fn indentation(
247    doc: &Document,
248    element: &Element,
249    closing: usize,
250    writer: &Writer,
251    cx: &mut Cx<'_>,
252) -> Result<Option<(usize, Vec<u8>)>, Error> {
253    let at = place(element);
254    spend(cx, Kind::Work, (closing - element.span().start) as u64, &at)?;
255    let line = |end: usize| {
256        let mut start = end;
257        while start > element.span().start {
258            let before = start - writer.width();
259            match writer.ascii(doc.src(), before) {
260                Some(b'\n' | b'\r') => return Some(start),
261                Some(b' ' | b'\t') => start = before,
262                _ => return None,
263            }
264        }
265        None
266    };
267    let Some(start) = line(closing) else {
268        return Ok(None);
269    };
270    for child in element.children() {
271        if let Node::Element(index) = child
272            && let Some(child) = doc.element(*index)
273            && let Some(child_start) = line(child.span().start)
274        {
275            let raw = doc.bytes(child_start..child.span().start);
276            spend(cx, Kind::DecodedBytes, raw.len() as u64, &at)?;
277            return Ok(Some((start, raw.to_vec())));
278        }
279    }
280    let mut indent = Vec::new();
281    append(&mut indent, doc.bytes(start..closing), cx, &at)?;
282    writer.push(&mut indent, "  ", cx, &at)?;
283    Ok(Some((start, indent)))
284}
285
286fn namespace<'a>(
287    doc: &'a Document,
288    mut parent: Option<&'a Element>,
289    prefix: &str,
290    cx: &mut Cx<'_>,
291    at: &Ref,
292) -> Result<bool, Error> {
293    // Namespaces in XML 1.0 §6.1: https://www.w3.org/TR/xml-names/#scoping
294    if prefix == "xml" {
295        return Ok(true);
296    }
297    if prefix == "xmlns" {
298        return Ok(false);
299    }
300    while let Some(element) = parent {
301        spend(cx, Kind::Work, 1, at)?;
302        for attribute in element.attributes() {
303            spend(cx, Kind::Work, 1, at)?;
304            if attribute.name().namespace() != Some(&Namespace::Xmlns)
305                || attribute.name().prefix().is_none()
306            {
307                continue;
308            }
309            let raw = attribute.name().local();
310            spend(cx, Kind::Work, raw.len() as u64, at)?;
311            spend(
312                cx,
313                Kind::DecodedBytes,
314                (raw.len() as u64).saturating_mul(6),
315                at,
316            )?;
317            if doc.cdata(raw) == prefix {
318                let raw = attribute.raw();
319                spend(cx, Kind::Work, raw.len() as u64, at)?;
320                spend(
321                    cx,
322                    Kind::DecodedBytes,
323                    (raw.len() as u64).saturating_mul(6),
324                    at,
325                )?;
326                return Ok(!doc.value(attribute).is_empty());
327            }
328        }
329        parent = element.parent().and_then(|index| doc.element(index));
330    }
331    Ok(false)
332}
333
334fn new_element(
335    doc: &Document,
336    parent: &Element,
337    child: &NewElement,
338    writer: &Writer,
339    out: &mut Vec<u8>,
340    cx: &mut Cx<'_>,
341) -> Result<(), Error> {
342    enum Visit<'a> {
343        Open(&'a NewElement),
344        Close(&'a str),
345    }
346    let at = place(parent);
347    spend(cx, Kind::DecodedBytes, 32, &at)?;
348    let mut stack = vec![Visit::Open(child)];
349    let mut entered = 0_u64;
350    let result = (|| {
351        // 追加後の深さは、既存の親までの階層も含める。
352        let mut ancestor = Some(parent);
353        while let Some(element) = ancestor {
354            spend(cx, Kind::Work, 1, &at)?;
355            spend(cx, Kind::Depth, 1, &at)?;
356            entered += 1;
357            ancestor = element.parent().and_then(|index| doc.element(index));
358        }
359        while let Some(visit) = stack.pop() {
360            spend(cx, Kind::Work, 1, &at)?;
361            match visit {
362                Visit::Close(name) => {
363                    writer.push(out, "</", cx, &at)?;
364                    writer.push(out, name, cx, &at)?;
365                    writer.push(out, ">", cx, &at)?;
366                    cx.leave();
367                    entered -= 1;
368                }
369                Visit::Open(element) => {
370                    spend(cx, Kind::Depth, 1, &at)?;
371                    entered += 1;
372                    spend(cx, Kind::Records, 1, &at)?;
373                    spend(cx, Kind::Work, element.name.len() as u64, &at)?;
374                    if !name::valid_utf8(element.name.as_bytes()) {
375                        return Err(invalid(cx, codes::XML_EDIT_NAME_INVALID, &at));
376                    }
377                    if let Some((prefix, _)) = element.name.split_once(':')
378                        && !namespace(doc, Some(parent), prefix, cx, &at)?
379                    {
380                        cx.report(
381                            Diagnostic::new(codes::XML_EDIT_NAMESPACE_MISSING)
382                                .with("prefix", prefix)
383                                .at(at.clone()),
384                        );
385                        return Err(Error::Rejected);
386                    }
387                    writer.push(out, "<", cx, &at)?;
388                    writer.push(out, &element.name, cx, &at)?;
389                    if element.value.is_none() && element.children.is_empty() {
390                        writer.push(out, "/>", cx, &at)?;
391                        cx.leave();
392                        entered -= 1;
393                        continue;
394                    }
395                    writer.push(out, ">", cx, &at)?;
396                    if let Some(value) = &element.value {
397                        append(out, &writer.text(value, cx, &at)?, cx, &at)?;
398                    }
399                    spend(cx, Kind::Work, element.children.len() as u64, &at)?;
400                    spend(
401                        cx,
402                        Kind::DecodedBytes,
403                        (element.children.len() as u64)
404                            .saturating_add(1)
405                            .saturating_mul(32),
406                        &at,
407                    )?;
408                    stack.push(Visit::Close(&element.name));
409                    stack.extend(element.children.iter().rev().map(Visit::Open));
410                }
411            }
412        }
413        Ok(())
414    })();
415    for _ in 0..entered {
416        cx.leave();
417    }
418    result
419}
420
421fn place(element: &Element) -> Ref {
422    Ref::at_bytes(element.span().start as u64, element.span().end as u64)
423}
424fn spend(cx: &mut Cx<'_>, kind: Kind, amount: u64, at: &Ref) -> Result<(), Error> {
425    cx.check(kind, amount).map_err(|stop| {
426        cx.report(stop.to_diagnostic().at(at.clone()));
427        Error::Stopped(stop)
428    })
429}
430fn invalid(cx: &mut Cx<'_>, code: Code, at: &Ref) -> Error {
431    cx.report(Diagnostic::new(code).at(at.clone()));
432    Error::Rejected
433}