iks 0.7.0

Fast, easy to use XML parser library for Jabber/XMPP and general XML processing
Documentation
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
/*
** This file is a part of Iksemel (XML parser for Jabber/XMPP)
** Copyright (C) 2000-2025 Gurer Ozen
**
** Iksemel is free software: you can redistribute it and/or modify it
** under the terms of the GNU Lesser General Public License as
** published by the Free Software Foundation, either version 3 of
** the License, or (at your option) any later version.
*/

use std::marker::Send;
use std::ptr::null_mut;
use std::sync::Arc;
use std::sync::Mutex;

use super::Attribute;
use super::Node;
use super::NodePayload;
use super::sync_iterators::SyncChildren;
use crate::Cursor;
use crate::Document;
use crate::ParseError;

pub struct SyncAttributes {
    sync_cursor: SyncCursor,
    current: *mut Attribute,
}

impl SyncAttributes {
    pub fn new(sync_cursor: &SyncCursor) -> Self {
        let _document = sync_cursor.document.lock().unwrap();
        unsafe {
            let attr = if sync_cursor.node.is_null() {
                null_mut::<Attribute>()
            } else {
                match (*sync_cursor.node).payload {
                    NodePayload::Tag(tag) => (*tag).attributes,
                    NodePayload::CData(_) => null_mut::<Attribute>(),
                }
            };
            SyncAttributes {
                sync_cursor: sync_cursor.clone(),
                current: attr,
            }
        }
    }
}

impl Iterator for SyncAttributes {
    type Item = (String, String);

    fn next(&mut self) -> Option<Self::Item> {
        if self.current.is_null() {
            return None;
        }
        let _document = self.sync_cursor.document.lock().unwrap();
        unsafe {
            let result = Some((
                (*self.current).name_as_str().to_string(),
                (*self.current).value_as_str().to_string(),
            ));
            self.current = (*self.current).next;
            result
        }
    }
}

pub struct SyncCursor {
    document: Arc<Mutex<Document>>,
    node: *mut Node,
}

macro_rules! tag_edit_method {
    ($method:ident) => {
        pub fn $method(mut self, tag_name: &str) -> Result<Self, ParseError> {
            {
                let document = self.document.lock().unwrap();
                let current = Cursor::new(self.node, &document.arena);
                let new = current.$method(tag_name)?;
                self.node = new.get_node_ptr();
            }
            Ok(self)
        }
    };
}

macro_rules! cdata_edit_method {
    ($method:ident) => {
        pub fn $method(mut self, cdata: &str) -> Result<Self, ParseError> {
            {
                let document = self.document.lock().unwrap();
                let current = Cursor::new(self.node, &document.arena);
                let new = current.$method(cdata)?;
                self.node = new.get_node_ptr();
            }
            Ok(self)
        }
    };
}

macro_rules! navigation_method {
    ($method:ident) => {
        pub fn $method(mut self) -> Self {
            {
                let document = self.document.lock().unwrap();
                let new = Cursor::new(self.node, &document.arena).$method();
                self.node = new.get_node_ptr();
            }
            self
        }
    };
}

impl SyncCursor {
    pub fn new(document: Document) -> Self {
        let node = document.root().get_node_ptr();
        let document = Arc::new(Mutex::new(document));
        Self { document, node }
    }

    //
    // Edit
    //

    tag_edit_method!(insert_tag);
    tag_edit_method!(append_tag);
    tag_edit_method!(prepend_tag);
    cdata_edit_method!(insert_cdata);
    cdata_edit_method!(append_cdata);
    cdata_edit_method!(prepend_cdata);

