exml 0.7.3-deprecated

Pure Rust XML library based on libxml2
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
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
use std::{borrow::Cow, ffi::c_void};

use crate::{generic_error, tree::XmlGenericNodePtr, xpointer::XmlLocationSet};

use super::{
    XML_XPATH_NAN, XmlNodeSet, xml_xpath_cast_boolean_to_number, xml_xpath_cast_boolean_to_string,
    xml_xpath_cast_node_set_to_boolean, xml_xpath_cast_node_set_to_number,
    xml_xpath_cast_node_set_to_string, xml_xpath_cast_number_to_boolean,
    xml_xpath_cast_number_to_string, xml_xpath_cast_string_to_boolean,
    xml_xpath_cast_string_to_number, xml_xpath_free_node_set, xml_xpath_free_value_tree,
    xml_xpath_node_set_create, xml_xpath_node_set_merge,
};

// An expression is evaluated to yield an object, which
// has one of the following four basic types:
//   - node-set
//   - boolean
//   - number
//   - string
//
// @@ XPointer will add more types !
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum XmlXPathObjectType {
    #[default]
    XPathUndefined = 0,
    XPathNodeset = 1,
    XPathBoolean = 2,
    XPathNumber = 3,
    XPathString = 4,
    #[cfg(feature = "libxml_xptr_locs")]
    XPathPoint = 5,
    #[cfg(feature = "libxml_xptr_locs")]
    XPathRange = 6,
    #[cfg(feature = "libxml_xptr_locs")]
    XPathLocationset = 7,
    XPathUsers = 8,
    XPathXSLTTree = 9, /* An XSLT value tree, non modifiable */
}

// #[cfg(all(feature = "libxml_xptr_locs", feature = "xpath"))]
// const XPATH_POINT: usize = 5;
// #[cfg(all(feature = "libxml_xptr_locs", feature = "xpath"))]
// const XPATH_RANGE: usize = 6;
// #[cfg(all(feature = "libxml_xptr_locs", feature = "xpath"))]
// const XPATH_LOCATIONSET: usize = 7;

#[repr(C)]
#[derive(Clone, PartialEq)]
pub struct XmlXPathObject {
    pub typ: XmlXPathObjectType,
    pub nodesetval: Option<Box<XmlNodeSet>>,
    pub boolval: bool,
    pub floatval: f64,
    pub stringval: Option<String>,
    pub(crate) user: Option<XmlXPathObjectUserData>,
    pub(crate) index: i32,
    pub(crate) user2: Option<XmlXPathObjectUserData>,
    pub(crate) index2: i32,
}

impl Default for XmlXPathObject {
    fn default() -> Self {
        Self {
            typ: XmlXPathObjectType::default(),
            nodesetval: None,
            boolval: false,
            floatval: 0.0,
            stringval: None,
            user: None,
            index: 0,
            user2: None,
            index2: 0,
        }
    }
}

impl Drop for XmlXPathObject {
    /// Free up an object: xmlXPathObjectPtr.
    #[doc(alias = "xmlXPathFreeObject")]
    fn drop(&mut self) {
        if matches!(
            self.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        ) {
            if self.boolval {
                self.typ = XmlXPathObjectType::XPathXSLTTree; // TODO: Just for debugging. 
                xml_xpath_free_value_tree(self.nodesetval.take());
            } else if let Some(set) = self.nodesetval.take() {
                xml_xpath_free_node_set(Some(set));
            }
        } else if matches!(self.typ, XmlXPathObjectType::XPathString) && self.stringval.is_some() {
            let _ = self.stringval.take();
        } else {
            #[cfg(feature = "libxml_xptr_locs")]
            let _ = self.user.take();
            // #[cfg(feature = "libxml_xptr_locs")]
            // if let Some(loc) = self.user.take() {
            //     if let Some(&loc) = loc.as_location_set() {
            //         xml_xptr_free_location_set(loc);
            //     }
            // }
        }
    }
}

impl From<&str> for XmlXPathObject {
    fn from(value: &str) -> Self {
        let mut ret = Self::default();
        ret.typ = XmlXPathObjectType::XPathString;
        ret.stringval = Some(value.to_owned());
        ret
    }
}

impl From<String> for XmlXPathObject {
    fn from(value: String) -> Self {
        let mut ret = Self::default();
        ret.typ = XmlXPathObjectType::XPathString;
        ret.stringval = Some(value);
        ret
    }
}

