File: mutability_guards.rs

package info (click to toggle)
rust-libxml 0.3.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 596 kB
  • sloc: xml: 239; ansic: 45; makefile: 2
file content (57 lines) | stat: -rw-r--r-- 1,636 bytes parent folder | download
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
//! Enforce Rust ownership pragmatics for the underlying libxml2 objects

use libxml::parser::Parser;
use libxml::tree::set_node_rc_guard;

#[test]
fn ownership_guards() {
  // Setup
  let parser = Parser::default();
  let doc_result = parser.parse_file("tests/resources/file01.xml");
  assert!(doc_result.is_ok());
  let doc = doc_result.unwrap();
  let root = doc.get_root_element().unwrap();

  let mut first_a = root.get_first_element_child().unwrap();
  let first_b = root.get_first_element_child().unwrap();

  assert_eq!(
    first_a.get_attribute("attribute"),
    Some(String::from("value"))
  );
  assert_eq!(
    first_b.get_attribute("attribute"),
    Some(String::from("value"))
  );

  // Setting an attribute will fail and return an error, as there are too many Rc references
  // to the same node (Rc strong count of 3)
  // see `Node::node_ptr_mut` for details
  assert!(first_a.set_attribute("attribute", "newa").is_err());

  assert_eq!(
    first_a.get_attribute("attribute"),
    Some(String::from("value"))
  );
  assert_eq!(
    first_b.get_attribute("attribute"),
    Some(String::from("value"))
  );

  // Try again with guard boosted, which allows the change
  set_node_rc_guard(3);

  // Setting an attribute will fail and return an error, as there are too many Rc references
  // to the same node (Rc strong count of 3)
  // see `Node::node_ptr_mut` for details
  assert!(first_a.set_attribute("attribute", "newa").is_ok());

  assert_eq!(
    first_a.get_attribute("attribute"),
    Some(String::from("newa"))
  );
  assert_eq!(
    first_b.get_attribute("attribute"),
    Some(String::from("newa"))
  );
}