-
Notifications
You must be signed in to change notification settings - Fork 240
/
Copy pathmod.rs
1529 lines (1398 loc) · 50.2 KB
/
mod.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
//! Defines zero-copy XML events used throughout this library.
//!
//! A XML event often represents part of a XML element.
//! They occur both during reading and writing and are
//! usually used with the stream-oriented API.
//!
//! For example, the XML element
//! ```xml
//! <name attr="value">Inner text</name>
//! ```
//! consists of the three events `Start`, `Text` and `End`.
//! They can also represent other parts in an XML document like the
//! XML declaration. Each Event usually contains further information,
//! like the tag name, the attribute or the inner text.
//!
//! See [`Event`] for a list of all possible events.
//!
//! # Reading
//! When reading a XML stream, the events are emitted by [`Reader::read_event`]
//! and [`Reader::read_event_into`]. You must listen
//! for the different types of events you are interested in.
//!
//! See [`Reader`] for further information.
//!
//! # Writing
//! When writing the XML document, you must create the XML element
//! by constructing the events it consists of and pass them to the writer
//! sequentially.
//!
//! See [`Writer`] for further information.
//!
//! [`Reader::read_event`]: crate::reader::Reader::read_event
//! [`Reader::read_event_into`]: crate::reader::Reader::read_event_into
//! [`Reader`]: crate::reader::Reader
//! [`Writer`]: crate::writer::Writer
//! [`Event`]: crate::events::Event
pub mod attributes;
#[cfg(feature = "encoding")]
use encoding_rs::Encoding;
use std::borrow::Cow;
use std::fmt::{self, Debug, Formatter};
use std::iter::FusedIterator;
use std::mem::replace;
use std::ops::Deref;
use std::str::from_utf8;
use crate::encoding::{Decoder, EncodingError};
use crate::errors::{Error, IllFormedError};
use crate::escape::{
escape, minimal_escape, partial_escape, resolve_predefined_entity, unescape_with,
};
use crate::name::{LocalName, QName};
#[cfg(feature = "serialize")]
use crate::utils::CowRef;
use crate::utils::{name_len, trim_xml_end, trim_xml_start, write_cow_string, Bytes};
use attributes::{AttrError, Attribute, Attributes};
/// Opening tag data (`Event::Start`), with optional attributes: `<name attr="value">`.
///
/// The name can be accessed using the [`name`] or [`local_name`] methods.
/// An iterator over the attributes is returned by the [`attributes`] method.
///
/// This event implements `Deref<Target = [u8]>`. The `deref()` implementation
/// returns the content of this event between `<` and `>` or `/>`:
///
/// ```
/// # use quick_xml::events::{BytesStart, Event};
/// # use quick_xml::reader::Reader;
/// # use pretty_assertions::assert_eq;
/// // Remember, that \ at the end of string literal strips
/// // all space characters to the first non-space character
/// let mut reader = Reader::from_str("\
/// <element a1 = 'val1' a2=\"val2\" />\
/// <element a1 = 'val1' a2=\"val2\" >"
/// );
/// let content = "element a1 = 'val1' a2=\"val2\" ";
/// let event = BytesStart::from_content(content, 7);
///
/// assert_eq!(reader.read_event().unwrap(), Event::Empty(event.borrow()));
/// assert_eq!(reader.read_event().unwrap(), Event::Start(event.borrow()));
/// // deref coercion of &BytesStart to &[u8]
/// assert_eq!(&event as &[u8], content.as_bytes());
/// // AsRef<[u8]> for &T + deref coercion
/// assert_eq!(event.as_ref(), content.as_bytes());
/// ```
///
/// [`name`]: Self::name
/// [`local_name`]: Self::local_name
/// [`attributes`]: Self::attributes
#[derive(Clone, Eq, PartialEq)]
pub struct BytesStart<'a> {
/// content of the element, before any utf8 conversion
pub(crate) buf: Cow<'a, [u8]>,
/// end of the element name, the name starts at that the start of `buf`
pub(crate) name_len: usize,
}
impl<'a> BytesStart<'a> {
/// Internal constructor, used by `Reader`. Supplies data in reader's encoding
#[inline]
pub(crate) const fn wrap(content: &'a [u8], name_len: usize) -> Self {
BytesStart {
buf: Cow::Borrowed(content),
name_len,
}
}
/// Creates a new `BytesStart` from the given name.
///
/// # Warning
///
/// `name` must be a valid name.
#[inline]
pub fn new<C: Into<Cow<'a, str>>>(name: C) -> Self {
let buf = str_cow_to_bytes(name);
BytesStart {
name_len: buf.len(),
buf,
}
}
/// Creates a new `BytesStart` from the given content (name + attributes).
///
/// # Warning
///
/// `&content[..name_len]` must be a valid name, and the remainder of `content`
/// must be correctly-formed attributes. Neither are checked, it is possible
/// to generate invalid XML if `content` or `name_len` are incorrect.
#[inline]
pub fn from_content<C: Into<Cow<'a, str>>>(content: C, name_len: usize) -> Self {
BytesStart {
buf: str_cow_to_bytes(content),
name_len,
}
}
/// Converts the event into an owned event.
pub fn into_owned(self) -> BytesStart<'static> {
BytesStart {
buf: Cow::Owned(self.buf.into_owned()),
name_len: self.name_len,
}
}
/// Converts the event into an owned event without taking ownership of Event
pub fn to_owned(&self) -> BytesStart<'static> {
BytesStart {
buf: Cow::Owned(self.buf.clone().into_owned()),
name_len: self.name_len,
}
}
/// Converts the event into a borrowed event. Most useful when paired with [`to_end`].
///
/// # Example
///
/// ```
/// use quick_xml::events::{BytesStart, Event};
/// # use quick_xml::writer::Writer;
/// # use quick_xml::Error;
///
/// struct SomeStruct<'a> {
/// attrs: BytesStart<'a>,
/// // ...
/// }
/// # impl<'a> SomeStruct<'a> {
/// # fn example(&self) -> Result<(), Error> {
/// # let mut writer = Writer::new(Vec::new());
///
/// writer.write_event(Event::Start(self.attrs.borrow()))?;
/// // ...
/// writer.write_event(Event::End(self.attrs.to_end()))?;
/// # Ok(())
/// # }}
/// ```
///
/// [`to_end`]: Self::to_end
pub fn borrow(&self) -> BytesStart {
BytesStart {
buf: Cow::Borrowed(&self.buf),
name_len: self.name_len,
}
}
/// Creates new paired close tag
#[inline]
pub fn to_end(&self) -> BytesEnd {
BytesEnd::from(self.name())
}
/// Gets the undecoded raw tag name, as present in the input stream.
#[inline]
pub fn name(&self) -> QName {
QName(&self.buf[..self.name_len])
}
/// Gets the undecoded raw local tag name (excluding namespace) as present
/// in the input stream.
///
/// All content up to and including the first `:` character is removed from the tag name.
#[inline]
pub fn local_name(&self) -> LocalName {
self.name().into()
}
/// Edit the name of the BytesStart in-place
///
/// # Warning
///
/// `name` must be a valid name.
pub fn set_name(&mut self, name: &[u8]) -> &mut BytesStart<'a> {
let bytes = self.buf.to_mut();
bytes.splice(..self.name_len, name.iter().cloned());
self.name_len = name.len();
self
}
/// Gets the undecoded raw tag name, as present in the input stream, which
/// is borrowed either to the input, or to the event.
///
/// # Lifetimes
///
/// - `'a`: Lifetime of the input data from which this event is borrow
/// - `'e`: Lifetime of the concrete event instance
// TODO: We should made this is a part of public API, but with safe wrapped for a name
#[cfg(feature = "serialize")]
pub(crate) fn raw_name<'e>(&'e self) -> CowRef<'a, 'e, [u8]> {
match self.buf {
Cow::Borrowed(b) => CowRef::Input(&b[..self.name_len]),
Cow::Owned(ref o) => CowRef::Slice(&o[..self.name_len]),
}
}
}
/// Attribute-related methods
impl<'a> BytesStart<'a> {
/// Consumes `self` and yield a new `BytesStart` with additional attributes from an iterator.
///
/// The yielded items must be convertible to [`Attribute`] using `Into`.
pub fn with_attributes<'b, I>(mut self, attributes: I) -> Self
where
I: IntoIterator,
I::Item: Into<Attribute<'b>>,
{
self.extend_attributes(attributes);
self
}
/// Add additional attributes to this tag using an iterator.
///
/// The yielded items must be convertible to [`Attribute`] using `Into`.
pub fn extend_attributes<'b, I>(&mut self, attributes: I) -> &mut BytesStart<'a>
where
I: IntoIterator,
I::Item: Into<Attribute<'b>>,
{
for attr in attributes {
self.push_attribute(attr);
}
self
}
/// Adds an attribute to this element.
pub fn push_attribute<'b, A>(&mut self, attr: A)
where
A: Into<Attribute<'b>>,
{
self.buf.to_mut().push(b' ');
self.push_attr(attr.into());
}
/// Remove all attributes from the ByteStart
pub fn clear_attributes(&mut self) -> &mut BytesStart<'a> {
self.buf.to_mut().truncate(self.name_len);
self
}
/// Returns an iterator over the attributes of this tag.
pub fn attributes(&self) -> Attributes {
Attributes::wrap(&self.buf, self.name_len, false)
}
/// Returns an iterator over the HTML-like attributes of this tag (no mandatory quotes or `=`).
pub fn html_attributes(&self) -> Attributes {
Attributes::wrap(&self.buf, self.name_len, true)
}
/// Gets the undecoded raw string with the attributes of this tag as a `&[u8]`,
/// including the whitespace after the tag name if there is any.
#[inline]
pub fn attributes_raw(&self) -> &[u8] {
&self.buf[self.name_len..]
}
/// Try to get an attribute
pub fn try_get_attribute<N: AsRef<[u8]> + Sized>(
&'a self,
attr_name: N,
) -> Result<Option<Attribute<'a>>, AttrError> {
for a in self.attributes().with_checks(false) {
let a = a?;
if a.key.as_ref() == attr_name.as_ref() {
return Ok(Some(a));
}
}
Ok(None)
}
/// Adds an attribute to this element.
pub(crate) fn push_attr<'b>(&mut self, attr: Attribute<'b>) {
let bytes = self.buf.to_mut();
bytes.extend_from_slice(attr.key.as_ref());
bytes.extend_from_slice(b"=\"");
// FIXME: need to escape attribute content
bytes.extend_from_slice(attr.value.as_ref());
bytes.push(b'"');
}
/// Adds new line in existing element
pub(crate) fn push_newline(&mut self) {
self.buf.to_mut().push(b'\n');
}
/// Adds indentation bytes in existing element
pub(crate) fn push_indent(&mut self, indent: &[u8]) {
self.buf.to_mut().extend_from_slice(indent);
}
}
impl<'a> Debug for BytesStart<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "BytesStart {{ buf: ")?;
write_cow_string(f, &self.buf)?;
write!(f, ", name_len: {} }}", self.name_len)
}
}
impl<'a> Deref for BytesStart<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.buf
}
}
impl<'a> From<QName<'a>> for BytesStart<'a> {
#[inline]
fn from(name: QName<'a>) -> Self {
let name = name.into_inner();
Self::wrap(name, name.len())
}
}
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for BytesStart<'a> {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let s = <&str>::arbitrary(u)?;
if s.is_empty() || !s.chars().all(char::is_alphanumeric) {
return Err(arbitrary::Error::IncorrectFormat);
}
let mut result = Self::new(s);
result.extend_attributes(Vec::<(&str, &str)>::arbitrary(u)?.into_iter());
Ok(result)
}
fn size_hint(depth: usize) -> (usize, Option<usize>) {
return <&str as arbitrary::Arbitrary>::size_hint(depth);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// Closing tag data (`Event::End`): `</name>`.
///
/// The name can be accessed using the [`name`] or [`local_name`] methods.
///
/// This event implements `Deref<Target = [u8]>`. The `deref()` implementation
/// returns the content of this event between `</` and `>`.
///
/// Note, that inner text will not contain `>` character inside:
///
/// ```
/// # use quick_xml::events::{BytesEnd, Event};
/// # use quick_xml::reader::Reader;
/// # use pretty_assertions::assert_eq;
/// let mut reader = Reader::from_str(r#"<element></element a1 = 'val1' a2="val2" >"#);
/// // Note, that this entire string considered as a .name()
/// let content = "element a1 = 'val1' a2=\"val2\" ";
/// let event = BytesEnd::new(content);
///
/// reader.config_mut().trim_markup_names_in_closing_tags = false;
/// reader.config_mut().check_end_names = false;
/// reader.read_event().unwrap(); // Skip `<element>`
///
/// assert_eq!(reader.read_event().unwrap(), Event::End(event.borrow()));
/// assert_eq!(event.name().as_ref(), content.as_bytes());
/// // deref coercion of &BytesEnd to &[u8]
/// assert_eq!(&event as &[u8], content.as_bytes());
/// // AsRef<[u8]> for &T + deref coercion
/// assert_eq!(event.as_ref(), content.as_bytes());
/// ```
///
/// [`name`]: Self::name
/// [`local_name`]: Self::local_name
#[derive(Clone, Eq, PartialEq)]
pub struct BytesEnd<'a> {
name: Cow<'a, [u8]>,
}
impl<'a> BytesEnd<'a> {
/// Internal constructor, used by `Reader`. Supplies data in reader's encoding
#[inline]
pub(crate) const fn wrap(name: Cow<'a, [u8]>) -> Self {
BytesEnd { name }
}
/// Creates a new `BytesEnd` borrowing a slice.
///
/// # Warning
///
/// `name` must be a valid name.
#[inline]
pub fn new<C: Into<Cow<'a, str>>>(name: C) -> Self {
Self::wrap(str_cow_to_bytes(name))
}
/// Converts the event into an owned event.
pub fn into_owned(self) -> BytesEnd<'static> {
BytesEnd {
name: Cow::Owned(self.name.into_owned()),
}
}
/// Converts the event into a borrowed event.
#[inline]
pub fn borrow(&self) -> BytesEnd {
BytesEnd {
name: Cow::Borrowed(&self.name),
}
}
/// Gets the undecoded raw tag name, as present in the input stream.
#[inline]
pub fn name(&self) -> QName {
QName(&self.name)
}
/// Gets the undecoded raw local tag name (excluding namespace) as present
/// in the input stream.
///
/// All content up to and including the first `:` character is removed from the tag name.
#[inline]
pub fn local_name(&self) -> LocalName {
self.name().into()
}
}
impl<'a> Debug for BytesEnd<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "BytesEnd {{ name: ")?;
write_cow_string(f, &self.name)?;
write!(f, " }}")
}
}
impl<'a> Deref for BytesEnd<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.name
}
}
impl<'a> From<QName<'a>> for BytesEnd<'a> {
#[inline]
fn from(name: QName<'a>) -> Self {
Self::wrap(name.into_inner().into())
}
}
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for BytesEnd<'a> {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self::new(<&str>::arbitrary(u)?))
}
fn size_hint(depth: usize) -> (usize, Option<usize>) {
return <&str as arbitrary::Arbitrary>::size_hint(depth);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// Data from various events (most notably, `Event::Text`) that stored in XML
/// in escaped form. Internally data is stored in escaped form.
///
/// This event implements `Deref<Target = [u8]>`. The `deref()` implementation
/// returns the content of this event. In case of comment this is everything
/// between `<!--` and `-->` and the text of comment will not contain `-->` inside.
/// In case of DTD this is everything between `<!DOCTYPE` + spaces and closing `>`
/// (i.e. in case of DTD the first character is never space):
///
/// ```
/// # use quick_xml::events::{BytesText, Event};
/// # use quick_xml::reader::Reader;
/// # use pretty_assertions::assert_eq;
/// // Remember, that \ at the end of string literal strips
/// // all space characters to the first non-space character
/// let mut reader = Reader::from_str("\
/// <!DOCTYPE comment or text >\
/// comment or text \
/// <!--comment or text -->"
/// );
/// let content = "comment or text ";
/// let event = BytesText::new(content);
///
/// assert_eq!(reader.read_event().unwrap(), Event::DocType(event.borrow()));
/// assert_eq!(reader.read_event().unwrap(), Event::Text(event.borrow()));
/// assert_eq!(reader.read_event().unwrap(), Event::Comment(event.borrow()));
/// // deref coercion of &BytesText to &[u8]
/// assert_eq!(&event as &[u8], content.as_bytes());
/// // AsRef<[u8]> for &T + deref coercion
/// assert_eq!(event.as_ref(), content.as_bytes());
/// ```
#[derive(Clone, Eq, PartialEq)]
pub struct BytesText<'a> {
/// Escaped then encoded content of the event. Content is encoded in the XML
/// document encoding when event comes from the reader and should be in the
/// document encoding when event passed to the writer
content: Cow<'a, [u8]>,
/// Encoding in which the `content` is stored inside the event
decoder: Decoder,
}
impl<'a> BytesText<'a> {
/// Creates a new `BytesText` from an escaped byte sequence in the specified encoding.
#[inline]
pub(crate) fn wrap<C: Into<Cow<'a, [u8]>>>(content: C, decoder: Decoder) -> Self {
Self {
content: content.into(),
decoder,
}
}
/// Creates a new `BytesText` from an escaped string.
#[inline]
pub fn from_escaped<C: Into<Cow<'a, str>>>(content: C) -> Self {
Self::wrap(str_cow_to_bytes(content), Decoder::utf8())
}
/// Creates a new `BytesText` from a string. The string is expected not to
/// be escaped.
#[inline]
pub fn new(content: &'a str) -> Self {
Self::from_escaped(escape(content))
}
/// Ensures that all data is owned to extend the object's lifetime if
/// necessary.
#[inline]
pub fn into_owned(self) -> BytesText<'static> {
BytesText {
content: self.content.into_owned().into(),
decoder: self.decoder,
}
}
/// Extracts the inner `Cow` from the `BytesText` event container.
#[inline]
pub fn into_inner(self) -> Cow<'a, [u8]> {
self.content
}
/// Converts the event into a borrowed event.
#[inline]
pub fn borrow(&self) -> BytesText {
BytesText {
content: Cow::Borrowed(&self.content),
decoder: self.decoder,
}
}
/// Decodes then unescapes the content of the event.
///
/// This will allocate if the value contains any escape sequences or in
/// non-UTF-8 encoding.
pub fn unescape(&self) -> Result<Cow<'a, str>, Error> {
self.unescape_with(resolve_predefined_entity)
}
/// Decodes then unescapes the content of the event with custom entities.
///
/// This will allocate if the value contains any escape sequences or in
/// non-UTF-8 encoding.
pub fn unescape_with<'entity>(
&self,
resolve_entity: impl FnMut(&str) -> Option<&'entity str>,
) -> Result<Cow<'a, str>, Error> {
let decoded = self.decoder.decode_cow(&self.content)?;
match unescape_with(&decoded, resolve_entity)? {
// Because result is borrowed, no replacements was done and we can use original string
Cow::Borrowed(_) => Ok(decoded),
Cow::Owned(s) => Ok(s.into()),
}
}
/// Removes leading XML whitespace bytes from text content.
///
/// Returns `true` if content is empty after that
pub fn inplace_trim_start(&mut self) -> bool {
self.content = trim_cow(
replace(&mut self.content, Cow::Borrowed(b"")),
trim_xml_start,
);
self.content.is_empty()
}
/// Removes trailing XML whitespace bytes from text content.
///
/// Returns `true` if content is empty after that
pub fn inplace_trim_end(&mut self) -> bool {
self.content = trim_cow(replace(&mut self.content, Cow::Borrowed(b"")), trim_xml_end);
self.content.is_empty()
}
}
impl<'a> Debug for BytesText<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "BytesText {{ content: ")?;
write_cow_string(f, &self.content)?;
write!(f, " }}")
}
}
impl<'a> Deref for BytesText<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.content
}
}
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for BytesText<'a> {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let s = <&str>::arbitrary(u)?;
if !s.chars().all(char::is_alphanumeric) {
return Err(arbitrary::Error::IncorrectFormat);
}
Ok(Self::new(s))
}
fn size_hint(depth: usize) -> (usize, Option<usize>) {
return <&str as arbitrary::Arbitrary>::size_hint(depth);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// CDATA content contains unescaped data from the reader. If you want to write them as a text,
/// [convert](Self::escape) it to [`BytesText`].
///
/// This event implements `Deref<Target = [u8]>`. The `deref()` implementation
/// returns the content of this event between `<![CDATA[` and `]]>`.
///
/// Note, that inner text will not contain `]]>` sequence inside:
///
/// ```
/// # use quick_xml::events::{BytesCData, Event};
/// # use quick_xml::reader::Reader;
/// # use pretty_assertions::assert_eq;
/// let mut reader = Reader::from_str("<![CDATA[ CDATA section ]]>");
/// let content = " CDATA section ";
/// let event = BytesCData::new(content);
///
/// assert_eq!(reader.read_event().unwrap(), Event::CData(event.borrow()));
/// // deref coercion of &BytesCData to &[u8]
/// assert_eq!(&event as &[u8], content.as_bytes());
/// // AsRef<[u8]> for &T + deref coercion
/// assert_eq!(event.as_ref(), content.as_bytes());
/// ```
#[derive(Clone, Eq, PartialEq)]
pub struct BytesCData<'a> {
content: Cow<'a, [u8]>,
/// Encoding in which the `content` is stored inside the event
decoder: Decoder,
}
impl<'a> BytesCData<'a> {
/// Creates a new `BytesCData` from a byte sequence in the specified encoding.
#[inline]
pub(crate) fn wrap<C: Into<Cow<'a, [u8]>>>(content: C, decoder: Decoder) -> Self {
Self {
content: content.into(),
decoder,
}
}
/// Creates a new `BytesCData` from a string.
///
/// # Warning
///
/// `content` must not contain the `]]>` sequence. You can use
/// [`BytesCData::escaped`] to escape the content instead.
#[inline]
pub fn new<C: Into<Cow<'a, str>>>(content: C) -> Self {
Self::wrap(str_cow_to_bytes(content), Decoder::utf8())
}
/// Creates an iterator of `BytesCData` from a string.
///
/// If a string contains `]]>`, it needs to be split into multiple `CDATA`
/// sections, splitting the `]]` and `>` characters, because the CDATA closing
/// sequence cannot be escaped. This iterator yields a `BytesCData` instance
/// for each of those sections.
///
/// # Examples
///
/// ```
/// # use quick_xml::events::BytesCData;
/// # use pretty_assertions::assert_eq;
/// let content = "";
/// let cdata = BytesCData::escaped(content).collect::<Vec<_>>();
/// assert_eq!(cdata, &[BytesCData::new("")]);
///
/// let content = "Certain tokens like ]]> can be difficult and <invalid>";
/// let cdata = BytesCData::escaped(content).collect::<Vec<_>>();
/// assert_eq!(cdata, &[
/// BytesCData::new("Certain tokens like ]]"),
/// BytesCData::new("> can be difficult and <invalid>"),
/// ]);
///
/// let content = "foo]]>bar]]>baz]]>quux";
/// let cdata = BytesCData::escaped(content).collect::<Vec<_>>();
/// assert_eq!(cdata, &[
/// BytesCData::new("foo]]"),
/// BytesCData::new(">bar]]"),
/// BytesCData::new(">baz]]"),
/// BytesCData::new(">quux"),
/// ]);
/// ```
#[inline]
pub fn escaped(content: &'a str) -> CDataIterator<'a> {
CDataIterator {
unprocessed: content.as_bytes(),
finished: false,
}
}
/// Ensures that all data is owned to extend the object's lifetime if
/// necessary.
#[inline]
pub fn into_owned(self) -> BytesCData<'static> {
BytesCData {
content: self.content.into_owned().into(),
decoder: self.decoder,
}
}
/// Extracts the inner `Cow` from the `BytesCData` event container.
#[inline]
pub fn into_inner(self) -> Cow<'a, [u8]> {
self.content
}
/// Converts the event into a borrowed event.
#[inline]
pub fn borrow(&self) -> BytesCData {
BytesCData {
content: Cow::Borrowed(&self.content),
decoder: self.decoder,
}
}
/// Converts this CDATA content to an escaped version, that can be written
/// as an usual text in XML.
///
/// This function performs following replacements:
///
/// | Character | Replacement
/// |-----------|------------
/// | `<` | `<`
/// | `>` | `>`
/// | `&` | `&`
/// | `'` | `'`
/// | `"` | `"`
pub fn escape(self) -> Result<BytesText<'a>, EncodingError> {
let decoded = self.decode()?;
Ok(BytesText::wrap(
match escape(decoded) {
Cow::Borrowed(escaped) => Cow::Borrowed(escaped.as_bytes()),
Cow::Owned(escaped) => Cow::Owned(escaped.into_bytes()),
},
Decoder::utf8(),
))
}
/// Converts this CDATA content to an escaped version, that can be written
/// as an usual text in XML.
///
/// In XML text content, it is allowed (though not recommended) to leave
/// the quote special characters `"` and `'` unescaped.
///
/// This function performs following replacements:
///
/// | Character | Replacement
/// |-----------|------------
/// | `<` | `<`
/// | `>` | `>`
/// | `&` | `&`
pub fn partial_escape(self) -> Result<BytesText<'a>, EncodingError> {
let decoded = self.decode()?;
Ok(BytesText::wrap(
match partial_escape(decoded) {
Cow::Borrowed(escaped) => Cow::Borrowed(escaped.as_bytes()),
Cow::Owned(escaped) => Cow::Owned(escaped.into_bytes()),
},
Decoder::utf8(),
))
}
/// Converts this CDATA content to an escaped version, that can be written
/// as an usual text in XML. This method escapes only those characters that
/// must be escaped according to the [specification].
///
/// This function performs following replacements:
///
/// | Character | Replacement
/// |-----------|------------
/// | `<` | `<`
/// | `&` | `&`
///
/// [specification]: https://www.w3.org/TR/xml11/#syntax
pub fn minimal_escape(self) -> Result<BytesText<'a>, EncodingError> {
let decoded = self.decode()?;
Ok(BytesText::wrap(
match minimal_escape(decoded) {
Cow::Borrowed(escaped) => Cow::Borrowed(escaped.as_bytes()),
Cow::Owned(escaped) => Cow::Owned(escaped.into_bytes()),
},
Decoder::utf8(),
))
}
/// Gets content of this text buffer in the specified encoding
pub(crate) fn decode(&self) -> Result<Cow<'a, str>, EncodingError> {
Ok(self.decoder.decode_cow(&self.content)?)
}
}
impl<'a> Debug for BytesCData<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "BytesCData {{ content: ")?;
write_cow_string(f, &self.content)?;
write!(f, " }}")
}
}
impl<'a> Deref for BytesCData<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.content
}
}
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for BytesCData<'a> {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self::new(<&str>::arbitrary(u)?))
}
fn size_hint(depth: usize) -> (usize, Option<usize>) {
return <&str as arbitrary::Arbitrary>::size_hint(depth);
}
}
/// Iterator over `CDATA` sections in a string.
///
/// This iterator is created by the [`BytesCData::escaped`] method.
#[derive(Clone)]
pub struct CDataIterator<'a> {
/// The unprocessed data which should be emitted as `BytesCData` events.
/// At each iteration, the processed data is cut from this slice.
unprocessed: &'a [u8],
finished: bool,
}
impl<'a> Debug for CDataIterator<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("CDataIterator")
.field("unprocessed", &Bytes(self.unprocessed))
.field("finished", &self.finished)
.finish()
}
}
impl<'a> Iterator for CDataIterator<'a> {
type Item = BytesCData<'a>;
fn next(&mut self) -> Option<BytesCData<'a>> {
if self.finished {
return None;
}
for gt in memchr::memchr_iter(b'>', self.unprocessed) {
if self.unprocessed[..gt].ends_with(b"]]") {
let (slice, rest) = self.unprocessed.split_at(gt);
self.unprocessed = rest;
return Some(BytesCData::wrap(slice, Decoder::utf8()));
}
}
self.finished = true;
Some(BytesCData::wrap(self.unprocessed, Decoder::utf8()))
}
}
impl FusedIterator for CDataIterator<'_> {}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// [Processing instructions][PI] (PIs) allow documents to contain instructions for applications.
///
/// This event implements `Deref<Target = [u8]>`. The `deref()` implementation
/// returns the content of this event between `<?` and `?>`.
///
/// Note, that inner text will not contain `?>` sequence inside:
///
/// ```
/// # use quick_xml::events::{BytesPI, Event};
/// # use quick_xml::reader::Reader;
/// # use pretty_assertions::assert_eq;
/// let mut reader = Reader::from_str("<?processing instruction >:-<~ ?>");
/// let content = "processing instruction >:-<~ ";
/// let event = BytesPI::new(content);
///
/// assert_eq!(reader.read_event().unwrap(), Event::PI(event.borrow()));
/// // deref coercion of &BytesPI to &[u8]
/// assert_eq!(&event as &[u8], content.as_bytes());
/// // AsRef<[u8]> for &T + deref coercion
/// assert_eq!(event.as_ref(), content.as_bytes());
/// ```
///
/// [PI]: https://www.w3.org/TR/xml11/#sec-pi
#[derive(Clone, Eq, PartialEq)]
pub struct BytesPI<'a> {
content: BytesStart<'a>,
}
impl<'a> BytesPI<'a> {
/// Creates a new `BytesPI` from a byte sequence in the specified encoding.
#[inline]
pub(crate) const fn wrap(content: &'a [u8], target_len: usize) -> Self {
Self {
content: BytesStart::wrap(content, target_len),
}
}
/// Creates a new `BytesPI` from a string.
///
/// # Warning
///
/// `content` must not contain the `?>` sequence.
#[inline]
pub fn new<C: Into<Cow<'a, str>>>(content: C) -> Self {
let buf = str_cow_to_bytes(content);
let name_len = name_len(&buf);
Self {
content: BytesStart { buf, name_len },
}
}
/// Ensures that all data is owned to extend the object's lifetime if
/// necessary.
#[inline]
pub fn into_owned(self) -> BytesPI<'static> {
BytesPI {
content: self.content.into_owned().into(),
}
}
/// Extracts the inner `Cow` from the `BytesPI` event container.
#[inline]
pub fn into_inner(self) -> Cow<'a, [u8]> {
self.content.buf
}
/// Converts the event into a borrowed event.
#[inline]
pub fn borrow(&self) -> BytesPI {
BytesPI {
content: self.content.borrow(),
}
}
/// A target used to identify the application to which the instruction is directed.
///
/// # Example
///