aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.cargo/config.toml2
-rw-r--r--Cargo.lock311
-rw-r--r--Cargo.toml12
-rw-r--r--LICENSE661
-rw-r--r--examples/example.rs (renamed from src/main.rs)0
-rw-r--r--src/declaration.rs3
-rw-r--r--src/element.rs66
-rw-r--r--src/error.rs54
-rw-r--r--src/lib.rs35
-rw-r--r--src/reader.rs274
-rw-r--r--src/writer.rs558
-rw-r--r--src/writer/endable.rs (renamed from src/endable.rs)0
-rw-r--r--src/writer/loggable.rs (renamed from src/loggable.rs)5
-rw-r--r--src/xml/mod.rs2
-rw-r--r--src/xml/parsers_complete.rs7
15 files changed, 1681 insertions, 309 deletions
diff --git a/.cargo/config.toml b/.cargo/config.toml
new file mode 100644
index 0000000..c91c3f3
--- /dev/null
+++ b/.cargo/config.toml
@@ -0,0 +1,2 @@
+[net]
+git-fetch-with-cli = true
diff --git a/Cargo.lock b/Cargo.lock
index 09a548d..65a6e6f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -50,10 +50,10 @@ dependencies = [
]
[[package]]
-name = "bitflags"
-version = "2.6.0"
+name = "bumpalo"
+version = "3.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
+checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf"
[[package]]
name = "bytes"
@@ -76,15 +76,16 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "circular"
version = "0.3.0"
+source = "git+https://bunny.garden/forks/circular#0a9c9ab1e2f4e3eb912ad9fe91e3ea953e066453"
dependencies = [
"bytes",
]
[[package]]
name = "futures"
-version = "0.3.30"
+version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0"
+checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876"
dependencies = [
"futures-channel",
"futures-core",
@@ -113,9 +114,9 @@ checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-executor"
-version = "0.3.30"
+version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d"
+checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"
dependencies = [
"futures-core",
"futures-task",
@@ -182,26 +183,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
[[package]]
+name = "js-sys"
+version = "0.3.77"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
+dependencies = [
+ "once_cell",
+ "wasm-bindgen",
+]
+
+[[package]]
name = "libc"
version = "0.2.153"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]]
-name = "lock_api"
-version = "0.4.12"
+name = "log"
+version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
-dependencies = [
- "autocfg",
- "scopeguard",
-]
+checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
[[package]]
name = "memchr"
-version = "2.3.4"
+version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525"
+checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "minimal-lexical"
@@ -220,17 +227,6 @@ dependencies = [
]
[[package]]
-name = "mio"
-version = "0.8.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"
-dependencies = [
- "libc",
- "wasi",
- "windows-sys 0.48.0",
-]
-
-[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -258,32 +254,9 @@ checksum = "1a5b3dd1c072ee7963717671d1ca129f1048fda25edea6b752bfc71ac8854170"
[[package]]
name = "once_cell"
-version = "1.20.2"
+version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775"
-
-[[package]]
-name = "parking_lot"
-version = "0.12.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27"
-dependencies = [
- "lock_api",
- "parking_lot_core",
-]
-
-[[package]]
-name = "parking_lot_core"
-version = "0.9.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
-dependencies = [
- "cfg-if",
- "libc",
- "redox_syscall",
- "smallvec",
- "windows-targets 0.52.5",
-]
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "peanuts"
@@ -293,11 +266,14 @@ dependencies = [
"circular",
"futures",
"futures-util",
+ "js-sys",
"nom",
"pin-project",
"thiserror",
"tokio",
"tracing",
+ "wasm-bindgen",
+ "web-sys",
]
[[package]]
@@ -334,51 +310,33 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "proc-macro2"
-version = "1.0.93"
+version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
+checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
-version = "1.0.35"
+version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
+checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
-name = "redox_syscall"
-version = "0.5.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0884ad60e090bf1345b93da0a5de8923c93884cd03f40dfcfddd3b4bee661853"
-dependencies = [
- "bitflags",
-]
-
-[[package]]
name = "rustc-demangle"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
[[package]]
-name = "scopeguard"
-version = "1.2.0"
+name = "rustversion"
+version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
-
-[[package]]
-name = "signal-hook-registry"
-version = "1.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
-dependencies = [
- "libc",
-]
+checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2"
[[package]]
name = "slab"
@@ -390,26 +348,10 @@ dependencies = [
]
[[package]]
-name = "smallvec"
-version = "1.13.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
-
-[[package]]
-name = "socket2"
-version = "0.5.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c"
-dependencies = [
- "libc",
- "windows-sys 0.52.0",
-]
-
-[[package]]
name = "syn"
-version = "2.0.98"
+version = "2.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1"
+checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
dependencies = [
"proc-macro2",
"quote",
@@ -418,18 +360,18 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "2.0.11"
+version = "2.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc"
+checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "2.0.11"
+version = "2.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2"
+checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d"
dependencies = [
"proc-macro2",
"quote",
@@ -444,15 +386,9 @@ checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931"
dependencies = [
"backtrace",
"bytes",
- "libc",
- "mio",
"num_cpus",
- "parking_lot",
"pin-project-lite",
- "signal-hook-registry",
- "socket2",
"tokio-macros",
- "windows-sys 0.48.0",
]
[[package]]
@@ -499,151 +435,74 @@ dependencies = [
[[package]]
name = "unicode-ident"
-version = "1.0.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
-
-[[package]]
-name = "wasi"
-version = "0.11.0+wasi-snapshot-preview1"
+version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
+checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
-name = "windows-sys"
-version = "0.48.0"
+name = "wasm-bindgen"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
+checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
dependencies = [
- "windows-targets 0.48.5",
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
]
[[package]]
-name = "windows-sys"
-version = "0.52.0"
+name = "wasm-bindgen-backend"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
dependencies = [
- "windows-targets 0.52.5",
+ "bumpalo",
+ "log",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
]
[[package]]
-name = "windows-targets"
-version = "0.48.5"
+name = "wasm-bindgen-macro"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
+checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
dependencies = [
- "windows_aarch64_gnullvm 0.48.5",
- "windows_aarch64_msvc 0.48.5",
- "windows_i686_gnu 0.48.5",
- "windows_i686_msvc 0.48.5",
- "windows_x86_64_gnu 0.48.5",
- "windows_x86_64_gnullvm 0.48.5",
- "windows_x86_64_msvc 0.48.5",
+ "quote",
+ "wasm-bindgen-macro-support",
]
[[package]]
-name = "windows-targets"
-version = "0.52.5"
+name = "wasm-bindgen-macro-support"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
+checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
dependencies = [
- "windows_aarch64_gnullvm 0.52.5",
- "windows_aarch64_msvc 0.52.5",
- "windows_i686_gnu 0.52.5",
- "windows_i686_gnullvm",
- "windows_i686_msvc 0.52.5",
- "windows_x86_64_gnu 0.52.5",
- "windows_x86_64_gnullvm 0.52.5",
- "windows_x86_64_msvc 0.52.5",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-backend",
+ "wasm-bindgen-shared",
]
[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.48.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
-
-[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.52.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.48.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.52.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.48.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.52.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
-
-[[package]]
-name = "windows_i686_gnullvm"
-version = "0.52.5"
+name = "wasm-bindgen-shared"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.48.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.52.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.48.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.52.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
-
-[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.48.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
-
-[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.52.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
-
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.48.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
+checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
+dependencies = [
+ "unicode-ident",
+]
[[package]]
-name = "windows_x86_64_msvc"
-version = "0.52.5"
+name = "web-sys"
+version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
+checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
diff --git a/Cargo.toml b/Cargo.toml
index efa03c1..334f0f1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,10 +8,18 @@ edition = "2021"
[dependencies]
pin-project = "1"
async-recursion = "1.1.1"
-circular = { version = "0.3.0", path = "../circular" }
+circular = { version = "0.3.0", git = "https://bunny.garden/forks/circular" }
futures = "0.3.30"
futures-util = { version = "0.3.31", features = ["sink"] }
nom = "7.1.3"
thiserror = "2.0.11"
-tokio = { version = "1.36.0", features = ["io-util", "net", "io-std", "full"] }
+tokio = { version = "1.36.0", features = ["io-util", "sync"] }
tracing = "0.1.41"
+
+[dev-dependencies]
+tokio = { version = "1.36.0", features = ["io-util", "macros", "rt-multi-thread", "io-std"] }
+
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+wasm-bindgen = "0.2"
+js-sys = "0.3"
+web-sys = { version = "0.3", features = ["WebSocket", "MessageEvent", "Blob"] }
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..be3f7b2
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
diff --git a/src/main.rs b/examples/example.rs
index 580652e..580652e 100644
--- a/src/main.rs
+++ b/examples/example.rs
diff --git a/src/declaration.rs b/src/declaration.rs
index 2c0855f..ecd877a 100644
--- a/src/declaration.rs
+++ b/src/declaration.rs
@@ -1,9 +1,11 @@
+/// An XML declaration.
pub struct Declaration {
pub version_info: VersionInfo,
pub encoding_decl: Option<String>,
pub sd_decl: Option<bool>,
}
+/// An XML version.
#[derive(Clone, Copy)]
pub enum VersionInfo {
One,
@@ -11,6 +13,7 @@ pub enum VersionInfo {
}
impl Declaration {
+ /// Create an XML declaration from a version.
pub fn version(version: VersionInfo) -> Self {
Self {
version_info: version,
diff --git a/src/element.rs b/src/element.rs
index 1c1366a..b6b3c15 100644
--- a/src/element.rs
+++ b/src/element.rs
@@ -11,12 +11,15 @@ use crate::{
Result,
};
+/// Result type for the `FromElement` trait.
pub type DeserializeResult<T> = std::result::Result<T, DeserializeError>;
+/// Trait for conversion from an `Element` into another type, for deserialisation from a `Reader`.
pub trait FromElement: Sized {
fn from_element(element: Element) -> DeserializeResult<Self>;
}
+/// Trait for conversion from a type into an `Element`, for serialisation into a `Writer`.
pub trait IntoElement {
fn builder(&self) -> ElementBuilder;
@@ -45,18 +48,24 @@ pub struct Name {
pub local_name: String,
}
+/// `Content` represents anything that can be the content of an XML element.
#[derive(Debug, Clone)]
pub enum Content {
+ /// A child element.
Element(Element),
+ /// A text value.
Text(String),
+ /// A processing instruction.
PI,
+ /// A comment.
Comment(String),
}
// should this be a trait?
+/// `Element` represents an XML element that can be written to a `Writer` or read from a `Reader`.
#[derive(Debug, Clone)]
pub struct Element {
- pub name: Name,
+ pub(crate) name: Name,
// namespace: Name,
// each element once created contains the qualified namespace information for that element
// the name contains the qualified namespace so this is unnecessary
@@ -64,15 +73,15 @@ pub struct Element {
// hashmap of explicit namespace declarations on the element itself only
// possibly not needed as can be calculated at write time depending on context and qualified namespace, and for reading, element validity and namespaces are kept track of by the reader.
// change this to custom namespace declarations only, so you can override the definition of namespaces if you wish
- pub namespace_declaration_overrides: HashSet<NamespaceDeclaration>,
+ pub(crate) namespace_declaration_overrides: HashSet<NamespaceDeclaration>,
// attributes can be in a different namespace than the element. how to make sure they are valid?
// maybe include the namespace instead of or with the prefix
// you can calculate the prefix from the namespaced name and the current writer context
// you can validate the prefix and calculate the namespace from the current reader context
// this results in readers and writers being able to return qualification errors as they aren't able to create elements until every part is qualified.
- pub attributes: HashMap<Name, String>,
+ pub(crate) attributes: HashMap<Name, String>,
// TODO: make a hashmap maybe? to be able to address parts of the content individually
- pub content: VecDeque<Content>,
+ pub(crate) content: VecDeque<Content>,
}
impl FromElement for Element {
@@ -82,10 +91,12 @@ impl FromElement for Element {
}
impl Element {
+ /// Return the namespace the xml element is qualified by, and the localname, for matching on the element when you don't know which kind of element to expect.
pub fn identify(&self) -> (Option<&str>, &str) {
(self.name.namespace.as_deref(), &self.name.local_name)
}
+ /// Check the localname of the element.
pub fn check_name(&self, name: &str) -> DeserializeResult<()> {
if self.name.local_name == name {
Ok(())
@@ -97,6 +108,7 @@ impl Element {
}
}
+ /// Check the element is qualified by a namespace.
pub fn check_namespace(&self, namespace: &str) -> DeserializeResult<()> {
if self.name.namespace.as_deref() == Some(namespace) {
return Ok(());
@@ -114,6 +126,7 @@ impl Element {
}
}
+ /// Optionally extract an attribute from the element.
pub fn attribute_opt<V: FromStr>(&mut self, att_name: &str) -> DeserializeResult<Option<V>> {
if let Some(att_value) = self.attributes.remove(&Name {
namespace: None,
@@ -127,6 +140,7 @@ impl Element {
}
}
+ /// Optionally extract a namespaced attribute from the elmeent.
pub fn attribute_opt_namespaced<V: FromStr>(
&mut self,
att_name: &str,
@@ -144,6 +158,7 @@ impl Element {
}
}
+ /// Extract an attribute from the element.
pub fn attribute<V: FromStr>(&mut self, att_name: &str) -> DeserializeResult<V> {
let name = Name {
namespace: None,
@@ -158,6 +173,7 @@ impl Element {
}
}
+ /// Extract a namespaced attribute from the element.
pub fn attribute_namespaced<V: FromStr>(
&mut self,
att_name: &str,
@@ -176,6 +192,7 @@ impl Element {
}
}
+ /// Ensure there are no more attributes on the element.
pub fn no_more_attributes(self) -> DeserializeResult<Self> {
if self.attributes.is_empty() {
Ok(self)
@@ -186,6 +203,8 @@ impl Element {
// for xs:any
+ /// Extract a child of type `T` from the element.
+ /// E.g. when there is an xs:any.
pub fn child_one<T: FromElement>(&mut self) -> DeserializeResult<T> {
if let Some(position) = self.content.iter().position(|content| match content {
Content::Element(element) => <T as FromElement>::from_element(element.clone()).is_ok(),
@@ -204,6 +223,8 @@ impl Element {
}
}
+ /// Optionally extract a child of type `T` from the element.
+ /// E.g. when there is an xs:any.
pub fn child_opt<T: FromElement>(&mut self) -> DeserializeResult<Option<T>> {
if let Some(position) = self.content.iter().position(|content| match content {
Content::Element(element) => <T as FromElement>::from_element(element.clone()).is_ok(),
@@ -222,6 +243,7 @@ impl Element {
}
}
+ /// Extract several children of type `T` from the element.
pub fn children<T: FromElement>(&mut self) -> DeserializeResult<Vec<T>> {
let (children, rest): (VecDeque<_>, VecDeque<_>) = self
.content
@@ -252,6 +274,7 @@ impl Element {
Ok(children)
}
+ /// Extract a text value from the element.
pub fn value<V: FromStr>(&mut self) -> DeserializeResult<V> {
if let Some(position) = self.content.iter().position(|content| match content {
Content::Element(_) => false,
@@ -270,6 +293,7 @@ impl Element {
}
}
+ /// Optionally extract a text value from the element.
pub fn value_opt<V: FromStr>(&mut self) -> DeserializeResult<Option<V>> {
if let Some(position) = self.content.iter().position(|content| match content {
Content::Element(_) => false,
@@ -290,6 +314,8 @@ impl Element {
// for xs:sequence
+ /// Pop a child element of type `T` from the element.
+ /// E.g. when there is an xs:sequence.
pub fn pop_child_one<T: FromElement>(&mut self) -> DeserializeResult<T> {
loop {
let child = self
@@ -307,6 +333,8 @@ impl Element {
}
}
+ /// Optionally pop a child element of type `T` from the element.
+ /// E.g. when there is an xs:sequence.
pub fn pop_child_opt<T: FromElement>(&mut self) -> DeserializeResult<Option<T>> {
loop {
let child = self.content.pop_front();
@@ -327,6 +355,8 @@ impl Element {
}
}
+ /// Pop several children of type `T` from the element.
+ /// E.g. when there is an xs:sequence.
pub fn pop_children<T: FromElement>(&mut self) -> DeserializeResult<Vec<T>> {
let mut children = Vec::new();
loop {
@@ -360,6 +390,8 @@ impl Element {
}
}
+ /// Pop a text value from the element.
+ /// E.g. when there is an xs:sequence.
pub fn pop_value<V: FromStr>(&mut self) -> DeserializeResult<V> {
loop {
let child = self
@@ -381,6 +413,8 @@ impl Element {
}
}
+ /// Optionally pop a text value from the element.
+ /// E.g. when there is an xs:sequence.
pub fn pop_value_opt<V: FromStr>(&mut self) -> DeserializeResult<Option<V>> {
loop {
let child = self.content.pop_front();
@@ -404,6 +438,7 @@ impl Element {
}
}
+ /// Ensure there is no more element content left.
pub fn no_more_content(self) -> DeserializeResult<Self> {
if self
.content
@@ -423,11 +458,13 @@ impl Element {
}
}
+ /// Create a new `ElementBuilder`.
pub fn builder(name: impl ToString, namespace: Option<impl ToString>) -> ElementBuilder {
ElementBuilder::new(name, namespace)
}
}
+/// Builder for the `Element` type.
pub struct ElementBuilder {
name: Name,
namespace_declaration_overrides: Vec<NamespaceDeclaration>,
@@ -436,6 +473,7 @@ pub struct ElementBuilder {
}
impl ElementBuilder {
+ /// Create a new `ElementBuilder`.
pub fn new(name: impl ToString, namespace: Option<impl ToString>) -> Self {
Self {
name: Name {
@@ -448,6 +486,7 @@ impl ElementBuilder {
}
}
+ /// Push a namespace declaration override onto the element builder.
pub fn push_namespace_declaration_override(
mut self,
prefix: Option<impl ToString>,
@@ -461,6 +500,7 @@ impl ElementBuilder {
self
}
+ /// Push an attribute onto the element builder.
pub fn push_attribute<N: ToString, V: ToString>(mut self, name: N, value: V) -> Self {
self.attributes.push((
// TODO: make sure name is a valid name, same for prefixes
@@ -473,6 +513,7 @@ impl ElementBuilder {
self
}
+ /// Push a namespaced attribute onto the element builder.
pub fn push_attribute_namespaced(
mut self,
namespace: impl ToString,
@@ -490,17 +531,20 @@ impl ElementBuilder {
}
// TODO: use references for everything to avoid cloning
+ /// Push a child element onto the element builder.
pub fn push_child(mut self, child: impl IntoElement) -> Self {
self.content.push(ContentBuilder::Element(child.builder()));
self
}
// TODO: better way for push_text to work, empty string should be empty element no matter what
+ /// Push a text value onto the element builder.
pub fn push_text(mut self, text: impl ToString) -> Self {
self.content.push(ContentBuilder::Text(text.to_string()));
self
}
+ /// Optionally push an attribute onto the element builder.
pub fn push_attribute_opt(self, name: impl ToString, value: Option<impl ToString>) -> Self {
if let Some(value) = value {
self.push_attribute(name, value)
@@ -509,6 +553,7 @@ impl ElementBuilder {
}
}
+ /// Optionally push a namespaced attribute onto the element builder.
pub fn push_attribute_opt_namespaced(
self,
namespace: impl ToString,
@@ -522,6 +567,7 @@ impl ElementBuilder {
}
}
+ /// Optionally push a child onto the element builder.
pub fn push_child_opt(self, child: Option<impl IntoElement>) -> Self {
if let Some(child) = child {
self.push_child(child)
@@ -530,6 +576,7 @@ impl ElementBuilder {
}
}
+ /// Optionally push a text value onto the element builder.
pub fn push_text_opt(self, text: Option<impl ToString>) -> Self {
if let Some(text) = text {
self.push_text(text)
@@ -538,11 +585,13 @@ impl ElementBuilder {
}
}
+ /// Optionally push a content item onto the element builder.
pub fn push_content(mut self, content: ContentBuilder) -> Self {
self.content.push(content);
self
}
+ /// Optionally push content items onto the element builder.
pub fn push_children(self, children: Vec<impl IntoContent>) -> Self {
let mut element_builder = self;
for child in children {
@@ -551,6 +600,7 @@ impl ElementBuilder {
element_builder
}
+ /// Build an `Element` from the `ElementBuilder`.
pub fn build(&self) -> Result<Element> {
let mut namespace_declaration_overrides = HashSet::new();
for namespace_declaration in &self.namespace_declaration_overrides {
@@ -588,6 +638,7 @@ impl ElementBuilder {
}
}
+/// Trait for conversion from a type into an (`Element`) `Content` item.
pub trait IntoContent {
fn into_content(&self) -> Content {
self.builder().build().unwrap()
@@ -605,17 +656,23 @@ where
}
}
+/// Trait for conversion from some `Element` `Content` into another type.
pub trait FromContent: Sized {
fn from_content(content: Content) -> DeserializeResult<Self>;
}
+/// Builder for `Content`.
pub enum ContentBuilder {
+ /// A child element.
Element(ElementBuilder),
+ /// A text value.
Text(String),
+ /// A comment.
Comment(String),
}
impl ContentBuilder {
+ /// Build a `Content` item from the builder.
pub fn build(&self) -> Result<Content> {
match self {
ContentBuilder::Element(element_builder) => {
@@ -627,6 +684,7 @@ impl ContentBuilder {
}
}
+/// Escape a str into an XML escaped string.
pub fn escape_str(s: &str) -> String {
let mut string = String::new();
for str in s.split_inclusive(|c| c == '<' || c == '&' || c == '>') {
diff --git a/src/error.rs b/src/error.rs
index ae4aa26..26b7766 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -1,57 +1,75 @@
use std::{
collections::{HashMap, VecDeque},
- fmt,
num::ParseIntError,
str::Utf8Error,
sync::Arc,
};
use thiserror::Error;
+#[cfg(target_arch = "wasm32")]
+use wasm_bindgen::JsValue;
use crate::{
element::{Content, Name, NamespaceDeclaration},
Element,
};
+/// Error type for the `FromElement` trait. Used when deserialising from an `Element`.
#[derive(Error, Debug, Clone)]
pub enum DeserializeError {
+ /// Could not parse string.
#[error("could not parse string {0:?} to requested value")]
FromStr(String),
+ /// Unexpected attributes.
#[error("unexpected attributes {0:?}")]
UnexpectedAttributes(HashMap<Name, String>),
+ /// Unexpected element content.
#[error("unexpected element content: {0:?}")]
UnexpectedContent(VecDeque<Content>),
+ /// Missing attribute.
#[error("attribute `{0:?}` missing")]
MissingAttribute(Name),
+ /// Incorrect localname encountered.
#[error("incorrect localname: expected `{expected:?}`, found `{found:?}`")]
IncorrectName { expected: String, found: String },
+ /// Incorrect namespace encountered.
#[error("incorrect namespace: expected `{expected:?}`, found `{found:?}`")]
IncorrectNamespace { expected: String, found: String },
+ /// Unqualified namespace when expecting qualified namespace.
#[error("unqualified namespace: expected `{expected:?}`")]
Unqualified { expected: String },
+ /// Element missing expected child.
#[error("element missing expected child")]
MissingChild,
+ /// Element missing expected text value.
#[error("element missing expected text value")]
MissingValue,
// not used by crate (yet), but may be used by consumers implementing FromElement
+ /// Unexpected element.
#[error("unexpected element: {0:?}")]
UnexpectedElement(Element),
+ /// Attribute is an empty string.
#[error("attribute `{0}` is an empty string")]
AttributeEmptyString(String),
+ /// Empty string.
#[error("empty string")]
EmptyString,
}
+/// General error type for functions in the crate.
// TODO: add error context (usually the stanza)
#[derive(Error, Debug, Clone)]
pub enum Error {
+ #[cfg(target_arch = "wasm32")]
+ #[error("websocket closed")]
+ WebSocketClosed,
#[error("io: {0}")]
// TODO: is this okay?
ReadError(Arc<std::io::Error>),
#[error("utf8 conversion: {0}")]
Utf8Error(#[from] Utf8Error),
#[error("nom parsing: {0}")]
- ParseError(String),
+ ParseError(String, String),
#[error("unknown xml entity reference `&{0};`")]
EntityProcessError(String),
#[error("invalid character reference: {0}")]
@@ -72,6 +90,34 @@ pub enum Error {
Deserialize(#[from] DeserializeError),
#[error("root element has already been fully processed")]
RootElementEnded,
+ #[cfg(target_arch = "wasm32")]
+ #[error("websocket error: {0}")]
+ Websocket(#[from] WebsocketError),
+}
+
+/// Websocket-related errors.
+#[cfg(target_arch = "wasm32")]
+#[derive(Error, Debug, Clone)]
+pub enum WebsocketError {
+ /// Websocket write error.
+ #[error("write")]
+ Write,
+ /// Invalid encoding.
+ #[error("invalid encoding")]
+ InvalidEncoding,
+ /// Can't decode blob.
+ #[error("can't decode blob")]
+ CantDecodeBlob,
+ /// Unknown data type.
+ #[error("unknown data type")]
+ UnknownDataType,
+}
+
+#[cfg(target_arch = "wasm32")]
+impl From<JsValue> for Error {
+ fn from(_e: JsValue) -> Self {
+ Self::Websocket(WebsocketError::Write)
+ }
}
impl From<std::io::Error> for Error {
@@ -80,12 +126,16 @@ impl From<std::io::Error> for Error {
}
}
+/// Character reference decode error.
#[derive(Error, Debug, Clone)]
pub enum CharRefError {
+ /// Int parsing.
#[error("int parsing: {0}")]
ParseInt(#[from] ParseIntError),
+ /// Integer is not a valid char.
#[error("u32 `{0}` does not represent a valid char")]
IntegerNotAChar(u32),
+ /// Character is an invalid XML char.
#[error("`{0}` is not a valid xml char")]
InvalidXMLChar(char),
}
diff --git a/src/lib.rs b/src/lib.rs
index 3b4a592..424af31 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,19 +1,44 @@
+//! # peanuts: An ergonomic (async) xml reader/writer library.
+//!
+//! Features:
+//!
+//! - Serialisation
+//! - Deserialisation
+//! - DOM navigation
+//! - Namespacing
+//! - Websocket framing
+
+/// XML prolog declaration types.
pub mod declaration;
-pub mod element;
-mod endable;
+mod element;
mod error;
-mod loggable;
-pub mod reader;
+mod reader;
mod writer;
-pub mod xml;
+// TODO: alternative raw xml API
+mod xml;
+/// Result type for the crate.
pub type Result<T> = std::result::Result<T, error::Error>;
+/// XML namespace URI for the `xml:` namespace prefix.
pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
+/// XML namespace URI for the `xmlns:` namespace prefix.
pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
+pub use element::Content;
+pub use element::ContentBuilder;
+pub use element::DeserializeResult;
pub use element::Element;
+pub use element::ElementBuilder;
+pub use element::FromContent;
+pub use element::FromElement;
+pub use element::IntoContent;
+pub use element::IntoElement;
pub use error::DeserializeError;
pub use error::Error;
+pub use reader::ReadableString;
pub use reader::Reader;
+#[cfg(target_arch = "wasm32")]
+pub use reader::WebSocketOnMessageRead;
+pub use writer::Loggable;
pub use writer::Writer;
diff --git a/src/reader.rs b/src/reader.rs
index 9eb7c91..a403171 100644
--- a/src/reader.rs
+++ b/src/reader.rs
@@ -1,12 +1,24 @@
+use std::io::Write;
+
use circular::Buffer;
+#[cfg(target_arch = "wasm32")]
+use js_sys::{ArrayBuffer, Uint8Array};
use nom::Err;
use std::{
collections::{HashMap, HashSet, VecDeque},
str,
};
-use tokio::io::{AsyncRead, AsyncReadExt};
-use tracing::{debug, info, trace};
-
+use tokio::io::AsyncRead;
+#[cfg(target_arch = "wasm32")]
+use tokio::sync::mpsc;
+use tracing::{info, trace};
+#[cfg(target_arch = "wasm32")]
+use wasm_bindgen::{closure::Closure, JsCast};
+#[cfg(target_arch = "wasm32")]
+use web_sys::{Blob, MessageEvent};
+
+#[cfg(target_arch = "wasm32")]
+use crate::error::WebsocketError;
use crate::{
declaration::{Declaration, VersionInfo},
element::{Content, Element, FromElement, Name, NamespaceDeclaration},
@@ -17,19 +29,144 @@ use crate::{
static MAX_STANZA_SIZE: usize = 65536;
-/// streaming reader that tracks depth and available namespaces at current depth
+/// Reader that tracks depth and corresponding declared/available namespaces.
#[derive(Debug)]
pub struct Reader<R> {
inner: R,
- pub buffer: Buffer,
+ buffer: Buffer,
// holds which tags we are in atm over depth
// to have names reference namespaces could
depth: Vec<Name>,
namespace_declarations: Vec<HashSet<NamespaceDeclaration>>,
+ unendable: bool,
root_ended: bool,
}
+/// Represents a WebSocket Message, after converting from JavaScript type.
+/// from https://github.com/najamelan/ws_stream_wasm/blob/dev/src/ws_message.rs
+#[cfg(target_arch = "wasm32")]
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum WsMessage {
+ /// The data of the message is a string.
+ ///
+ Text(String),
+
+ /// The message contains binary data.
+ ///
+ Binary(Vec<u8>),
+}
+
+/// This will convert the JavaScript event into a WsMessage. Note that this
+/// will only work if the connection is set to use the binary type ArrayBuffer.
+/// On binary type Blob, this will panic.
+/// from https://github.com/najamelan/ws_stream_wasm/blob/dev/src/ws_message.rs
+#[cfg(target_arch = "wasm32")]
+impl TryFrom<MessageEvent> for WsMessage {
+ type Error = WebsocketError;
+
+ fn try_from(evt: MessageEvent) -> std::result::Result<Self, Self::Error> {
+ match evt.data() {
+ d if d.is_instance_of::<ArrayBuffer>() => {
+ let buffy = Uint8Array::new(d.unchecked_ref());
+ let mut v = vec![0; buffy.length() as usize];
+
+ buffy.copy_to(&mut v); // FIXME: get rid of this copy
+
+ Ok(WsMessage::Binary(v))
+ }
+
+ // We don't allow invalid encodings. In principle if needed,
+ // we could add a variant to WsMessage with a CString or an OsString
+ // to allow the user to access this data. However until there is a usecase,
+ // I'm not inclined, amongst other things because the conversion from Js isn't very
+ // clear and it would require a bunch of testing for something that's a rather bad
+ // idea to begin with. If you need data that is not a valid string, use a binary
+ // message.
+ //
+ d if d.is_string() => match d.as_string() {
+ Some(text) => Ok(WsMessage::Text(text)),
+ None => Err(WebsocketError::InvalidEncoding),
+ },
+
+ // We have set the binary mode to array buffer (WsMeta::connect), so normally this shouldn't happen.
+ // That is as long as this is used within the context of the WsMeta constructor.
+ //
+ d if d.is_instance_of::<Blob>() => Err(WebsocketError::CantDecodeBlob),
+
+ // should never happen.
+ //
+ _ => Err(WebsocketError::UnknownDataType),
+ }
+ }
+}
+
+#[cfg(target_arch = "wasm32")]
+#[derive(Debug)]
+/// Receiver for websocket frames. Implements `Readable` for asynchronous XML reading.
+pub struct WebSocketOnMessageRead {
+ queue: mpsc::UnboundedReceiver<WsMessage>,
+}
+
+#[cfg(target_arch = "wasm32")]
+impl WebSocketOnMessageRead {
+ /// Create a new `WebsocketOnMessageRead` with corresponding `on_message` event closure.
+ pub fn new() -> (Closure<dyn FnMut(MessageEvent)>, Self) {
+ let (send, recv) = mpsc::unbounded_channel();
+ let on_msg = Closure::wrap(Box::new(move |msg_evt: MessageEvent| {
+ let msg_evt = msg_evt.try_into();
+ match msg_evt {
+ Ok(msg_evt) => match send.send(msg_evt) {
+ Ok(()) => {}
+ Err(e) => {
+ tracing::error!("message event send error: {:?}", e);
+ }
+ },
+ Err(e) => {
+ tracing::error!("websocket receive error: {}", e);
+ }
+ }
+ }) as Box<dyn FnMut(MessageEvent)>);
+
+ (on_msg, Self { queue: recv })
+ }
+}
+
+#[cfg(target_arch = "wasm32")]
+impl Readable for WebSocketOnMessageRead {
+ async fn read_buf(&mut self, buffer: &mut Buffer) -> Result<usize> {
+ let msg = self.queue.recv().await;
+ let msg = match msg {
+ Some(msg) => msg,
+ None => return Err(Error::WebSocketClosed),
+ };
+ match msg {
+ WsMessage::Text(s) => {
+ let text = s.as_bytes();
+ Ok(buffer.write(text)?)
+ }
+ WsMessage::Binary(v) => Ok(buffer.write(&v)?),
+ }
+ }
+}
+
+/// Trait for abstracting asynchronous read streams.
+pub trait Readable {
+ fn read_buf(&mut self, buffer: &mut Buffer)
+ -> impl std::future::Future<Output = Result<usize>>;
+}
+
+/// String wrapper which implements Readable, for string parsing.
+pub struct ReadableString(pub String);
+
+impl Readable for ReadableString {
+ async fn read_buf(&mut self, buffer: &mut Buffer) -> Result<usize> {
+ let string = self.0.split_off(0);
+ Ok(buffer.write(string.as_bytes())?)
+ }
+}
+
impl<R> Reader<R> {
+ /// Create a new `Reader` which is constrained to a single root element.
pub fn new(reader: R) -> Self {
let mut default_declarations = HashSet::new();
default_declarations.insert(NamespaceDeclaration {
@@ -46,25 +183,52 @@ impl<R> Reader<R> {
depth: Vec::new(),
// TODO: make sure reserved namespaces are never overwritten
namespace_declarations: vec![default_declarations],
+ unendable: false,
+ root_ended: false,
+ }
+ }
+
+ /// Create a new `Reader` which is not constrained to a single root element.
+ pub fn new_unendable(reader: R) -> Self {
+ let mut default_declarations = HashSet::new();
+ default_declarations.insert(NamespaceDeclaration {
+ prefix: Some("xml".to_string()),
+ namespace: XML_NS.to_string(),
+ });
+ default_declarations.insert(NamespaceDeclaration {
+ prefix: Some("xmlns".to_string()),
+ namespace: XMLNS_NS.to_string(),
+ });
+ Self {
+ inner: reader,
+ buffer: Buffer::with_capacity(MAX_STANZA_SIZE),
+ depth: Vec::new(),
+ // TODO: make sure reserved namespaces are never overwritten
+ namespace_declarations: vec![default_declarations],
+ unendable: true,
root_ended: false,
}
}
+ /// Extract the inner type from the `Reader`.
pub fn into_inner(self) -> R {
self.inner
}
}
-impl<R> Reader<R>
+impl<R> Readable for R
where
R: AsyncRead + Unpin,
{
- pub async fn read_buf<'s>(&mut self) -> Result<usize> {
- Ok(self.inner.read_buf(&mut self.buffer).await?)
+ async fn read_buf(&mut self, buffer: &mut Buffer) -> Result<usize> {
+ Ok(tokio::io::AsyncReadExt::read_buf(self, buffer).await?)
}
+}
+impl<R: Readable> Reader<R> {
+ /// Attempt to read an XML prolog, which could include an XML declaration, miscellaneous items (e.g. comments, processing instructions), and/or a doctype declaration.
pub async fn read_prolog<'s>(&'s mut self) -> Result<Option<Declaration>> {
- if self.root_ended {
+ if !self.unendable && self.root_ended {
return Err(Error::RootElementEnded);
}
loop {
@@ -104,30 +268,37 @@ where
}
std::result::Result::Err(e) => match e {
Err::Incomplete(_) => {
- self.read_buf().await?;
+ self.inner.read_buf(&mut self.buffer).await?;
}
// TODO: better error
- Err::Error(e) => return Err(Error::ParseError(e.to_string())),
- Err::Failure(e) => return Err(Error::ParseError(e.to_string())),
+ Err::Error(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
+ Err::Failure(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
},
}
}
}
+ /// Read a start tag, moving up in document depth, and convert it into a type which implements `FromElement`.
pub async fn read_start<'s, T: FromElement>(&'s mut self) -> Result<T> {
let element = self.read_start_tag().await?;
trace!("read element start: {:?}", element);
Ok(FromElement::from_element(element)?)
}
+ /// Read a full element (start tag + content + end tag, or empty tag) and convert it into a type which implements `FromElement`.
pub async fn read<'s, T: FromElement>(&'s mut self) -> Result<T> {
let element = self.read_element().await?;
trace!("read element: {:?}", element);
Ok(FromElement::from_element(element)?)
}
+ /// Read a start tag, moving up in document depth.
pub async fn read_start_tag<'s>(&'s mut self) -> Result<Element> {
- if self.root_ended {
+ if !self.unendable && self.root_ended {
return Err(Error::RootElementEnded);
}
loop {
@@ -147,18 +318,23 @@ where
}
std::result::Result::Err(e) => match e {
Err::Incomplete(_) => {
- self.read_buf().await?;
+ self.inner.read_buf(&mut self.buffer).await?;
}
// TODO: better error
- Err::Error(e) => return Err(Error::ParseError(e.to_string())),
- Err::Failure(e) => return Err(Error::ParseError(e.to_string())),
+ Err::Error(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
+ Err::Failure(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
},
}
}
}
+ /// Read an end tag, moving down in document depth.
pub async fn read_end_tag<'s>(&'s mut self) -> Result<()> {
- if self.root_ended {
+ if !self.unendable && self.root_ended {
return Err(Error::RootElementEnded);
}
loop {
@@ -181,18 +357,23 @@ where
}
std::result::Result::Err(e) => match e {
Err::Incomplete(_) => {
- self.read_buf().await?;
+ self.inner.read_buf(&mut self.buffer).await?;
}
// TODO: better error
- Err::Error(e) => return Err(Error::ParseError(e.to_string())),
- Err::Failure(e) => return Err(Error::ParseError(e.to_string())),
+ Err::Error(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
+ Err::Failure(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
},
}
}
}
+ /// Read a full element (start tag + content + end tag, or empty tag).
pub async fn read_element<'s>(&'s mut self) -> Result<Element> {
- if self.root_ended {
+ if !self.unendable && self.root_ended {
return Err(Error::RootElementEnded);
}
loop {
@@ -212,18 +393,23 @@ where
}
std::result::Result::Err(e) => match e {
Err::Incomplete(_) => {
- self.read_buf().await?;
+ self.inner.read_buf(&mut self.buffer).await?;
}
// TODO: better error
- Err::Error(e) => return Err(Error::ParseError(e.to_string())),
- Err::Failure(e) => return Err(Error::ParseError(e.to_string())),
+ Err::Error(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
+ Err::Failure(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
},
}
}
}
+ /// Read element content (text, another full element, a comment, a PI).
pub async fn read_content<'s>(&'s mut self) -> Result<Content> {
- if self.root_ended {
+ if !self.unendable && self.root_ended {
return Err(Error::RootElementEnded);
}
let mut last_char = false;
@@ -240,7 +426,7 @@ where
}
std::result::Result::Err(e) => match e {
Err::Incomplete(_) => {
- self.read_buf().await?;
+ self.inner.read_buf(&mut self.buffer).await?;
}
_ => match xml::ContentItem::parse(input) {
Ok((rest, content_item)) => match content_item {
@@ -289,7 +475,7 @@ where
} else {
let len =
self.buffer.available_data() - rest.as_bytes().len();
- let comment = comment.to_string();
+ let comment = comment.0.to_string();
self.buffer.consume(len);
return Ok(Content::Comment(comment));
}
@@ -297,11 +483,15 @@ where
},
std::result::Result::Err(e) => match e {
Err::Incomplete(_) => {
- self.read_buf().await?;
+ self.inner.read_buf(&mut self.buffer).await?;
}
// TODO: better error
- Err::Error(e) => return Err(Error::ParseError(e.to_string())),
- Err::Failure(e) => return Err(Error::ParseError(e.to_string())),
+ Err::Error(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
+ Err::Failure(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
},
},
},
@@ -351,18 +541,22 @@ where
}
xml::ContentItem::Comment(comment) => {
let len = self.buffer.available_data() - rest.as_bytes().len();
- let comment = comment.to_string();
+ let comment = comment.0.to_string();
self.buffer.consume(len);
return Ok(Content::Comment(comment));
}
},
std::result::Result::Err(e) => match e {
Err::Incomplete(_) => {
- self.read_buf().await?;
+ self.inner.read_buf(&mut self.buffer).await?;
}
// TODO: better error
- Err::Error(e) => return Err(Error::ParseError(e.to_string())),
- Err::Failure(e) => return Err(Error::ParseError(e.to_string())),
+ Err::Error(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
+ Err::Failure(e) => {
+ return Err(Error::ParseError(input.to_string(), e.to_string()))
+ }
},
}
}
@@ -371,6 +565,7 @@ where
}
impl<R> Reader<R> {
+ /// Convert a start tag into an `Element` given a mutable document context.
fn start_tag_from_xml(
depth: &mut Vec<Name>,
namespace_declarations: &mut Vec<HashSet<NamespaceDeclaration>>,
@@ -388,7 +583,7 @@ impl<R> Reader<R> {
}) {
let prefix = match prefix {
xml::NSAttName::PrefixedAttName(prefixed_att_name) => {
- Some(prefixed_att_name.to_string())
+ Some(prefixed_att_name.0.to_string())
}
xml::NSAttName::DefaultAttName => None,
};
@@ -408,6 +603,10 @@ impl<R> Reader<R> {
.chain(element_namespace_declarations.iter())
.collect();
+ trace!(
+ "namespace declaration stack: {:?}",
+ namespace_declarations_stack
+ );
// element name
let element_namespace_declaration;
@@ -488,6 +687,7 @@ impl<R> Reader<R> {
});
}
+ /// Ensure an end tag is acceptable given a document context.
fn end_tag_from_xml(
depth: &mut Vec<Name>,
namespace_declarations: &mut Vec<HashSet<NamespaceDeclaration>>,
@@ -535,6 +735,7 @@ impl<R> Reader<R> {
}
}
+ /// Convert an xml element (empty or not) into an `Element` given a mutable document context.
fn element_from_xml(
namespace_declarations: &mut Vec<HashSet<NamespaceDeclaration>>,
element: xml::Element,
@@ -571,7 +772,7 @@ impl<R> Reader<R> {
}) {
let prefix = match prefix {
xml::NSAttName::PrefixedAttName(prefixed_att_name) => {
- Some(prefixed_att_name.to_string())
+ Some(prefixed_att_name.0.to_string())
}
xml::NSAttName::DefaultAttName => None,
};
@@ -709,6 +910,7 @@ impl<R> Reader<R> {
});
}
+ /// Convert xml content into a `VecDeque` of `Content` given a document context.
fn content_from_xml(
namespaces: &mut Vec<HashSet<NamespaceDeclaration>>,
xml_content: xml::Content,
diff --git a/src/writer.rs b/src/writer.rs
index 7ed1775..1818fca 100644
--- a/src/writer.rs
+++ b/src/writer.rs
@@ -3,26 +3,33 @@ use std::collections::HashSet;
use async_recursion::async_recursion;
use tokio::io::{AsyncWrite, AsyncWriteExt};
use tracing::info;
+#[cfg(target_arch = "wasm32")]
+use web_sys::WebSocket;
use crate::{
declaration::{Declaration, VersionInfo},
element::{escape_str, Content, Element, IntoContent, IntoElement, Name, NamespaceDeclaration},
- endable::Endable,
error::Error,
- loggable::Loggable,
xml::{self, composers::Composer, parsers_complete::Parser},
Result, XMLNS_NS, XML_NS,
};
+use endable::Endable;
+pub use loggable::Loggable;
-// pub struct Writer<W, C = Composer> {
+mod endable;
+mod loggable;
+
+/// Writer that tracks depth and corresponding declared/available namespaces.
#[derive(Debug)]
pub struct Writer<W> {
- inner: Endable<Loggable<W>>,
+ inner: Endable<W>,
+ unendable: bool,
depth: Vec<Name>,
namespace_declarations: Vec<HashSet<NamespaceDeclaration>>,
}
-impl<W> Writer<W> {
+impl<W> Writer<Loggable<W>> {
+ /// Create a new `Writer` which is constrained to a single root element.
pub fn new(writer: W) -> Self {
let mut default_declarations = HashSet::new();
default_declarations.insert(NamespaceDeclaration {
@@ -35,19 +42,477 @@ impl<W> Writer<W> {
});
Self {
inner: Endable::new(Loggable::new(writer)),
+ unendable: false,
depth: Vec::new(),
namespace_declarations: vec![default_declarations],
}
}
+ /// Create a new `Writer` which is not constrained to a single root element.
+ pub fn new_unendable(writer: W) -> Self {
+ let mut default_declarations = HashSet::new();
+ default_declarations.insert(NamespaceDeclaration {
+ prefix: Some("xml".to_string()),
+ namespace: XML_NS.to_string(),
+ });
+ default_declarations.insert(NamespaceDeclaration {
+ prefix: Some("xmlns".to_string()),
+ namespace: XMLNS_NS.to_string(),
+ });
+ Self {
+ inner: Endable::new(Loggable::new(writer)),
+ unendable: true,
+ depth: Vec::new(),
+ namespace_declarations: vec![default_declarations],
+ }
+ }
+
+ /// Extract the inner type from the `Writer`.
pub fn into_inner(self) -> W {
self.inner.into_inner().into_inner()
}
}
-impl<W: AsyncWrite + Unpin + Send> Writer<W> {
+#[cfg(target_arch = "wasm32")]
+impl Writer<WebSocket> {
+ /// Create a new `Writer` which is constrained to a single root element.
+ pub fn new(websocket: WebSocket) -> Self {
+ let mut default_declarations = HashSet::new();
+ default_declarations.insert(NamespaceDeclaration {
+ prefix: Some("xml".to_string()),
+ namespace: XML_NS.to_string(),
+ });
+ default_declarations.insert(NamespaceDeclaration {
+ prefix: Some("xmlns".to_string()),
+ namespace: XMLNS_NS.to_string(),
+ });
+ Self {
+ inner: Endable::new(websocket),
+ unendable: false,
+ depth: Vec::new(),
+ namespace_declarations: vec![default_declarations],
+ }
+ }
+
+ /// Extract the inner `WebSocket` from the `Writer`.
+ pub fn into_inner(self) -> WebSocket {
+ self.inner.into_inner()
+ }
+
+ /// Create a new `Writer` which is not constrained to a single root element.
+ pub fn new_unendable(websocket: WebSocket) -> Self {
+ let mut default_declarations = HashSet::new();
+ default_declarations.insert(NamespaceDeclaration {
+ prefix: Some("xml".to_string()),
+ namespace: XML_NS.to_string(),
+ });
+ default_declarations.insert(NamespaceDeclaration {
+ prefix: Some("xmlns".to_string()),
+ namespace: XMLNS_NS.to_string(),
+ });
+ Self {
+ inner: Endable::new(websocket),
+ unendable: true,
+ depth: Vec::new(),
+ namespace_declarations: vec![default_declarations],
+ }
+ }
+
+ /// Write an XML declaration with the provided `VersionInfo`.
pub async fn write_declaration(&mut self, version: VersionInfo) -> Result<()> {
- let writer = self.inner.try_as_mut()?;
+ let declaration = Declaration::version(version);
+ let version_info;
+ match declaration.version_info {
+ VersionInfo::One => version_info = xml::VersionInfo::SingleQuoted(xml::VersionNum::One),
+ VersionInfo::OneDotOne => {
+ version_info = xml::VersionInfo::SingleQuoted(xml::VersionNum::OneDotOne)
+ }
+ }
+ let declaration = xml::XMLDecl {
+ version_info,
+ encoding_decl: None,
+ sd_decl: None,
+ };
+ let declaration = declaration.to_string();
+ if self.unendable {
+ self.inner.ignore_end().send_with_str(&declaration)?;
+ } else {
+ self.inner.try_as_mut()?.send_with_str(&declaration)?;
+ }
+ Ok(())
+ }
+
+ /// Write a full element corresponding with the item implementing `IntoElement` (start tag + content + end tag).
+ pub async fn write_full(&mut self, into_element: &impl IntoElement) -> Result<()> {
+ let element = into_element.into_element();
+ let mut frame = String::new();
+ self.write_element_to_frame(&element, &mut frame)?;
+ self.inner.ignore_end().send_with_str(&frame)?;
+ info!("wrote element: {}", frame);
+ Ok(())
+ }
+
+ /// Write the start tag of an item that implements `IntoElement`. Navigates up the document.
+ pub async fn write_start(&mut self, into_element: &impl IntoElement) -> Result<()> {
+ let element = into_element.into_element();
+ let mut frame = String::new();
+ self.write_element_start_to_frame(&element, &mut frame)?;
+ self.inner.ignore_end().send_with_str(&frame)?;
+ info!("wrote element: {}", frame);
+ Ok(())
+ }
+
+ /// Write all the inner content (everything within the start and end tag of an xml element) of an item that implements `IntoElement`. In the case of an empty element, write nothing.
+ pub async fn write_all_content(&mut self, into_element: &impl IntoElement) -> Result<()> {
+ let mut frame = String::new();
+ for content in &into_element.get_content() {
+ self.write_content_to_frame(content, &mut frame)?;
+ }
+ self.inner.ignore_end().send_with_str(&frame)?;
+ info!("wrote element: {}", frame);
+ Ok(())
+ }
+
+ /// Write an item that implements `IntoContent`. Could be an element, some text, a comment, etc. Anything that could be included in an element body.
+ pub async fn write(&mut self, into_content: &impl IntoContent) -> Result<()> {
+ let content = into_content.into_content();
+ let mut frame = String::new();
+ self.write_content_to_frame(&content, &mut frame)?;
+ self.inner.ignore_end().send_with_str(&frame)?;
+ info!("wrote element: {}", frame);
+ Ok(())
+ }
+
+ /// Navigate down the document structure and write the end tag for the current element opened in the document context.
+ pub async fn write_end(&mut self) -> Result<()> {
+ let mut frame = String::new();
+ self.write_end_tag_to_frame(&mut frame)?;
+ self.inner.ignore_end().send_with_str(&frame)?;
+ info!("wrote element: {}", frame);
+ Ok(())
+ }
+
+ fn write_element_to_frame(&mut self, element: &Element, frame: &mut String) -> Result<()> {
+ if element.content.is_empty() {
+ self.write_empty_to_frame(element, frame)?;
+ } else {
+ self.write_element_start_to_frame(element, frame)?;
+ for content in &element.content {
+ self.write_content_to_frame(content, frame)?;
+ }
+ self.write_end_tag_to_frame(frame)?;
+ }
+ Ok(())
+ }
+
+ fn write_empty_to_frame(&mut self, element: &Element, frame: &mut String) -> Result<()> {
+ let _writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
+
+ let mut namespace_declarations_stack: Vec<_> = self
+ .namespace_declarations
+ .iter()
+ .flatten()
+ .chain(&element.namespace_declaration_overrides)
+ .collect();
+
+ let mut namespace_declarations = element.namespace_declaration_overrides.clone();
+
+ let default_namespace_declaration;
+ let prefix;
+ if let Some(namespace) = &element.name.namespace {
+ if let Some(name_namespace_declaration) = namespace_declarations_stack
+ .iter()
+ .rfind(|namespace_declaration| namespace_declaration.namespace == *namespace)
+ {
+ prefix = name_namespace_declaration.prefix.as_ref();
+ } else {
+ default_namespace_declaration = NamespaceDeclaration {
+ prefix: None,
+ namespace: namespace.clone(),
+ };
+ if namespace_declarations.insert(default_namespace_declaration.clone()) {
+ namespace_declarations_stack.push(&default_namespace_declaration);
+ prefix = None
+ } else {
+ return Err(Error::DuplicateNameSpaceDeclaration(NamespaceDeclaration {
+ prefix: None,
+ namespace: namespace.clone(),
+ }));
+ }
+ }
+ } else {
+ prefix = None
+ }
+
+ let name;
+ if let Some(prefix) = &prefix {
+ name = xml::QName::PrefixedName(xml::PrefixedName {
+ prefix: xml::Prefix::parse_full(prefix)?,
+ local_part: xml::LocalPart::parse_full(&element.name.local_name)?,
+ })
+ } else {
+ name = xml::QName::UnprefixedName(xml::UnprefixedName::parse_full(
+ &element.name.local_name,
+ )?)
+ }
+
+ let mut attributes = Vec::new();
+
+ for namespace_declaration in namespace_declarations.iter() {
+ let ns_name = namespace_declaration
+ .prefix
+ .as_ref()
+ .map(|prefix| -> Result<_> {
+ Ok(xml::NSAttName::PrefixedAttName(xml::PrefixedAttName(
+ xml::NCName::parse_full(&prefix)?,
+ )))
+ })
+ .unwrap_or(Ok(xml::NSAttName::DefaultAttName))?;
+ let value = xml::AttValue::from(namespace_declaration.namespace.as_str());
+ let xml_attribute = xml::Attribute::NamespaceDeclaration { ns_name, value };
+ attributes.push(xml_attribute);
+ }
+
+ for (name, value) in &element.attributes {
+ let prefix;
+ if let Some(namespace) = &name.namespace {
+ let name_namespace_declaration = namespace_declarations_stack
+ .iter()
+ .rfind(|namespace_declaration| namespace_declaration.namespace == *namespace)
+ .ok_or(Error::UndeclaredNamespace(namespace.clone()))?;
+ prefix = name_namespace_declaration.prefix.as_ref();
+ } else {
+ prefix = None
+ }
+
+ let att_name;
+ if let Some(prefix) = &prefix {
+ att_name = xml::QName::PrefixedName(xml::PrefixedName {
+ prefix: xml::Prefix::parse_full(prefix)?,
+ local_part: xml::LocalPart::parse_full(&name.local_name)?,
+ })
+ } else {
+ att_name =
+ xml::QName::UnprefixedName(xml::UnprefixedName::parse_full(&name.local_name)?)
+ }
+
+ let value = xml::AttValue::from(value.as_str());
+
+ let xml_attribute = xml::Attribute::Attribute {
+ name: att_name,
+ value,
+ };
+ attributes.push(xml_attribute);
+ }
+
+ let tag = xml::EmptyElemTag { name, attributes };
+
+ frame.push_str(&tag.to_string());
+
+ // if self.depth.is_empty() {
+ // self.inner.end();
+ // }
+
+ Ok(())
+ }
+
+ fn write_element_start_to_frame(
+ &mut self,
+ element: &Element,
+ frame: &mut String,
+ ) -> Result<()> {
+ let _writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
+
+ let mut namespace_declarations_stack: Vec<_> = self
+ .namespace_declarations
+ .iter()
+ .flatten()
+ .chain(&element.namespace_declaration_overrides)
+ .collect();
+
+ let mut namespace_declarations = element.namespace_declaration_overrides.clone();
+
+ let default_namespace_declaration;
+ let prefix;
+ if let Some(namespace) = &element.name.namespace {
+ if let Some(name_namespace_declaration) = namespace_declarations_stack
+ .iter()
+ .rfind(|namespace_declaration| namespace_declaration.namespace == *namespace)
+ {
+ prefix = name_namespace_declaration.prefix.as_ref();
+ } else {
+ default_namespace_declaration = NamespaceDeclaration {
+ prefix: None,
+ namespace: namespace.clone(),
+ };
+ if namespace_declarations.insert(default_namespace_declaration.clone()) {
+ namespace_declarations_stack.push(&default_namespace_declaration);
+ prefix = None
+ } else {
+ return Err(Error::DuplicateNameSpaceDeclaration(NamespaceDeclaration {
+ prefix: None,
+ namespace: namespace.clone(),
+ }));
+ }
+ }
+ } else {
+ prefix = None
+ }
+
+ let name;
+ if let Some(prefix) = &prefix {
+ name = xml::QName::PrefixedName(xml::PrefixedName {
+ prefix: xml::Prefix::parse_full(prefix)?,
+ local_part: xml::LocalPart::parse_full(&element.name.local_name)?,
+ })
+ } else {
+ name = xml::QName::UnprefixedName(xml::UnprefixedName::parse_full(
+ &element.name.local_name,
+ )?)
+ }
+
+ let mut attributes = Vec::new();
+
+ for namespace_declaration in namespace_declarations.iter() {
+ let ns_name = namespace_declaration
+ .prefix
+ .as_ref()
+ .map(|prefix| -> Result<_> {
+ Ok(xml::NSAttName::PrefixedAttName(xml::PrefixedAttName(
+ xml::NCName::parse_full(&prefix)?,
+ )))
+ })
+ .unwrap_or(Ok(xml::NSAttName::DefaultAttName))?;
+ let value = xml::AttValue::from(namespace_declaration.namespace.as_str());
+ let xml_attribute = xml::Attribute::NamespaceDeclaration { ns_name, value };
+ attributes.push(xml_attribute);
+ }
+
+ for (name, value) in &element.attributes {
+ let prefix;
+ if let Some(namespace) = &name.namespace {
+ let name_namespace_declaration = namespace_declarations_stack
+ .iter()
+ .rfind(|namespace_declaration| namespace_declaration.namespace == *namespace)
+ .ok_or(Error::UndeclaredNamespace(namespace.clone()))?;
+ prefix = name_namespace_declaration.prefix.as_ref();
+ } else {
+ prefix = None
+ }
+
+ let att_name;
+ if let Some(prefix) = &prefix {
+ att_name = xml::QName::PrefixedName(xml::PrefixedName {
+ prefix: xml::Prefix::parse_full(prefix)?,
+ local_part: xml::LocalPart::parse_full(&name.local_name)?,
+ })
+ } else {
+ att_name =
+ xml::QName::UnprefixedName(xml::UnprefixedName::parse_full(&name.local_name)?)
+ }
+
+ let value = xml::AttValue::from(value.as_str());
+
+ let xml_attribute = xml::Attribute::Attribute {
+ name: att_name,
+ value,
+ };
+ attributes.push(xml_attribute);
+ }
+
+ let s_tag = xml::STag { name, attributes };
+
+ frame.push_str(&s_tag.to_string());
+
+ self.depth.push(element.name.clone());
+ self.namespace_declarations
+ .push(namespace_declarations.clone());
+ Ok(())
+ }
+
+ fn write_content_to_frame(&mut self, content: &Content, frame: &mut String) -> Result<()> {
+ match content {
+ Content::Element(element) => self.write_element_to_frame(element, frame)?,
+ Content::Text(text) => {
+ let _writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
+ frame.push_str(&escape_str(text))
+ }
+ // TODO: comments and PI
+ Content::PI => {}
+ Content::Comment(_) => {}
+ }
+ Ok(())
+ }
+
+ fn write_end_tag_to_frame(&mut self, frame: &mut String) -> Result<()> {
+ let _writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
+ if let Some(name) = &self.depth.pop() {
+ let e_tag;
+ let namespace_declarations_stack: Vec<_> =
+ self.namespace_declarations.iter().flatten().collect();
+
+ let prefix;
+ if let Some(namespace) = &name.namespace {
+ let name_namespace_declaration = namespace_declarations_stack
+ .iter()
+ .rfind(|namespace_declaration| namespace_declaration.namespace == *namespace)
+ .ok_or(Error::UndeclaredNamespace(namespace.clone()))?;
+ prefix = name_namespace_declaration.prefix.as_ref();
+ } else {
+ prefix = None
+ }
+
+ if let Some(prefix) = &prefix {
+ e_tag = xml::ETag {
+ name: xml::QName::PrefixedName(xml::PrefixedName {
+ prefix: xml::Prefix::parse_full(prefix)?,
+ local_part: xml::LocalPart::parse_full(&name.local_name)?,
+ }),
+ };
+ } else {
+ e_tag = xml::ETag {
+ name: xml::QName::UnprefixedName(xml::UnprefixedName::parse_full(
+ &name.local_name,
+ )?),
+ };
+ }
+ frame.push_str(&e_tag.to_string());
+ self.namespace_declarations.pop();
+
+ // if self.depth.is_empty() {
+ // self.inner.end();
+ // }
+ Ok(())
+ } else {
+ return Err(Error::NotInElement("".to_string()));
+ }
+ }
+}
+
+impl<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
+ /// Write an XML declaration with the provided `VersionInfo`.
+ pub async fn write_declaration(&mut self, version: VersionInfo) -> Result<()> {
+ let writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
let declaration = Declaration::version(version);
let version_info;
match declaration.version_info {
@@ -65,53 +530,68 @@ impl<W: AsyncWrite + Unpin + Send> Writer<W> {
Ok(())
}
+ /// Write a full element corresponding with the item implementing `IntoElement` (start tag + content + end tag).
pub async fn write_full(&mut self, into_element: &impl IntoElement) -> Result<()> {
let element = into_element.into_element();
self.write_element(&element).await?;
- let bytes = &self.inner.ignore_end().take_log();
- let log = str::from_utf8(bytes).unwrap_or("failed to convert bytes written to str");
- info!("wrote element: {}", log);
+
+ let bytes = self.inner.ignore_end().take_log();
+ let log = String::from_utf8(bytes)
+ .map_err(|err| format!("failed to convert bytes written to str: {err}"));
+ info!("wrote element: {log:?}");
Ok(())
}
+ /// Write the start tag of an item that implements `IntoElement`. Navigates up the document.
pub async fn write_start(&mut self, into_element: &impl IntoElement) -> Result<()> {
let element = into_element.into_element();
self.write_element_start(&element).await?;
- let bytes = &self.inner.ignore_end().take_log();
- let log = str::from_utf8(bytes).unwrap_or("failed to convert bytes written to str");
- info!("wrote element start: {}", log);
+
+ let bytes = self.inner.ignore_end().take_log();
+ let log = String::from_utf8(bytes)
+ .map_err(|err| format!("failed to convert bytes written to str: {err}"));
+ info!("wrote element start: {log:?}");
Ok(())
}
+ /// Write all the inner content (everything within the start and end tag of an xml element) of an item that implements `IntoElement`. In the case of an empty element, write nothing.
pub async fn write_all_content(&mut self, into_element: &impl IntoElement) -> Result<()> {
for content in &into_element.get_content() {
self.write_content(content).await?;
}
- let bytes = &self.inner.ignore_end().take_log();
- let log = str::from_utf8(bytes).unwrap_or("failed to convert bytes written to str");
- info!("wrote element content: {}", log);
+
+ let bytes = self.inner.ignore_end().take_log();
+ let log = String::from_utf8(bytes)
+ .map_err(|err| format!("failed to convert bytes written to str: {err}"));
+ info!("wrote element content: {log:?}");
Ok(())
}
+ /// Write an item that implements `IntoContent`. Could be an element, some text, a comment, etc. Anything that could be included in an element body.
pub async fn write(&mut self, into_content: &impl IntoContent) -> Result<()> {
let content = into_content.into_content();
self.write_content(&content).await?;
- let bytes = &self.inner.ignore_end().take_log();
- let log = str::from_utf8(bytes).unwrap_or("failed to convert bytes written to str");
- info!("wrote element: {}", log);
+
+ let bytes = self.inner.ignore_end().take_log();
+ let log = String::from_utf8(bytes)
+ .map_err(|err| format!("failed to convert bytes written to str: {err}"));
+ info!("wrote element: {log:?}");
Ok(())
}
- // pub async fn write_end(&mut self)
+ /// Navigate down the document structure and write the end tag for the current element opened in the document context.
pub async fn write_end(&mut self) -> Result<()> {
self.write_end_tag().await?;
- let bytes = &self.inner.ignore_end().take_log();
- let log = str::from_utf8(bytes).unwrap_or("failed to convert bytes written to str");
- info!("wrote element end: {}", log);
+
+ let bytes = self.inner.ignore_end().take_log();
+ let log = String::from_utf8(bytes)
+ .map_err(|err| format!("failed to convert bytes written to str: {err}"));
+ info!("wrote element end: {log:?}");
Ok(())
}
#[async_recursion]
+ /// Write an `Element`.
pub async fn write_element(&mut self, element: &Element) -> Result<()> {
if element.content.is_empty() {
self.write_empty(element).await?;
@@ -125,8 +605,13 @@ impl<W: AsyncWrite + Unpin + Send> Writer<W> {
Ok(())
}
+ /// Write an empty element tag from an `Element` (ignoring any content).
pub async fn write_empty(&mut self, element: &Element) -> Result<()> {
- let writer = self.inner.try_as_mut()?;
+ let writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
let mut namespace_declarations_stack: Vec<_> = self
.namespace_declarations
.iter()
@@ -235,8 +720,13 @@ impl<W: AsyncWrite + Unpin + Send> Writer<W> {
Ok(())
}
+ /// Write an element start tag from an `Element`, navigating up in document depth.
pub async fn write_element_start(&mut self, element: &Element) -> Result<()> {
- let writer = self.inner.try_as_mut()?;
+ let writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
let mut namespace_declarations_stack: Vec<_> = self
.namespace_declarations
.iter()
@@ -344,14 +834,17 @@ impl<W: AsyncWrite + Unpin + Send> Writer<W> {
Ok(())
}
+ /// Write some `Content`.
pub async fn write_content(&mut self, content: &Content) -> Result<()> {
match content {
Content::Element(element) => self.write_element(element).await?,
Content::Text(text) => {
- self.inner
- .try_as_mut()?
- .write_all(escape_str(text).as_bytes())
- .await?
+ let writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
+ writer.write_all(escape_str(text).as_bytes()).await?
}
// TODO: comments and PI
Content::PI => {}
@@ -360,8 +853,13 @@ impl<W: AsyncWrite + Unpin + Send> Writer<W> {
Ok(())
}
+ /// Write an end tag (depending on the current document context), moving back down in the document.
pub async fn write_end_tag(&mut self) -> Result<()> {
- let writer = self.inner.try_as_mut()?;
+ let writer = if self.unendable {
+ self.inner.ignore_end()
+ } else {
+ self.inner.try_as_mut()?
+ };
if let Some(name) = &self.depth.pop() {
let e_tag;
let namespace_declarations_stack: Vec<_> =
diff --git a/src/endable.rs b/src/writer/endable.rs
index 6d842f3..6d842f3 100644
--- a/src/endable.rs
+++ b/src/writer/endable.rs
diff --git a/src/loggable.rs b/src/writer/loggable.rs
index dd69668..1b9f64a 100644
--- a/src/loggable.rs
+++ b/src/writer/loggable.rs
@@ -5,6 +5,7 @@ use pin_project::pin_project;
pub use tokio::io::AsyncWrite;
#[pin_project]
+/// Wrapper struct for logging writes to `AsyncWrite` implementors.
#[derive(Debug)]
pub struct Loggable<W> {
log_buffer: Vec<u8>,
@@ -32,8 +33,8 @@ impl<W> Loggable<W> {
impl<W: AsyncWrite + Unpin + Send> Display for Loggable<W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let str = str::from_utf8(&self.log_buffer).unwrap_or("buffer to string conversion failed");
- f.write_str(str)
+ let str = String::from_utf8_lossy(&self.log_buffer);
+ write!(f, "{str}")
}
}
diff --git a/src/xml/mod.rs b/src/xml/mod.rs
index b0d9056..005a122 100644
--- a/src/xml/mod.rs
+++ b/src/xml/mod.rs
@@ -328,7 +328,7 @@ impl<'s> Deref for CharData<'s> {
/// [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
#[derive(Clone, Debug, PartialEq, Eq)]
#[repr(transparent)]
-pub struct Comment<'s>(&'s str);
+pub struct Comment<'s>(pub(crate) &'s str);
impl<'s> Deref for Comment<'s> {
type Target = &'s str;
diff --git a/src/xml/parsers_complete.rs b/src/xml/parsers_complete.rs
index f18d0ff..1e2ac31 100644
--- a/src/xml/parsers_complete.rs
+++ b/src/xml/parsers_complete.rs
@@ -40,7 +40,12 @@ pub trait Parser<'s> {
return Err(crate::error::Error::ExtraData(rest.to_string()));
}
}
- Result::Err(e) => return Err(crate::error::Error::ParseError(e.to_string())),
+ Result::Err(e) => {
+ return Err(crate::error::Error::ParseError(
+ input.to_string(),
+ e.to_string(),
+ ))
+ }
}
}
}