impl From<f64> for XmlXPathObject {
    fn from(value: f64) -> Self {
        let mut ret = Self::default();
        ret.typ = XmlXPathObjectType::XPathNumber;
        ret.floatval = value;
        ret
    }
}

impl From<bool> for XmlXPathObject {
    fn from(value: bool) -> Self {
        let mut ret = Self::default();
        ret.typ = XmlXPathObjectType::XPathBoolean;
        ret.boolval = value;
        ret
    }
}

#[derive(Clone, PartialEq)]
pub enum XmlXPathObjectUserData {
    Node(XmlGenericNodePtr),
    LocationSet(XmlLocationSet),
    External(*mut c_void),
}

impl XmlXPathObjectUserData {
    pub fn as_node(&self) -> Option<&XmlGenericNodePtr> {
        match self {
            Self::Node(node) => Some(node),
            _ => None,
        }
    }

    pub fn as_location_set(&self) -> Option<&XmlLocationSet> {
        match self {
            Self::LocationSet(loc) => Some(loc),
            _ => None,
        }
    }

    pub fn as_location_set_mut(&mut self) -> Option<&mut XmlLocationSet> {
        match self {
            Self::LocationSet(loc) => Some(loc),
            _ => None,
        }
    }

    pub fn as_external(&self) -> Option<&*mut c_void> {
        match self {
            Self::External(external) => Some(external),
            _ => None,
        }
    }
}

/// Create a new xmlXPathObjectPtr of type string and of value @val
///
/// Returns the newly created object.
#[doc(
    alias = "xmlXPathNewCString",
    alias = "xmlXPathNewString",
    alias = "xmlXPathCacheNewString",
    alias = "xmlXPathCacheNewCString"
)]
pub fn xml_xpath_new_string(val: Option<&str>) -> XmlXPathObject {
    XmlXPathObject::from(val.unwrap_or(""))
}

/// Wraps the @val string into an XPath object.
///
/// Returns the newly created object.
///
/// Frees @val in case of error.
#[doc(
    alias = "xmlXPathWrapString",
    alias = "xmlXPathWrapCString",
    alias = "xmlXPathCacheWrapString"
)]
pub fn xml_xpath_wrap_string(val: Option<&str>) -> XmlXPathObject {
    let mut ret = XmlXPathObject::default();
    ret.typ = XmlXPathObjectType::XPathString;
    ret.stringval = val.map(|s| s.to_owned());
    ret
}

/// Create a new xmlXPathObjectPtr of type f64 and of value @val
///
/// Returns the newly created object.
#[doc(alias = "xmlXPathNewFloat", alias = "xmlXPathCacheNewFloat")]
pub fn xml_xpath_new_float(val: f64) -> XmlXPathObject {
    XmlXPathObject::from(val)
}

/// Create a new xmlXPathObjectPtr of type boolean and of value @val
///
/// Returns the newly created object.
#[doc(alias = "xmlXPathNewBoolean", alias = "xmlXPathCacheNewBoolean")]
pub fn xml_xpath_new_boolean(val: bool) -> XmlXPathObject {
    XmlXPathObject::from(val)
}

/// Create a new xmlXPathObjectPtr of type NodeSet and initialize
/// it with the single Node @val
///
/// Returns the newly created object.
#[doc(alias = "xmlXPathNewNodeSet", alias = "xmlXPathCacheNewNodeSet")]
pub fn xml_xpath_new_node_set(val: Option<XmlGenericNodePtr>) -> XmlXPathObject {
    let mut ret = XmlXPathObject::default();
    ret.typ = XmlXPathObjectType::XPathNodeset;
    ret.boolval = false;
    // TODO: Check memory error.
    ret.nodesetval = xml_xpath_node_set_create(val);
    /* @@ with_ns to check whether namespace nodes should be looked at @@ */
    ret
}

/// Wrap the Nodeset @val in a new xmlXPathObjectPtr
///
/// Returns the newly created object.
///
/// In case of error the node set is destroyed and NULL is returned.
#[doc(alias = "xmlXPathWrapNodeSet", alias = "xmlXPathCacheWrapNodeSet")]
pub fn xml_xpath_wrap_node_set(val: Option<Box<XmlNodeSet>>) -> XmlXPathObject {
    let mut ret = XmlXPathObject::default();
    ret.typ = XmlXPathObjectType::XPathNodeset;
    ret.nodesetval = val;
    ret
}