    /// Insert an attribute into the current tag element.
    ///
    /// # Errors:
    ///
    /// Returns `ParseError::BadXml` if the attribute already exists.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn insert_attribute<'b>(
        mut self,
        name: &'b str,
        value: &'b str,
    ) -> Result<Self, ParseError> {
        {
            let document = self.document.lock().unwrap();
            let current = Cursor::new(self.node, &document.arena);
            let new = current.insert_attribute(name, value)?;
            self.node = new.get_node_ptr();
        }
        Ok(self)
    }

    /// Sets or clears an attribute of the current tag element.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn set_attribute<'b>(
        mut self,
        name: &'b str,
        value: Option<&'b str>,
    ) -> Result<Self, ParseError> {
        {
            let document = self.document.lock().unwrap();
            let current = Cursor::new(self.node, &document.arena);
            let new = current.set_attribute(name, value)?;
            self.node = new.get_node_ptr();
        }
        Ok(self)
    }

    /// Removes the tag element from the document.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn remove(self) {
        let document = self.document.lock().unwrap();
        let current = Cursor::new(self.node, &document.arena);
        current.remove();
    }

    //
    // Navigation
    //

    navigation_method!(next);
    navigation_method!(next_tag);
    navigation_method!(previous);
    navigation_method!(previous_tag);
    navigation_method!(parent);
    navigation_method!(root);
    navigation_method!(first_child);
    navigation_method!(last_child);
    navigation_method!(first_tag);

    //
    // Iterators
    //

    pub fn attributes(self) -> SyncAttributes {
        SyncAttributes::new(&self)
    }

    pub fn children(&self) -> SyncChildren {
        SyncChildren::new(self)
    }

    /// Returns the first child tag element with the given name.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn find_tag(mut self, tag_name: &str) -> Self {
        {
            let document = self.document.lock().unwrap();
            let next = Cursor::new(self.node, &document.arena).find_tag(tag_name);
            self.node = next.get_node_ptr();
        }
        self
    }

    /// Returns the first child tag element with the given attribute.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn find_tag_with_attribute(mut self, attribute_name: &str) -> Self {
        {
            let document = self.document.lock().unwrap();
            let next =
                Cursor::new(self.node, &document.arena).find_tag_with_attribute(attribute_name);
            self.node = next.get_node_ptr();
        }
        self
    }

    /// Returns the first child tag element with the given attribute.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn find_tag_with_attribute_value(mut self, attribute_name: &str, value: &str) -> Self {
        {
            let document = self.document.lock().unwrap();
            let next = Cursor::new(self.node, &document.arena)
                .find_tag_with_attribute_value(attribute_name, value);
            self.node = next.get_node_ptr();
        }
        self
    }

    //
    // Properties
    //

    pub fn is_null(&self) -> bool {
        self.node.is_null()
    }

    pub fn is_tag(&self) -> bool {
        unsafe {
            if self.node.is_null() {
                return false;
            }
            match (*self.node).payload {
                NodePayload::CData(_) => false,
                NodePayload::Tag(_) => true,
            }
        }
    }

    /// Returns true if the node has children.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn has_children(&self) -> bool {
        let document = self.document.lock().unwrap();
        Cursor::new(self.node, &document.arena).has_children()
    }

    pub fn name(&self) -> &str {
        if self.node.is_null() {
            return "";
        }
        // SAFETY:
        // Invariants:
        // 1. Returned reference must not outlive the pointed memory.
        // 2. Pointed string must be valid UTF-8.
        // 3. Pointed string must not change while the reference is alive.
        // 4. Dereferenced members must be immutable as there is no lock taken.
        // Guards:
        // a. Elided lifetime ensures the liveness of self while reference is alive.
        // b. While self is alive, Arc keeps a reference count on the backing Arena (1).
        // c. Document constructors ensure UTF-8 validity (2):
        // c.1. SaxParser validates input bytes.
        // c.2. Edit methods only accept &str.
        // d. Arena strings are immutable, never moved or changed until Arena is dropped (3).
        // e. Only the navigational members of a tag node are mutated after the construction,
        // and they are not accessed here (4).
        unsafe {
            match (*self.node).payload {
                NodePayload::CData(_) => "",
                NodePayload::Tag(tag) => (*tag).as_str(),
            }
        }
    }

    /// Returns the value of the given attribute.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn attribute(&self, name: &str) -> Option<&str> {
        if self.node.is_null() {
            return None;
        }
        unsafe {
            if let NodePayload::Tag(tag) = (*self.node).payload {
                let _document = self.document.lock().unwrap();
                let mut attr = (*tag).attributes;
                while !attr.is_null() {
                    let attr_name = (*attr).name_as_str();
                    if attr_name == name {
                        return Some((*attr).value_as_str());
                    }
                    attr = (*attr).next;
                }
            }
        }
        None
    }

    /// Returns the character data of the current element.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn cdata(&self) -> &str {
        let _document = self.document.lock().unwrap();
        unsafe {
            if self.node.is_null() {
                return "";
            }
            match (*self.node).payload {
                NodePayload::CData(cdata) => (*cdata).as_str(),
                NodePayload::Tag(_) => {
                    // Not a CData
                    ""
                }
            }
        }
    }

    /// Returns the currently pointer subdocument as a new Document.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn to_document(&self) -> Result<Self, ParseError> {
        let document = self.document.lock().unwrap();
        let new_document = Cursor::new(self.node, &document.arena).to_document()?;
        Ok(SyncCursor::new(new_document))
    }

    /// Inserts the given document into this document.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn insert_document(mut self, document: &Self) -> Result<Self, ParseError> {
        {
            let self_document = self.document.lock().unwrap();
            let other_document = document.document.lock().unwrap();
            let new_document = Cursor::new(self.node, &self_document.arena)
                .insert_document(Cursor::new(document.node, &other_document.arena))?;
            self.node = new_document.node;
        }
        Ok(self)
    }

    /// Returns the length of the XML string representation.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    pub fn str_size(&self) -> usize {
        let document = self.document.lock().unwrap();
        Cursor::new(self.node, &document.arena).str_size()
    }

    /// Returns the XML string representation.
    ///
    /// # Panics
    ///
    /// Panics if the mutex is poisoned.
    ///
    #[expect(
        clippy::inherent_to_string_shadow_display,
        reason = "prereserving exact capacity makes this method significantly faster"
    )]
    pub fn to_string(&self) -> String {
        let document = self.document.lock().unwrap();
        Cursor::new(self.node, &document.arena).to_string()
    }
}

impl Clone for SyncCursor {
    fn clone(&self) -> Self {
        Self {
            document: self.document.clone(),
            node: self.node,
        }
    }
}

impl std::fmt::Display for SyncCursor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let document = self.document.lock().unwrap();
        let cursor = Cursor::new(self.node, &document.arena);
        std::fmt::Display::fmt(&cursor, f)
    }
}

unsafe impl Send for SyncCursor {}

unsafe impl Sync for SyncCursor {}