-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdata.rs
1755 lines (1566 loc) · 54.5 KB
/
data.rs
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) The yang-rs Core Contributors
//
// SPDX-License-Identifier: MIT
//
//! YANG instance data.
use bitflags::bitflags;
use core::ffi::{c_char, c_void};
use std::ffi::CStr;
use std::ffi::CString;
use std::mem::ManuallyDrop;
use std::slice;
use crate::context::Context;
use crate::error::{Error, Result};
use crate::iter::{
Ancestors, MetadataList, NodeIterable, Set, Siblings, Traverse,
};
use crate::schema::SchemaExtInstance;
use crate::schema::{DataValue, SchemaModule, SchemaNode, SchemaNodeKind};
use crate::utils::*;
use libyang3_sys as ffi;
/// YANG data tree.
#[derive(Debug)]
pub struct DataTree<'a> {
context: &'a Context,
raw: *mut ffi::lyd_node,
}
/// YANG data tree with an associated inner node reference.
#[derive(Debug)]
pub struct DataTreeOwningRef<'a> {
pub tree: DataTree<'a>,
raw: *mut ffi::lyd_node,
}
/// YANG data node reference.
#[derive(Clone, Debug)]
pub struct DataNodeRef<'a> {
tree: &'a DataTree<'a>,
raw: *mut ffi::lyd_node,
}
/// The structure provides information about metadata of a data element. Such
/// attributes must map to annotations as specified in RFC 7952. The only
/// exception is the filter type (in NETCONF get operations) and edit-config's
/// operation attributes. In XML, they are represented as standard XML
/// attributes. In JSON, they are represented as JSON elements starting with the
/// '@' character (for more information, see the YANG metadata RFC).
#[derive(Clone, Debug)]
pub struct Metadata<'a> {
dnode: &'a DataNodeRef<'a>,
raw: *mut ffi::lyd_meta,
}
/// YANG data tree diff.
#[derive(Debug)]
pub struct DataDiff<'a> {
tree: DataTree<'a>,
}
/// YANG data diff operation.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DataDiffOp {
Create,
Delete,
Replace,
}
/// Data input/output formats supported by libyang.
#[allow(clippy::upper_case_acronyms)]
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DataFormat {
/// XML instance data format.
XML = ffi::LYD_FORMAT::LYD_XML,
/// JSON instance data format.
JSON = ffi::LYD_FORMAT::LYD_JSON,
/// LYB instance data format.
LYB = ffi::LYD_FORMAT::LYD_LYB,
}
/// Data operation type.
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DataOperation {
/// Generic YANG instance data.
Data = ffi::lyd_type::LYD_TYPE_DATA_YANG,
/// Instance of a YANG RPC/action request with only "input" data children.
/// Including all parents in case of an action
RpcYang = ffi::lyd_type::LYD_TYPE_RPC_YANG,
/// Instance of a YANG notification, including all parents in case of a
/// nested one.
NotificationYang = ffi::lyd_type::LYD_TYPE_NOTIF_YANG,
/// Instance of a YANG RPC/action request with only "output" data children.
/// Including all parents in case of an action
ReplyYang = ffi::lyd_type::LYD_TYPE_REPLY_YANG,
}
bitflags! {
/// Data parser options.
///
/// Various options to change the data tree parsers behavior.
///
/// Default parser behavior:
/// - complete input file is always parsed. In case of XML, even not
/// well-formed XML document (multiple top-level elements) is parsed in
/// its entirety.
/// - parser silently ignores data without matching schema node definition.
/// - list instances are checked whether they have all the keys, error is
/// raised if not.
///
/// Default parser validation behavior:
/// - the provided data are expected to provide complete datastore content
/// (both the configuration and state data) and performs data validation
/// according to all YANG rules, specifics follow.
/// - list instances are expected to have all the keys (it is not checked).
/// - instantiated (status) obsolete data print a warning.
/// - all types are fully resolved (leafref/instance-identifier targets,
/// unions) and must be valid (lists have all the keys, leaf(-lists)
/// correct values).
/// - when statements on existing nodes are evaluated, if not satisfied, a
/// validation error is raised.
/// - if-feature statements are evaluated.
/// - invalid multiple data instances/data from several cases cause a
/// validation error.
/// - implicit nodes (NP containers and default values) are added.
pub struct DataParserFlags: u32 {
/// Data will be only parsed and no validation will be performed. When
/// statements are kept unevaluated, union types may not be fully
/// resolved, if-feature statements are not checked, and default values
/// are not added (only the ones parsed are present).
const NO_VALIDATION = ffi::LYD_PARSE_ONLY;
/// Instead of silently ignoring data without schema definition raise an
/// error.
const STRICT = ffi::LYD_PARSE_STRICT;
/// Forbid state data in the parsed data.
const NO_STATE = ffi::LYD_PARSE_NO_STATE;
}
}
bitflags! {
/// Data validation options.
///
/// Various options to change data validation behaviour, both for the parser
/// and separate validation.
pub struct DataValidationFlags: u32 {
/// Consider state data not allowed and raise an error if they are found.
const NO_STATE = ffi::LYD_VALIDATE_NO_STATE;
/// Validate only modules whose data actually exist.
const PRESENT = ffi::LYD_VALIDATE_PRESENT;
}
}
bitflags! {
/// Data printer flags.
///
/// Various options to change data validation behaviour, both for the parser
/// and separate validation.
pub struct DataPrinterFlags: u32 {
/// Flag for printing also the (following) sibling nodes of the data
/// node.
const WITH_SIBLINGS = ffi::LYD_PRINT_WITHSIBLINGS;
/// Flag for output without indentation and formatting new lines.
const SHRINK = ffi::LYD_PRINT_SHRINK;
/// Preserve empty non-presence containers.
const KEEP_EMPTY_CONT = ffi::LYD_PRINT_KEEPEMPTYCONT;
/// Explicit with-defaults mode. Only the data explicitly being present
/// in the data tree are printed, so the implicitly added default nodes
/// are not printed. Note that this is the default value when no WD
/// option is specified.
const WD_EXPLICIT = ffi::LYD_PRINT_WD_EXPLICIT;
/// Trim mode avoids printing the nodes with the value equal to their
/// default value.
const WD_TRIM = ffi::LYD_PRINT_WD_TRIM;
/// Include implicit default nodes.
const WD_ALL = ffi::LYD_PRINT_WD_ALL;
}
}
bitflags! {
/// Implicit node creation options.
///
/// Default behavior:
/// - both configuration and state missing implicit nodes are added.
/// - for existing RPC/action nodes, input implicit nodes are added.
/// - all implicit node types are added (non-presence containers,
/// default leaves, and default leaf-lists).
pub struct DataImplicitFlags: u32 {
/// Do not add any implicit state nodes.
const NO_STATE = ffi::LYD_IMPLICIT_NO_STATE;
/// Do not add any implicit config nodes.
const NO_CONFIG = ffi::LYD_IMPLICIT_NO_CONFIG;
/// For RPC/action nodes, add output implicit nodes instead of input.
const OUTPUT = ffi::LYD_IMPLICIT_OUTPUT;
/// Do not add any default nodes (leaves/leaf-lists), only non-presence
/// containers.
const NO_DEFAULTS = ffi::LYD_IMPLICIT_NO_DEFAULTS;
}
}
bitflags! {
/// Data diff options.
///
/// Default behavior:
/// - Any default nodes are treated as non-existent and ignored.
pub struct DataDiffFlags: u16 {
/// Default nodes in the trees are not ignored but treated similarly to
/// explicit nodes. Also, leaves and leaf-lists are added into diff even
/// in case only their default flag (state) was changed.
const DEFAULTS = ffi::LYD_DIFF_DEFAULTS as u16;
}
}
/// Methods common to data trees, data node references and data diffs.
pub trait Data<'a> {
#[doc(hidden)]
fn context(&self) -> &'a Context {
self.tree().context
}
#[doc(hidden)]
fn tree(&self) -> &DataTree<'a>;
#[doc(hidden)]
fn raw(&self) -> *mut ffi::lyd_node;
/// Search in the given data for instances of nodes matching the provided
/// XPath.
///
/// The expected format of the expression is JSON, meaning the first node in
/// every path must have its module name as prefix or be the special `*`
/// value for all the nodes.
///
/// If a list instance is being selected with all its key values specified
/// (but not necessarily ordered) in the form
/// `list[key1='val1'][key2='val2'][key3='val3']` or a leaf-list instance in
/// the form `leaf-list[.='val']`, these instances are found using hashes
/// with constant (*O(1)*) complexity (unless they are defined in
/// top-level). Other predicates can still follow the aforementioned ones.
fn find_xpath(&'a self, xpath: &str) -> Result<Set<'a, DataNodeRef<'a>>> {
let xpath = CString::new(xpath).unwrap();
let mut set = std::ptr::null_mut();
let set_ptr = &mut set;
let ret =
unsafe { ffi::lyd_find_xpath(self.raw(), xpath.as_ptr(), set_ptr) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context()));
}
let rnodes_count = unsafe { (*set).count } as usize;
let slice = if rnodes_count == 0 {
&[]
} else {
let rnodes = unsafe { (*set).__bindgen_anon_1.dnodes };
unsafe { slice::from_raw_parts(rnodes, rnodes_count) }
};
Ok(Set::new(self.tree(), slice))
}
/// Search in the given data for a single node matching the provided XPath.
///
/// The expected format of the expression is JSON, meaning the first node in
/// every path must have its module name as prefix or be the special `*`
/// value for all the nodes.
fn find_path(&'a self, path: &str) -> Result<DataNodeRef<'a>> {
let path = CString::new(path).unwrap();
let mut rnode = std::ptr::null_mut();
let rnode_ptr = &mut rnode;
let ret = unsafe {
ffi::lyd_find_path(self.raw(), path.as_ptr(), 0u8, rnode_ptr)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context()));
}
Ok(unsafe { DataNodeRef::from_raw(self.tree(), rnode as *mut _) })
}
/// Print data tree in the specified format.
#[cfg(not(target_os = "windows"))]
fn print_file<F: std::os::unix::io::AsRawFd>(
&self,
fd: F,
format: DataFormat,
options: DataPrinterFlags,
) -> Result<()> {
let ret = unsafe {
ffi::lyd_print_fd(
fd.as_raw_fd(),
self.raw(),
format as u32,
options.bits(),
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context()));
}
Ok(())
}
/// Print data tree in the specified format.
#[cfg(target_os = "windows")]
fn print_file(
&self,
file: impl std::os::windows::io::AsRawHandle,
format: DataFormat,
options: DataPrinterFlags,
) -> Result<()> {
use libc::open_osfhandle;
let raw_handle = file.as_raw_handle();
let fd = unsafe { open_osfhandle(raw_handle as isize, 0) };
let ret = unsafe {
ffi::lyd_print_fd(fd, self.raw(), format as u32, options.bits())
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context()));
}
Ok(())
}
/// Print data tree in the specified format to a `String`.
///
/// # Warning
/// For printing a data tree in the `DataFormat::LYB` format, use the
/// [`Data::print_bytes`] method instead. Using this function with
/// `DataFormat::LYB` may result in mangled data because the `LYB` format
/// can contain invalid UTF-8 sequences, which cannot be represented in a
/// `String`.
fn print_string(
&self,
format: DataFormat,
options: DataPrinterFlags,
) -> Result<String> {
let mut cstr = std::ptr::null_mut();
let cstr_ptr = &mut cstr;
let ret = unsafe {
ffi::lyd_print_mem(
cstr_ptr,
self.raw(),
format as u32,
options.bits(),
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context()));
}
Ok(char_ptr_to_string(cstr, true))
}
/// Print data tree in the specified format to a bytes vector.
fn print_bytes(
&self,
format: DataFormat,
options: DataPrinterFlags,
) -> Result<Vec<u8>> {
let mut cstr = std::ptr::null_mut();
let cstr_ptr = &mut cstr;
let ret = unsafe {
ffi::lyd_print_mem(
cstr_ptr,
self.raw(),
format as u32,
options.bits(),
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context()));
}
let bytes = match format {
DataFormat::XML | DataFormat::JSON => {
// Convert the null-terminated C string to a vector of bytes.
// After converting to bytes, manually add a null terminator.
let mut bytes =
unsafe { CStr::from_ptr(cstr) }.to_bytes().to_vec();
bytes.push(0);
bytes
}
DataFormat::LYB => {
// Get the length of the LYB data.
let len = unsafe { ffi::lyd_lyb_data_length(cstr) };
// For the LYB data format, `cstr` isn't null-terminated.
// Create a byte slice from the raw parts and convert it to a
// vector.
unsafe { std::slice::from_raw_parts(cstr as _, len as _) }
.to_vec()
}
};
Ok(bytes)
}
}
// ===== impl DataTree =====
enum CtxOrExt<'a> {
C(&'a Context),
E(&'a SchemaExtInstance<'a>),
}
impl<'a> DataTree<'a> {
/// Create new empty data tree.
pub fn new(context: &'a Context) -> DataTree<'a> {
DataTree {
context,
raw: std::ptr::null_mut(),
}
}
/// Returns a mutable raw pointer to the underlying C library representation
/// of the root node of the YANG data tree.
pub fn into_raw(self) -> *mut ffi::lyd_node {
ManuallyDrop::new(self).raw
}
unsafe fn reroot(&mut self, raw: *mut ffi::lyd_node) {
if self.raw.is_null() {
let mut dnode = DataNodeRef::from_raw(self, raw);
while let Some(parent) = dnode.parent() {
dnode = parent;
}
self.raw = dnode.raw();
}
self.raw = ffi::lyd_first_sibling(self.raw);
}
/// Parse (and validate) input data as a YANG data tree.
#[cfg(not(target_os = "windows"))]
pub fn parse_file<F: std::os::unix::io::AsRawFd>(
context: &'a Context,
fd: F,
format: DataFormat,
parser_options: DataParserFlags,
validation_options: DataValidationFlags,
) -> Result<DataTree<'a>> {
let mut rnode = std::ptr::null_mut();
let rnode_ptr = &mut rnode;
let ret = unsafe {
ffi::lyd_parse_data_fd(
context.raw,
fd.as_raw_fd(),
format as u32,
parser_options.bits(),
validation_options.bits(),
rnode_ptr,
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(context));
}
Ok(unsafe { DataTree::from_raw(context, rnode) })
}
#[cfg(target_os = "windows")]
pub fn parse_file(
context: &'a Context,
file: impl std::os::windows::io::AsRawHandle,
format: DataFormat,
parser_options: DataParserFlags,
validation_options: DataValidationFlags,
) -> Result<DataTree<'a>> {
use libc::open_osfhandle;
let raw_handle = file.as_raw_handle();
let fd = unsafe { open_osfhandle(raw_handle as isize, 0) };
let mut rnode = std::ptr::null_mut();
let rnode_ptr = &mut rnode;
let ret = unsafe {
ffi::lyd_parse_data_fd(
context.raw,
fd,
format as u32,
parser_options.bits(),
validation_options.bits(),
rnode_ptr,
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(context));
}
Ok(unsafe { DataTree::from_raw(context, rnode) })
}
fn _parse_string(
ctx_or_ext: CtxOrExt<'a>,
data: impl AsRef<[u8]>,
format: DataFormat,
parser_options: DataParserFlags,
validation_options: DataValidationFlags,
) -> Result<DataTree<'a>> {
let mut rnode = std::ptr::null_mut();
let rnode_ptr = &mut rnode;
let context = match ctx_or_ext {
CtxOrExt::C(c) => c,
CtxOrExt::E(e) => e.context,
};
// Create input handler.
let cdata;
let mut ly_in = std::ptr::null_mut();
let ret = match format {
DataFormat::XML | DataFormat::JSON => unsafe {
cdata = CString::new(data.as_ref()).unwrap();
ffi::ly_in_new_memory(cdata.as_ptr() as _, &mut ly_in)
},
DataFormat::LYB => unsafe {
ffi::ly_in_new_memory(data.as_ref().as_ptr() as _, &mut ly_in)
},
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(context));
}
let ret = unsafe {
match ctx_or_ext {
CtxOrExt::C(c) => ffi::lyd_parse_data(
c.raw,
std::ptr::null_mut(),
ly_in,
format as u32,
parser_options.bits(),
validation_options.bits(),
rnode_ptr,
),
CtxOrExt::E(e) => ffi::lyd_parse_ext_data(
e.raw,
std::ptr::null_mut(),
ly_in,
format as u32,
parser_options.bits(),
validation_options.bits(),
rnode_ptr,
),
}
};
unsafe { ffi::ly_in_free(ly_in, 0) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(context));
}
Ok(unsafe { DataTree::from_raw(context, rnode) })
}
/// Parse (and validate) input data as a YANG data tree.
pub fn parse_string(
context: &'a Context,
data: impl AsRef<[u8]>,
format: DataFormat,
parser_options: DataParserFlags,
validation_options: DataValidationFlags,
) -> Result<DataTree<'a>> {
DataTree::_parse_string(
CtxOrExt::C(context),
data,
format,
parser_options,
validation_options,
)
}
/// Parse input data as an extension data tree using the given schema
/// extension.
pub fn parse_ext_string(
ext: &'a SchemaExtInstance<'a>,
data: impl AsRef<[u8]>,
format: DataFormat,
parser_options: DataParserFlags,
validation_options: DataValidationFlags,
) -> Result<DataTree<'a>> {
DataTree::_parse_string(
CtxOrExt::E(ext),
data,
format,
parser_options,
validation_options,
)
}
fn _parse_op_string(
ctx_or_ext: CtxOrExt<'a>,
data: impl AsRef<[u8]>,
format: DataFormat,
op: DataOperation,
) -> Result<DataTree<'a>> {
let mut rnode = std::ptr::null_mut();
let rnode_ptr = &mut rnode;
let context = match ctx_or_ext {
CtxOrExt::C(c) => c,
CtxOrExt::E(e) => e.context,
};
// Create input handler.
let cdata = CString::new(data.as_ref()).unwrap();
let mut ly_in = std::ptr::null_mut();
let ret =
unsafe { ffi::ly_in_new_memory(cdata.as_ptr() as _, &mut ly_in) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(context));
}
let ret = unsafe {
match ctx_or_ext {
CtxOrExt::C(c) => ffi::lyd_parse_op(
c.raw,
std::ptr::null_mut(),
ly_in,
format as u32,
op as u32,
rnode_ptr,
std::ptr::null_mut(),
),
CtxOrExt::E(e) => ffi::lyd_parse_ext_op(
e.raw,
std::ptr::null_mut(),
ly_in,
format as u32,
op as u32,
rnode_ptr,
std::ptr::null_mut(),
),
}
};
unsafe { ffi::ly_in_free(ly_in, 0) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(context));
}
Ok(unsafe { DataTree::from_raw(context, rnode) })
}
/// Parse YANG data into an operation data tree.
pub fn parse_op_string(
context: &'a Context,
data: impl AsRef<[u8]>,
format: DataFormat,
op: DataOperation,
) -> Result<DataTree<'a>> {
DataTree::_parse_op_string(CtxOrExt::C(context), data, format, op)
}
/// Parse op data as an extension data tree using the given schema
/// extension. Parse input data into an operation data tree.
pub fn parse_op_ext_string(
ext: &'a SchemaExtInstance<'a>,
data: impl AsRef<[u8]>,
format: DataFormat,
op: DataOperation,
) -> Result<DataTree<'a>> {
DataTree::_parse_op_string(CtxOrExt::E(ext), data, format, op)
}
/// Returns a reference to the fist top-level data node, unless the data
/// tree is empty.
pub fn reference(&self) -> Option<DataNodeRef<'_>> {
if self.raw.is_null() {
None
} else {
Some(DataNodeRef {
tree: self,
raw: self.raw,
})
}
}
/// Create a new node or modify existing one in the data tree based on a
/// path.
///
/// If path points to a list key and the list instance does not exist,
/// the key value from the predicate is used and value is ignored. Also,
/// if a leaf-list is being created and both a predicate is defined in
/// path and value is set, the predicate is preferred.
///
/// For key-less lists and state leaf-lists, positional predicates can be
/// used. If no preciate is used for these nodes, they are always created.
///
/// The output parameter can be used to change the behavior to ignore
/// RPC/action input schema nodes and use only output ones.
///
/// Returns the last created or modified node (if any).
pub fn new_path(
&mut self,
path: &str,
value: Option<&str>,
output: bool,
) -> Result<Option<DataNodeRef<'_>>> {
let path = CString::new(path).unwrap();
let mut rnode_root = std::ptr::null_mut();
let mut rnode = std::ptr::null_mut();
let rnode_root_ptr = &mut rnode_root;
let rnode_ptr = &mut rnode;
let value_cstr;
let (value_ptr, value_len) = match value {
Some(value) => {
value_cstr = CString::new(value).unwrap();
(value_cstr.as_ptr(), value.len())
}
None => (std::ptr::null(), 0),
};
let mut options = ffi::LYD_NEW_PATH_UPDATE;
if output {
options |= ffi::LYD_NEW_VAL_OUTPUT;
}
let ret = unsafe {
ffi::lyd_new_path2(
self.raw(),
self.context().raw,
path.as_ptr(),
value_ptr as *const c_void,
value_len,
ffi::LYD_ANYDATA_VALUETYPE::LYD_ANYDATA_STRING,
options,
rnode_root_ptr,
rnode_ptr,
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context()));
}
// Update top-level sibling.
if self.raw.is_null() {
self.raw = unsafe { ffi::lyd_first_sibling(rnode_root) };
} else {
self.raw = unsafe { ffi::lyd_first_sibling(self.raw) };
}
Ok(unsafe { DataNodeRef::from_raw_opt(self.tree(), rnode) })
}
/// Remove a data node.
pub fn remove(&mut self, path: &str) -> Result<()> {
let dnode = self.find_path(path)?;
unsafe { ffi::lyd_free_tree(dnode.raw) };
Ok(())
}
/// Fully validate the data tree.
pub fn validate(&mut self, options: DataValidationFlags) -> Result<()> {
let ret = unsafe {
ffi::lyd_validate_all(
&mut self.raw,
self.context.raw,
options.bits(),
std::ptr::null_mut(),
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context));
}
Ok(())
}
/// Create a copy of the data tree.
pub fn duplicate<'b>(&'b self) -> Result<DataTree<'a>> {
let mut dup = std::ptr::null_mut();
let dup_ptr = &mut dup;
// Special handling for empty data trees.
if self.raw.is_null() {
return Ok(unsafe {
DataTree::from_raw(self.context, std::ptr::null_mut())
});
}
let options = ffi::LYD_DUP_RECURSIVE | ffi::LYD_DUP_WITH_FLAGS;
let ret = unsafe {
ffi::lyd_dup_siblings(
self.raw,
std::ptr::null_mut(),
options,
dup_ptr,
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context));
}
Ok(unsafe { DataTree::from_raw(self.context, dup) })
}
/// Merge the source data tree into the target data tree. Merge may not be
/// complete until validation is called on the resulting data tree (data
/// from more cases may be present, default and non-default values).
pub fn merge(&mut self, source: &DataTree<'_>) -> Result<()> {
// Special handling for empty data trees.
if self.raw.is_null() {
let mut new_tree = source.duplicate()?;
self.raw = new_tree.raw;
new_tree.raw = std::ptr::null_mut();
} else {
let options = 0u16;
let ret = unsafe {
ffi::lyd_merge_siblings(&mut self.raw, source.raw, options)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context));
}
}
Ok(())
}
/// Add any missing implicit nodes. Default nodes with a false "when" are
/// not added.
pub fn add_implicit(&mut self, options: DataImplicitFlags) -> Result<()> {
let ret = unsafe {
ffi::lyd_new_implicit_all(
&mut self.raw,
self.context.raw,
options.bits(),
std::ptr::null_mut(),
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context));
}
// Update top-level sibling.
self.raw = unsafe { ffi::lyd_first_sibling(self.raw) };
Ok(())
}
/// Learn the differences between 2 data trees.
///
/// The resulting diff is represented as a data tree with specific metadata
/// from the internal 'yang' module. Most importantly, every node has an
/// effective 'operation' metadata. If there is none defined on the
/// node, it inherits the operation from the nearest parent. Top-level nodes
/// must always have the 'operation' metadata defined. Additional
/// metadata ('orig-default', 'value', 'orig-value', 'key', 'orig-key')
/// are used for storing more information about the value in the first
/// or the second tree.
pub fn diff(
&self,
dtree: &DataTree<'a>,
options: DataDiffFlags,
) -> Result<DataDiff<'a>> {
let mut rnode = std::ptr::null_mut();
let rnode_ptr = &mut rnode;
let ret = unsafe {
ffi::lyd_diff_siblings(
self.raw,
dtree.raw,
options.bits(),
rnode_ptr,
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context));
}
Ok(DataDiff {
tree: unsafe { DataTree::from_raw(dtree.context, rnode) },
})
}
/// Apply the whole diff tree on the data tree.
pub fn diff_apply(&mut self, diff: &DataDiff<'a>) -> Result<()> {
let ret =
unsafe { ffi::lyd_diff_apply_all(&mut self.raw, diff.tree.raw) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self.context));
}
Ok(())
}
/// Returns an iterator over all elements in the data tree and its sibling
/// trees (depth-first search algorithm).
pub fn traverse(&self) -> impl Iterator<Item = DataNodeRef<'_>> {
let top = Siblings::new(self.reference());
top.flat_map(|dnode| dnode.traverse())
}
}
impl<'a> Data<'a> for DataTree<'a> {
fn tree(&self) -> &DataTree<'a> {
self
}
fn raw(&self) -> *mut ffi::lyd_node {
self.raw
}
}
unsafe impl<'a> Binding<'a> for DataTree<'a> {
type CType = ffi::lyd_node;
type Container = Context;
unsafe fn from_raw(
context: &'a Context,
raw: *mut ffi::lyd_node,
) -> DataTree<'a> {
DataTree { context, raw }
}
}
unsafe impl Send for DataTree<'_> {}
unsafe impl Sync for DataTree<'_> {}
impl Drop for DataTree<'_> {
fn drop(&mut self) {
unsafe { ffi::lyd_free_all(self.raw) };
}
}
// ===== impl DataTreeOwningRef =====
impl<'a> DataTreeOwningRef<'a> {
unsafe fn from_raw(tree: DataTree<'a>, raw: *mut ffi::lyd_node) -> Self {
DataTreeOwningRef { tree, raw }
}
/// Get a temporary DataTreeOwningRef from a raw lyd_node pointer.
///
/// The intent of this function is to create a temporary DataTreeOwningRef
/// from a raw lyd_node pointer passed to user that lives in a DataTree they
/// do not own (e.g., as a C callback argument).
///
/// # Safety:
///
/// The user must still have access and pass in the context that the tree
/// of the data node was created from. The function will panic if the
/// context does not match.
///
/// The returned value is only valid for as long as the node's tree and the
/// node itself are valid.
pub unsafe fn from_raw_node(
context: &Context,
raw: *mut ffi::lyd_node,
) -> std::mem::ManuallyDrop<DataTreeOwningRef<'_>> {
if (*(*(*raw).schema).module).ctx != context.raw {
panic!("raw node context differs from passed in context");
}
let mut tree = DataTree::new(context);
tree.reroot(raw);
std::mem::ManuallyDrop::new(DataTreeOwningRef { tree, raw })
}
/// Create a new node or modify existing one in the data tree based on a
/// path.
///
/// If path points to a list key and the list instance does not exist,
/// the key value from the predicate is used and value is ignored. Also,
/// if a leaf-list is being created and both a predicate is defined in
/// path and value is set, the predicate is preferred.
///
/// For key-less lists and state leaf-lists, positional predicates can be
/// used. If no preciate is used for these nodes, they are always created.
///
/// The output parameter can be used to change the behavior to ignore
/// RPC/action input schema nodes and use only output ones.
///
/// Returns the last created or modified node (if any).
pub fn new_path(
context: &'a Context,
path: &str,
value: Option<&str>,
output: bool,
) -> Result<Self> {
let mut tree = DataTree::new(context);
let raw = {
match tree.new_path(path, value, output)? {
Some(node) => node.raw,
None => tree.find_path(path)?.raw,
}
};
Ok(unsafe { DataTreeOwningRef::from_raw(tree, raw) })
}
/// Obtain a DataNodeRef that the DataTreeOwningRef is referencing.
pub fn noderef(&'a self) -> DataNodeRef<'a> {
DataNodeRef {
tree: &self.tree,