/// Create a new xmlXPathObjectPtr of type Value Tree (XSLT) and initialize
/// it with the tree root @val
///
/// Returns the newly created object.
#[doc(alias = "xmlXPathNewValueTree")]
pub fn xml_xpath_new_value_tree(val: Option<XmlGenericNodePtr>) -> XmlXPathObject {
    let mut ret = XmlXPathObject::default();
    ret.typ = XmlXPathObjectType::XPathXSLTTree;
    ret.boolval = true;
    ret.user = val.map(XmlXPathObjectUserData::Node);
    ret.nodesetval = xml_xpath_node_set_create(val);
    ret
}

/// Wraps the @val data into an XPath object.
///
/// Returns the newly created object.
#[doc(alias = "xmlXPathWrapExternal")]
pub fn xml_xpath_wrap_external(val: *mut c_void) -> XmlXPathObject {
    let mut ret = XmlXPathObject::default();
    ret.typ = XmlXPathObjectType::XPathUsers;
    ret.user = (!val.is_null()).then_some(XmlXPathObjectUserData::External(val));
    ret
}

/// Allocate a new copy of a given object
///
/// Returns the newly created object.
#[doc(alias = "xmlXPathObjectCopy", alias = "xmlXPathCacheObjectCopy")]
pub fn xml_xpath_object_copy(val: &XmlXPathObject) -> XmlXPathObject {
    let mut ret = val.clone();
    match val.typ {
        XmlXPathObjectType::XPathBoolean | XmlXPathObjectType::XPathNumber => {}
        #[cfg(feature = "libxml_xptr_locs")]
        XmlXPathObjectType::XPathPoint | XmlXPathObjectType::XPathRange => {}
        XmlXPathObjectType::XPathString => {}
        XmlXPathObjectType::XPathXSLTTree | XmlXPathObjectType::XPathNodeset => {
            // TODO: Check memory error.
            ret.nodesetval = xml_xpath_node_set_merge(None, val.nodesetval.as_deref());
            // Do not deallocate the copied tree value
            ret.boolval = false;
        }
        #[cfg(feature = "libxml_xptr_locs")]
        XmlXPathObjectType::XPathLocationset => {
            // What is this ????
            // It seems that `xml_xptr_location_set_merge` always returns `null_mut()`...
            // if let Some(loc) = (*val).user.as_ref().and_then(|user| user.as_location_set()) {
            //     let loc = xml_xptr_location_set_merge(null_mut(), loc);
            //     ret.user =
            //         (!loc.is_null()).then_some(XmlXPathObjectUserData::LocationSet(loc));
            // }
        }
        XmlXPathObjectType::XPathUsers => {
            ret.user = val.user.clone();
        }
        XmlXPathObjectType::XPathUndefined => {
            generic_error!("xmlXPathObjectCopy: unsupported type {}\n", val.typ as i32);
        } // _ => {}
    }
    ret
}

/// Converts an XPath object to its boolean value
///
/// Returns the boolean value
#[doc(alias = "xmlXPathCastToBoolean")]
pub fn xml_xpath_cast_to_boolean(val: &XmlXPathObject) -> bool {
    match val.typ {
        XmlXPathObjectType::XPathUndefined => false,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {
            xml_xpath_cast_node_set_to_boolean(val.nodesetval.as_deref())
        }
        XmlXPathObjectType::XPathString => {
            xml_xpath_cast_string_to_boolean(val.stringval.as_deref())
        }
        XmlXPathObjectType::XPathNumber => xml_xpath_cast_number_to_boolean(val.floatval),
        XmlXPathObjectType::XPathBoolean => val.boolval,
        XmlXPathObjectType::XPathUsers => {
            // todo!();
            false
        }
        #[cfg(feature = "libxml_xptr_locs")]
        XmlXPathObjectType::XPathPoint
        | XmlXPathObjectType::XPathRange
        | XmlXPathObjectType::XPathLocationset => {
            // todo!();
            false
        }
    }
}

/// Converts an XPath object to its number value
///
/// Returns the number value
#[doc(alias = "xmlXPathCastToNumber")]
pub fn xml_xpath_cast_to_number(val: &mut XmlXPathObject) -> f64 {
    match val.typ {
        XmlXPathObjectType::XPathUndefined => XML_XPATH_NAN,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {
            xml_xpath_cast_node_set_to_number(val.nodesetval.as_deref_mut())
        }
        XmlXPathObjectType::XPathString => {
            let strval = val.stringval.as_deref();
            xml_xpath_cast_string_to_number(strval)
        }
        XmlXPathObjectType::XPathNumber => val.floatval,
        XmlXPathObjectType::XPathBoolean => xml_xpath_cast_boolean_to_number(val.boolval),
        XmlXPathObjectType::XPathUsers => {
            // todo!();
            XML_XPATH_NAN
        }
        #[cfg(feature = "libxml_xptr_locs")]
        XmlXPathObjectType::XPathPoint
        | XmlXPathObjectType::XPathRange
        | XmlXPathObjectType::XPathLocationset => {
            // todo!();
            XML_XPATH_NAN
        }
    }
}

/// Converts an existing object to its string() equivalent
///
/// Returns the allocated string value of the object, `None` in case of error.
#[doc(alias = "xmlXPathCastToString")]
pub fn xml_xpath_cast_to_string(val: &mut XmlXPathObject) -> Cow<'static, str> {
    match val.typ {
        XmlXPathObjectType::XPathUndefined => "".into(),
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {
            xml_xpath_cast_node_set_to_string(val.nodesetval.as_deref_mut())
        }
        XmlXPathObjectType::XPathString => val.stringval.clone().unwrap().into(),
        XmlXPathObjectType::XPathBoolean => xml_xpath_cast_boolean_to_string(val.boolval).into(),
        XmlXPathObjectType::XPathNumber => xml_xpath_cast_number_to_string(val.floatval),
        XmlXPathObjectType::XPathUsers => {
            // todo!();
            "".into()
        }
        #[cfg(feature = "libxml_xptr_locs")]
        XmlXPathObjectType::XPathPoint
        | XmlXPathObjectType::XPathRange
        | XmlXPathObjectType::XPathLocationset => {
            // todo!();
            "".into()
        }
    }
}

/// Converts an existing object to its boolean() equivalent
///
/// Returns the new object, the old one is freed (or the operation is done directly on @val)
#[doc(
    alias = "xmlXPathConvertBoolean",
    alias = "xmlXPathCacheConvertBoolean"
)]
pub fn xml_xpath_convert_boolean(val: Option<XmlXPathObject>) -> XmlXPathObject {
    let Some(val) = val else {
        return xml_xpath_new_boolean(false);
    };
    if val.typ == XmlXPathObjectType::XPathBoolean {
        return val;
    }
    xml_xpath_new_boolean(xml_xpath_cast_to_boolean(&val))
}

/// Converts an existing object to its number() equivalent
///
/// Returns the new object, the old one is freed (or the operation is done directly on @val)
#[doc(alias = "xmlXPathConvertNumber", alias = "xmlXPathCacheConvertNumber")]
pub fn xml_xpath_convert_number(val: Option<XmlXPathObject>) -> XmlXPathObject {
    let Some(mut val) = val else {
        return xml_xpath_new_float(0.0);
    };
    if val.typ == XmlXPathObjectType::XPathNumber {
        return val;
    }
    xml_xpath_new_float(xml_xpath_cast_to_number(&mut val))
}

/// Converts an existing object to its string() equivalent
///
/// Returns the new object, the old one is freed (or the operation is done directly on @val)
#[doc(alias = "xmlXPathConvertString", alias = "xmlXPathCacheConvertString")]
pub fn xml_xpath_convert_string(val: Option<XmlXPathObject>) -> XmlXPathObject {
    let Some(mut val) = val else {
        return xml_xpath_new_string(Some(""));
    };

    let mut res = None::<Cow<'_, str>>;
    match val.typ {
        XmlXPathObjectType::XPathUndefined => {}
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {
            res = Some(xml_xpath_cast_node_set_to_string(
                val.nodesetval.as_deref_mut(),
            ));
        }
        XmlXPathObjectType::XPathString => {
            return val;
        }
        XmlXPathObjectType::XPathBoolean => {
            res = Some(xml_xpath_cast_boolean_to_string(val.boolval).into());
        }
        XmlXPathObjectType::XPathNumber => {
            res = Some(xml_xpath_cast_number_to_string(val.floatval));
        }
        XmlXPathObjectType::XPathUsers => {
            // todo!()
        }
        #[cfg(feature = "libxml_xptr_locs")]
        XmlXPathObjectType::XPathPoint
        | XmlXPathObjectType::XPathRange
        | XmlXPathObjectType::XPathLocationset => {
            // todo!()
        }
    }
    let Some(res) = res else {
        return xml_xpath_new_string(Some(""));
    };
    xml_xpath_wrap_string(Some(&res))
}