diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 26eb455..9a169b9 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -8,32 +8,36 @@ on: jobs: build: + runs-on: ubuntu-latest + continue-on-error: true + + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Run tests + run: cargo test + + clippy: + runs-on: ubuntu-latest + continue-on-error: true + + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - name: Catch common mistakes + run: cargo clippy --workspace --tests --all-targets -- -D warnings + rustfmt: runs-on: ubuntu-latest + continue-on-error: true steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - default: true - profile: minimal - components: rustfmt, clippy - - name: Build - uses: actions-rs/cargo@v1 - with: - command: build - - name: Run tests - uses: actions-rs/cargo@v1 - with: - command: test - - name: Check formatting - uses: actions-rs/cargo@v1 - with: - command: fmt - args: -- --check - - name: Catch common mistakes - uses: actions-rs/cargo@v1 - with: - command: clippy - args: --all-targets -- -D warnings + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt + - name: Check formatting + run: cargo fmt -- --check diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..2a35f02 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1 @@ +use_small_heuristics = "Max" diff --git a/Cargo.lock b/Cargo.lock index 68d1a54..4dbbc7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14,9 +14,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea5d730647d4fadd988536d06fecce94b7b4f2a7efdae548f1cf4b63205518ab" +checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" dependencies = [ "memchr", ] @@ -38,9 +38,9 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.4" +version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab91ebe16eb252986481c5b62f6098f3b698a45e34b5b98200cf20dd2484a44" +checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" dependencies = [ "anstyle", "anstyle-parse", @@ -52,33 +52,33 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.4" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" +checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" [[package]] name = "anstyle-parse" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317b9a89c1868f5ea6ff1d9539a69f45dffc21ce321ac1fd1160dfa48c8e2140" +checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.0.0" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" +checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" dependencies = [ "windows-sys", ] [[package]] name = "anstyle-wincon" -version = "3.0.1" +version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0699d10d2f4d628a98ee7b57b289abbc98ff3bad977cb3152709d4bf2330628" +checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" dependencies = [ "anstyle", "windows-sys", @@ -86,9 +86,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.75" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" +checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" [[package]] name = "autocfg" @@ -98,9 +98,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "bigdecimal" -version = "0.4.1" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "454bca3db10617b88b566f205ed190aedb0e0e6dd4cad61d3988a72e8c5594cb" +checksum = "9324c8014cd04590682b34f1e9448d38f0674d0f7b2dc553331016ef0e4e9ebc" dependencies = [ "autocfg", "libm", @@ -111,18 +111,15 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.14.0" +version = "3.15.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" +checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa" [[package]] name = "cc" -version = "1.0.83" +version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] +checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5" [[package]] name = "cfg-if" @@ -132,9 +129,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.31" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" +checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" dependencies = [ "android-tzdata", "iana-time-zone", @@ -146,9 +143,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.6" +version = "4.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d04704f56c2cde07f43e8e2c154b43f216dc5c92fc98ada720177362f953b956" +checksum = "949626d00e063efc93b6dca932419ceb5432f99769911c0b995f7e884c778813" dependencies = [ "clap_builder", "clap_derive", @@ -156,9 +153,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.6" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e231faeaca65ebd1ea3c737966bf858971cd38c3849107aa3ea7de90a804e45" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" dependencies = [ "anstream", "anstyle", @@ -168,21 +165,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.4.2" +version = "4.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0862016ff20d69b84ef8247369fabf5c008a7417002411897d40ee1f4532b873" +checksum = "90239a040c80f5e14809ca132ddc4176ab33d5e17e49691793296e3fcb34d72f" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.53", ] [[package]] name = "clap_lex" -version = "0.5.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" [[package]] name = "colorchoice" @@ -192,9 +189,9 @@ checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" [[package]] name = "core-foundation-sys" -version = "0.8.4" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" [[package]] name = "getopts" @@ -216,22 +213,22 @@ dependencies = [ [[package]] name = "heck" -version = "0.4.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "iana-time-zone" -version = "0.1.57" +version = "0.1.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", - "windows", + "windows-core", ] [[package]] @@ -245,9 +242,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.64" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" dependencies = [ "wasm-bindgen", ] @@ -270,27 +267,27 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.148" +version = "0.2.153" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cdc71e17332e86d2e1d38c1f99edcb6288ee11b815fb1a4b049eaa2114d369b" +checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "libm" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4" +checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" [[package]] name = "log" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "memchr" -version = "2.6.4" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" +checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" [[package]] name = "num-bigint" @@ -305,52 +302,51 @@ dependencies = [ [[package]] name = "num-integer" -version = "0.1.45" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" dependencies = [ - "autocfg", "num-traits", ] [[package]] name = "num-traits" -version = "0.2.16" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" +checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" dependencies = [ "autocfg", ] [[package]] name = "once_cell" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "proc-macro2" -version = "1.0.67" +version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328" +checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.33" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] [[package]] name = "regex" -version = "1.9.6" +version = "1.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebee201405406dbf528b8b672104ae6d6d63e6d118cb10e4d51abbc7b58044ff" +checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" dependencies = [ "aho-corasick", "memchr", @@ -360,9 +356,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.3.9" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9" +checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", @@ -371,24 +367,21 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.7.5" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "roxmltree" -version = "0.14.1" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "921904a62e410e37e215c40381b7117f830d9d89ba60ab5236170541dd25646b" -dependencies = [ - "xmlparser", -] +checksum = "3cd14fd5e3b777a7422cca79358c57a8f6e3a703d9ac187448d0daf220c2407f" [[package]] name = "strsim" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01" [[package]] name = "syn" @@ -403,9 +396,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.37" +version = "2.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7303ef2c05cd654186cb250d29049a24840ca25d2747c25c0381c8d9e2f582e8" +checksum = "7383cd0e49fff4b6b90ca5670bfd3e9d6a733b3f90c686605aa7eec8c4996032" dependencies = [ "proc-macro2", "quote", @@ -440,9 +433,9 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-segmentation" -version = "1.10.1" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" +checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" [[package]] name = "unicode-width" @@ -458,9 +451,9 @@ checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "wasm-bindgen" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -468,24 +461,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.53", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -493,22 +486,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.53", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" [[package]] name = "winapi" @@ -523,28 +516,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" [[package]] -name = "windows" -version = "0.48.0" +name = "windows-core" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ "windows-targets", ] [[package]] name = "windows-sys" -version = "0.48.0" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" -version = "0.48.5" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", @@ -557,45 +550,45 @@ dependencies = [ [[package]] name = "windows_aarch64_gnullvm" -version = "0.48.5" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" +checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" [[package]] name = "windows_aarch64_msvc" -version = "0.48.5" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" +checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" [[package]] name = "windows_i686_gnu" -version = "0.48.5" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" +checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" [[package]] name = "windows_i686_msvc" -version = "0.48.5" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" +checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" [[package]] name = "windows_x86_64_gnu" -version = "0.48.5" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" +checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" [[package]] name = "windows_x86_64_gnullvm" -version = "0.48.5" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" +checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" [[package]] name = "windows_x86_64_msvc" -version = "0.48.5" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" +checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" [[package]] name = "wsdl-parser" @@ -603,7 +596,7 @@ version = "0.1.0" dependencies = [ "Inflector", "roxmltree", - "syn 2.0.37", + "syn 2.0.53", "text-diff", "xsd-parser", ] @@ -625,19 +618,13 @@ version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fcb9cbac069e033553e8bb871be2fbdffcab578eb25bd0f7c508cedc6dcd75a" -[[package]] -name = "xmlparser" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" - [[package]] name = "xsd-macro-utils" version = "0.1.0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.53", ] [[package]] @@ -647,7 +634,7 @@ dependencies = [ "Inflector", "num-bigint", "roxmltree", - "syn 2.0.37", + "syn 2.0.53", "text-diff", "xml-rs", "xsd-macro-utils", diff --git a/wsdl-parser-cli/Cargo.toml b/wsdl-parser-cli/Cargo.toml index 3fecd06..43c6bd9 100644 --- a/wsdl-parser-cli/Cargo.toml +++ b/wsdl-parser-cli/Cargo.toml @@ -17,6 +17,6 @@ path = "src/main.rs" [dependencies] anyhow = "1" clap = { version = "4", features = ["derive"] } -roxmltree = { version = "0.14", features = ["std"] } +roxmltree = { version = "0.19", features = ["std"] } wsdl-parser = { path = "../wsdl-parser" } xsd-parser = { path = "../xsd-parser" } diff --git a/wsdl-parser-cli/src/main.rs b/wsdl-parser-cli/src/main.rs index 3c53bb5..1843bed 100644 --- a/wsdl-parser-cli/src/main.rs +++ b/wsdl-parser-cli/src/main.rs @@ -1,15 +1,14 @@ -use clap::Parser; +use std::{ + fs, + io::{prelude::*, Read}, + path::{Path, PathBuf}, +}; use anyhow::Context; - +use clap::Parser; use roxmltree::{Document, Node}; -use std::fs; -use std::io::{prelude::*, Read}; -use std::path::{Path, PathBuf}; -use wsdl_parser::generator::generate; -use wsdl_parser::parser::definitions::Definitions; -use xsd_parser::generator::builder::GeneratorBuilder; -use xsd_parser::parser::schema::parse_schema; +use wsdl_parser::{generator::generate, parser::definitions::Definitions}; +use xsd_parser::{generator::builder::GeneratorBuilder, parser::schema::parse_schema}; #[derive(Parser)] #[clap(name = env!("CARGO_PKG_NAME"))] @@ -31,9 +30,7 @@ fn main() -> anyhow::Result<()> { let input_path = opt.input.unwrap_or_else(|| PathBuf::from("input/wsdl")); let md = fs::metadata(&input_path).unwrap(); if md.is_dir() { - let output_path = opt - .output - .unwrap_or_else(|| PathBuf::from("output/wsdl-rs")); + let output_path = opt.output.unwrap_or_else(|| PathBuf::from("output/wsdl-rs")); process_dir(&input_path, &output_path)?; } else { process_single_file(&input_path, opt.output.as_deref())?; @@ -65,15 +62,10 @@ fn process_single_file(input_path: &Path, output_path: Option<&Path>) -> anyhow: let doc = Document::parse(text.as_str()).context("Failed to parse input document")?; let definitions = Definitions::new(&doc.root_element()); let gen = GeneratorBuilder::default().build(); - let schemas = definitions - .types() - .iter() - .flat_map(|t| t.schemas()) - .collect::>>(); - let mut code = schemas - .iter() - .map(|f| gen.generate_rs_file(&parse_schema(f))) - .collect::>(); + let schemas = + definitions.types().iter().flat_map(|t| t.schemas()).collect::>>(); + let mut code = + schemas.iter().map(|f| gen.generate_rs_file(&parse_schema(f))).collect::>(); code.push(generate(&definitions)); let code = code.join(""); diff --git a/wsdl-parser/Cargo.toml b/wsdl-parser/Cargo.toml index a83e976..741befd 100644 --- a/wsdl-parser/Cargo.toml +++ b/wsdl-parser/Cargo.toml @@ -12,7 +12,7 @@ license = "MIT OR Apache-2.0" [dependencies] Inflector = "0.11" -roxmltree = "0.14" +roxmltree = "0.19" [dev-dependencies] syn = { version = "2", features = ["full", "extra-traits"] } diff --git a/wsdl-parser/src/generator/function.rs b/wsdl-parser/src/generator/function.rs index 16bddd6..29c845c 100644 --- a/wsdl-parser/src/generator/function.rs +++ b/wsdl-parser/src/generator/function.rs @@ -1,17 +1,15 @@ -use crate::parser::definitions::Definitions; -use crate::parser::message::{Message, Part}; -use crate::parser::port_type::Operation; -use crate::parser::port_type::OperationType::{OneWay, RequestResponse}; - -const GENERIC_TRANSPORT: Param<'static> = Param { - name: "T", - typename: "transport::Transport", -}; -const ARGUMENT_TRANSPORT: Param<'static> = Param { - name: "transport", - typename: "T", +use crate::parser::{ + definitions::Definitions, + message::{Message, Part}, + port_type::{ + Operation, + OperationType::{OneWay, RequestResponse}, + }, }; +const GENERIC_TRANSPORT: Param<'static> = Param { name: "T", typename: "transport::Transport" }; +const ARGUMENT_TRANSPORT: Param<'static> = Param { name: "transport", typename: "T" }; + #[derive(Debug)] pub struct Function<'a> { pub generic_params: Vec>, @@ -57,9 +55,7 @@ impl<'a> Function<'a> { Function { generic_params: vec![GENERIC_TRANSPORT], arguments: get_input_params(input_message), - return_type: output_message - .and_then(|m| m.parts()[0].element()) - .unwrap_or(""), + return_type: output_message.and_then(|m| m.parts()[0].element()).unwrap_or(""), documentation: operation.documentation(), name: operation.name(), } @@ -75,10 +71,7 @@ fn get_input_params<'a>(input: Option<&'a Message<'_>>) -> Vec> { if input.parts().len() == 1 { // ONVIF case - result.push(Param { - name: "request", - typename: input.parts()[0].element().unwrap(), - }) + result.push(Param { name: "request", typename: input.parts()[0].element().unwrap() }) } else { result.append(&mut input.parts().iter().map(Param::new).collect()); }; diff --git a/wsdl-parser/src/generator/mod.rs b/wsdl-parser/src/generator/mod.rs index 2884576..fe1858f 100644 --- a/wsdl-parser/src/generator/mod.rs +++ b/wsdl-parser/src/generator/mod.rs @@ -1,10 +1,10 @@ -use crate::generator::function::Function; -use crate::parser::definitions::Definitions; -use inflector::cases::pascalcase::to_pascal_case; -use inflector::cases::snakecase::to_snake_case; -use roxmltree::Namespace; use std::borrow::Cow; +use inflector::cases::{pascalcase::to_pascal_case, snakecase::to_snake_case}; +use roxmltree::Namespace; + +use crate::{generator::function::Function, parser::definitions::Definitions}; + pub mod function; pub fn generate(definitions: &Definitions) -> String { diff --git a/wsdl-parser/src/parser/binding.rs b/wsdl-parser/src/parser/binding.rs index d3ed770..fdab74e 100644 --- a/wsdl-parser/src/parser/binding.rs +++ b/wsdl-parser/src/parser/binding.rs @@ -1,7 +1,7 @@ -use crate::parser::constants::attribute; -use crate::parser::{ElementType, WsdlElement}; use roxmltree::Node; +use crate::parser::{constants::attribute, ElementType, WsdlElement}; + #[derive(Clone, Debug)] pub struct Binding<'a> { node: Node<'a, 'a>, @@ -10,15 +10,11 @@ pub struct Binding<'a> { impl<'a> Binding<'a> { pub fn name(&self) -> &'a str { - self.node - .attribute(attribute::NAME) - .expect("Namespace required for wsdl:binding") + self.node.attribute(attribute::NAME).expect("Namespace required for wsdl:binding") } pub fn type_(&self) -> &'a str { - self.node - .attribute(attribute::TYPE) - .expect("Location required for wsdl:binding") + self.node.attribute(attribute::TYPE).expect("Location required for wsdl:binding") } pub fn new(node: &Node<'a, '_>) -> Self { @@ -48,9 +44,7 @@ pub struct Operation<'a> { impl<'a> Operation<'a> { pub fn name(&self) -> &'a str { - self.node - .attribute(attribute::NAME) - .expect("Namespace required for wsdl:binding") + self.node.attribute(attribute::NAME).expect("Namespace required for wsdl:binding") } pub fn new(node: &Node<'a, '_>) -> Self { @@ -65,12 +59,7 @@ impl<'a> Operation<'a> { _ => {} } } - Self { - node: *node, - input, - output, - faults, - } + Self { node: *node, input, output, faults } } } diff --git a/wsdl-parser/src/parser/definitions.rs b/wsdl-parser/src/parser/definitions.rs index a982bb8..df04a62 100644 --- a/wsdl-parser/src/parser/definitions.rs +++ b/wsdl-parser/src/parser/definitions.rs @@ -1,12 +1,16 @@ -use crate::parser::binding::Binding; -use crate::parser::constants::attribute; -use crate::parser::message::Message; -use crate::parser::port_type::{Param, PortType}; -use crate::parser::types::Types; -use crate::parser::{ElementType, WsdlElement}; -use roxmltree::{Namespace, Node}; use std::collections::HashMap; +use roxmltree::{Namespace, Node}; + +use crate::parser::{ + binding::Binding, + constants::attribute, + message::Message, + port_type::{Param, PortType}, + types::Types, + ElementType, WsdlElement, +}; + // Content: Sequence [1..1] // wsdl:documentation [0..1] from type wsdl:tDocumented // Any element [0..*] Namespace: ##other, Process Contents: lax from type wsdl:tExtensibleDocumented @@ -44,7 +48,7 @@ pub struct Definitions<'a> { impl<'a> Definitions<'a> { pub fn target_namespace(&self) -> Option<&'a Namespace<'_>> { match self.node().attribute(attribute::TARGET_NAMESPACE) { - Some(tn) => self.node().namespaces().iter().find(|a| a.uri() == tn), + Some(tn) => self.node().namespaces().find(|a| a.uri() == tn), None => None, } } @@ -74,8 +78,7 @@ impl<'a> Definitions<'a> { } pub fn get_message_by_param(&self, param: &Param<'_>) -> Option<&Message> { - self.messages - .get(param.message().split(':').last().unwrap()) + self.messages.get(param.message().split(':').last().unwrap()) } pub fn new(definitions: &Node<'a, '_>) -> Self { @@ -119,9 +122,7 @@ impl<'a> Definitions<'a> { fn add_port_type(&mut self, node: &Node<'a, '_>) { let port_type = PortType::new(node); assert!( - self.port_types - .insert(port_type.name(), port_type) - .is_none(), + self.port_types.insert(port_type.name(), port_type).is_none(), "portType name must be unique" ); } @@ -159,15 +160,11 @@ pub struct Import<'a> { impl<'a> Import<'a> { pub fn namespace(&self) -> &'a str { - self.node - .attribute(attribute::NAMESPACE) - .expect("Namespace required for wsdl:Import") + self.node.attribute(attribute::NAMESPACE).expect("Namespace required for wsdl:Import") } pub fn location(&self) -> &'a str { - self.node - .attribute(attribute::LOCATION) - .expect("Location required for wsdl:Import") + self.node.attribute(attribute::LOCATION).expect("Location required for wsdl:Import") } pub fn new(node: &Node<'a, '_>) -> Self { diff --git a/wsdl-parser/src/parser/message.rs b/wsdl-parser/src/parser/message.rs index 33fd969..1ca04dd 100644 --- a/wsdl-parser/src/parser/message.rs +++ b/wsdl-parser/src/parser/message.rs @@ -1,7 +1,7 @@ -use crate::parser::constants::attribute; -use crate::parser::{ElementType, WsdlElement}; use roxmltree::Node; +use crate::parser::{constants::attribute, ElementType, WsdlElement}; + // Element information: // Namespace: http://schemas.xmlsoap.org/wsdl/ // Schema document: wsdl11.xsd @@ -47,9 +47,7 @@ impl<'a> Message<'a> { } pub fn name(&self) -> &'a str { - self.node - .attribute(attribute::NAME) - .expect("Name required for wsdl:message") + self.node.attribute(attribute::NAME).expect("Name required for wsdl:message") } pub fn parts(&self) -> &[Part<'a>] { @@ -81,9 +79,7 @@ pub struct Part<'a> { impl<'a> Part<'a> { pub fn name(&self) -> &'a str { - self.node - .attribute(attribute::NAME) - .expect("Name required for wsdl:part") + self.node.attribute(attribute::NAME).expect("Name required for wsdl:part") } pub fn element(&self) -> Option<&'a str> { diff --git a/wsdl-parser/src/parser/mod.rs b/wsdl-parser/src/parser/mod.rs index c5e59c0..8826913 100644 --- a/wsdl-parser/src/parser/mod.rs +++ b/wsdl-parser/src/parser/mod.rs @@ -55,9 +55,10 @@ impl<'a> WsdlElement for roxmltree::Node<'a, '_> { #[cfg(test)] mod test { - use crate::parser::definitions::Definitions; use roxmltree::Document; + use crate::parser::definitions::Definitions; + const TEXT: &str = r#" PortType<'a> { } pub fn name(&self) -> &'a str { - self.node - .attribute(attribute::NAME) - .expect("Name required for wsdl:portType") + self.node.attribute(attribute::NAME).expect("Name required for wsdl:portType") } pub fn operations(&self) -> &[Operation] { @@ -83,16 +81,11 @@ pub struct Operation<'a> { impl<'a> Operation<'a> { pub fn new(node: &Node<'a, '_>) -> Self { - Self { - node: *node, - ty: OperationType::new(node), - } + Self { node: *node, ty: OperationType::new(node) } } pub fn name(&self) -> &'a str { - self.node - .attribute(attribute::NAME) - .expect("Name required for wsdl:operation") + self.node.attribute(attribute::NAME).expect("Name required for wsdl:operation") } pub fn parameter_order(&self) -> Option<&'a str> { @@ -116,22 +109,10 @@ impl<'a> Operation<'a> { #[derive(Clone, Debug, PartialEq)] pub enum OperationType<'a> { - RequestResponse { - input: Param<'a>, - output: Param<'a>, - faults: Vec>, - }, - OneWay { - input: Param<'a>, - }, - SolicitResponse { - output: Param<'a>, - input: Param<'a>, - faults: Vec>, - }, - Notification { - output: Param<'a>, - }, + RequestResponse { input: Param<'a>, output: Param<'a>, faults: Vec> }, + OneWay { input: Param<'a> }, + SolicitResponse { output: Param<'a>, input: Param<'a>, faults: Vec> }, + Notification { output: Param<'a> }, } impl<'a> OperationType<'a> { @@ -162,9 +143,7 @@ impl<'a> OperationType<'a> { } } else { // OneWay - OperationType::OneWay { - input: Param::new(&ch), - } + OperationType::OneWay { input: Param::new(&ch) } }; } ElementType::Output => { @@ -183,9 +162,7 @@ impl<'a> OperationType<'a> { .collect(), } } else { - OperationType::Notification { - output: Param::new(&ch), - } + OperationType::Notification { output: Param::new(&ch) } }; } _ => continue, @@ -227,14 +204,10 @@ impl<'a> Fault<'a> { } pub fn name(&self) -> &'a str { - self.node - .attribute(attribute::NAME) - .expect("Name required for wsdl:fault") + self.node.attribute(attribute::NAME).expect("Name required for wsdl:fault") } pub fn message(&self) -> &'a str { - self.node - .attribute(attribute::MESSAGE) - .expect("Message required for wsdl:fault") + self.node.attribute(attribute::MESSAGE).expect("Message required for wsdl:fault") } } diff --git a/wsdl-parser/src/parser/types.rs b/wsdl-parser/src/parser/types.rs index 129e253..5f9786f 100644 --- a/wsdl-parser/src/parser/types.rs +++ b/wsdl-parser/src/parser/types.rs @@ -20,9 +20,6 @@ impl<'a> Types<'a> { } pub fn schemas(&self) -> Vec> { - self.node - .children() - .filter(|n| n.is_element() && n.tag_name().name() == "schema") - .collect() + self.node.children().filter(|n| n.is_element() && n.tag_name().name() == "schema").collect() } } diff --git a/wsdl-parser/tests/mod.rs b/wsdl-parser/tests/mod.rs index 5eb8fcc..e710b0f 100644 --- a/wsdl-parser/tests/mod.rs +++ b/wsdl-parser/tests/mod.rs @@ -1,8 +1,6 @@ use roxmltree::{Document, Node}; -use wsdl_parser::generator::generate; -use wsdl_parser::parser::definitions::Definitions; -use xsd_parser::generator::builder::GeneratorBuilder; -use xsd_parser::parser::schema::parse_schema; +use wsdl_parser::{generator::generate, parser::definitions::Definitions}; +use xsd_parser::{generator::builder::GeneratorBuilder, parser::schema::parse_schema}; mod port_type_to_function; @@ -10,15 +8,10 @@ pub fn generate_wsdl(input: &str) -> String { let doc = Document::parse(input).unwrap(); let definitions = Definitions::new(&doc.root_element()); let gen = GeneratorBuilder::default().build(); - let schemas = definitions - .types() - .iter() - .flat_map(|t| t.schemas()) - .collect::>>(); - let mut code = schemas - .iter() - .map(|f| gen.generate_rs_file(&parse_schema(f))) - .collect::>(); + let schemas = + definitions.types().iter().flat_map(|t| t.schemas()).collect::>>(); + let mut code = + schemas.iter().map(|f| gen.generate_rs_file(&parse_schema(f))).collect::>(); code.push(generate(&definitions)); code.join("") diff --git a/xsd-macro-utils/src/lib.rs b/xsd-macro-utils/src/lib.rs index 8e13a91..5bfdc58 100644 --- a/xsd-macro-utils/src/lib.rs +++ b/xsd-macro-utils/src/lib.rs @@ -8,9 +8,7 @@ mod union; #[proc_macro_derive(UtilsTupleIo)] pub fn tuple_serde(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); - tuple::serde(&ast) - .unwrap_or_else(|err| err.to_compile_error()) - .into() + tuple::serde(&ast).unwrap_or_else(|err| err.to_compile_error()).into() } // Adds YaSerialize and YaDeserialize implementations for types that support FromStr and Display traits. @@ -67,7 +65,5 @@ pub fn default_serde(input: TokenStream) -> TokenStream { #[proc_macro_derive(UtilsUnionSerDe)] pub fn union_serde(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); - union::serde(&ast) - .unwrap_or_else(|err| err.to_compile_error()) - .into() + union::serde(&ast).unwrap_or_else(|err| err.to_compile_error()).into() } diff --git a/xsd-macro-utils/src/tuple.rs b/xsd-macro-utils/src/tuple.rs index 0928a59..0d2dc2f 100644 --- a/xsd-macro-utils/src/tuple.rs +++ b/xsd-macro-utils/src/tuple.rs @@ -6,7 +6,7 @@ enum Type<'a> { Simple(&'a syn::Path), String(&'a syn::Path), Struct(&'a syn::Path), - Vec(&'a syn::Path, &'a syn::Path), + Vec(&'a syn::Path), } pub fn serde(ast: &syn::DeriveInput) -> syn::Result { @@ -25,18 +25,13 @@ fn from_str(ast: &syn::DeriveInput) -> syn::Result { Type::Struct(ty) | Type::Simple(ty) => { quote! { <#ty as ::std::str::FromStr>::from_str(s).map_err(|e| e.to_string())? } } - Type::Vec(_, subtype) => match Type::from_path(subtype) { + Type::Vec(subtype) => match Type::from_path(subtype) { Type::String(subtype) | Type::Struct(subtype) | Type::Simple(subtype) => quote! { s.split_whitespace() .filter_map(|s| <#subtype as ::std::str::FromStr>::from_str(s).ok()) .collect() }, - _ => { - return Err(syn::Error::new( - subtype.span(), - "Not implemented for this subtype", - )) - } + _ => return Err(syn::Error::new(subtype.span(), "Not implemented for this subtype")), }, }; @@ -58,7 +53,7 @@ fn display(ast: &syn::DeriveInput) -> syn::Result { Type::String(_) | Type::Simple(_) | Type::Struct(_) => quote! { write!(f, "{}", self.0) }, - Type::Vec(_, subtype) => match Type::from_path(subtype) { + Type::Vec(subtype) => match Type::from_path(subtype) { Type::String(_) | Type::Simple(_) | Type::Struct(_) => quote! { let mut it = self.0.iter(); if let Some(val) = it.next() { @@ -70,12 +65,7 @@ fn display(ast: &syn::DeriveInput) -> syn::Result { Ok(()) }, - _ => { - return Err(syn::Error::new( - subtype.span(), - "Not implemented for this subtype", - )) - } + _ => return Err(syn::Error::new(subtype.span(), "Not implemented for this subtype")), }, }; @@ -92,19 +82,11 @@ fn display(ast: &syn::DeriveInput) -> syn::Result { impl Type<'_> { pub fn from_path(path: &syn::Path) -> Type { - match path - .segments - .last() - .expect("Empty type") - .ident - .to_string() - .as_str() - { + match path.segments.last().expect("Empty type").ident.to_string().as_str() { "bool" | "i8" | "u8" | "i16" | "u16" | "i32" | "u32" | "i64" | "u64" | "f32" | "f64" => Type::Simple(path), "String" => Type::String(path), "Vec" => Type::Vec( - path, extract_subtype(path.segments.last().expect("Missing subtype")) .expect("Vec subtype not found"), ), diff --git a/xsd-macro-utils/src/union.rs b/xsd-macro-utils/src/union.rs index a4ddb78..c809193 100644 --- a/xsd-macro-utils/src/union.rs +++ b/xsd-macro-utils/src/union.rs @@ -36,10 +36,7 @@ pub fn serde(ast: &syn::DeriveInput) -> syn::Result { }) .collect::>>()?, _ => { - return Err(syn::Error::new( - Span::call_site(), - "This macro can only be used on enums", - )); + return Err(syn::Error::new(Span::call_site(), "This macro can only be used on enums")); } }; diff --git a/xsd-parser-cli/src/main.rs b/xsd-parser-cli/src/main.rs index dd8f15f..51577ae 100644 --- a/xsd-parser-cli/src/main.rs +++ b/xsd-parser-cli/src/main.rs @@ -1,14 +1,13 @@ -use clap::Parser; +use std::{ + fs, + fs::OpenOptions, + io::{prelude::*, Read}, + path::{Path, PathBuf}, +}; use anyhow::Context; - -use std::fs; -use std::io::{prelude::*, Read}; -use std::path::{Path, PathBuf}; - -use std::fs::OpenOptions; -use xsd_parser::generator::builder::GeneratorBuilder; -use xsd_parser::parser::parse; +use clap::Parser; +use xsd_parser::{generator::builder::GeneratorBuilder, parser::parse}; #[derive(Parser)] #[clap(name = env!("CARGO_PKG_NAME"))] @@ -77,10 +76,6 @@ fn load_file(path: &Path) -> std::io::Result { } fn write_to_file(path: &Path, text: &str) -> std::io::Result<()> { - let mut file = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(path)?; + let mut file = OpenOptions::new().write(true).truncate(true).create(true).open(path)?; file.write_all(text.as_bytes()) } diff --git a/xsd-parser/Cargo.toml b/xsd-parser/Cargo.toml index 432b87b..a13f5e6 100644 --- a/xsd-parser/Cargo.toml +++ b/xsd-parser/Cargo.toml @@ -12,7 +12,7 @@ license = "MIT OR Apache-2.0" [dependencies] Inflector = "0.11" -roxmltree = "0.14" +roxmltree = "0.19" [dev-dependencies] num-bigint = "0.4" diff --git a/xsd-parser/src/generator/alias.rs b/xsd-parser/src/generator/alias.rs index 3fd6323..7908df2 100644 --- a/xsd-parser/src/generator/alias.rs +++ b/xsd-parser/src/generator/alias.rs @@ -1,5 +1,4 @@ -use crate::generator::Generator; -use crate::parser::types::Alias; +use crate::{generator::Generator, parser::types::Alias}; pub trait AliasGenerator { fn generate(&self, entity: &Alias, gen: &Generator) -> String { diff --git a/xsd-parser/src/generator/base.rs b/xsd-parser/src/generator/base.rs index efb8afb..d66ab5d 100644 --- a/xsd-parser/src/generator/base.rs +++ b/xsd-parser/src/generator/base.rs @@ -1,11 +1,16 @@ -use crate::generator::default::{ - default_format_comment, default_format_name, default_format_type, default_modify_type, -}; -use crate::generator::utils::match_built_in_type; -use crate::generator::Generator; -use crate::parser::types::{RsEntity, TypeModifier}; use std::borrow::Cow; +use crate::{ + generator::{ + default::{ + default_format_comment, default_format_name, default_format_type, default_modify_type, + }, + utils::match_built_in_type, + Generator, + }, + parser::types::{RsEntity, TypeModifier}, +}; + pub trait BaseGenerator { fn indent(&self) -> String { " ".repeat(self.indent_size()) @@ -39,11 +44,7 @@ pub trait BaseGenerator { } fn join_subtypes(&self, subtypes: &[RsEntity], gen: &Generator) -> String { - subtypes - .iter() - .map(|f| gen.generate(f)) - .collect::>() - .join("\n") + subtypes.iter().map(|f| gen.generate(f)).collect::>().join("\n") } } diff --git a/xsd-parser/src/generator/builder.rs b/xsd-parser/src/generator/builder.rs index bf4afbd..e688584 100644 --- a/xsd-parser/src/generator/builder.rs +++ b/xsd-parser/src/generator/builder.rs @@ -1,12 +1,14 @@ -use crate::generator::alias::{AliasGenerator, DefaultAliasGen}; -use crate::generator::base::{BaseGenerator, DefaultBaseGenerator}; -use crate::generator::enum_case::{DefaultEnumCaseGen, EnumCaseGenerator}; -use crate::generator::import::{DefaultImportGen, ImportGenerator}; -use crate::generator::r#enum::{DefaultEnumGen, EnumGenerator}; -use crate::generator::r#struct::{DefaultStructGen, StructGenerator}; -use crate::generator::struct_field::{DefaultStructFieldGen, StructFieldGenerator}; -use crate::generator::tuple_struct::{DefaultTupleStructGen, TupleStructGenerator}; -use crate::generator::Generator; +use crate::generator::{ + alias::{AliasGenerator, DefaultAliasGen}, + base::{BaseGenerator, DefaultBaseGenerator}, + enum_case::{DefaultEnumCaseGen, EnumCaseGenerator}, + import::{DefaultImportGen, ImportGenerator}, + r#enum::{DefaultEnumGen, EnumGenerator}, + r#struct::{DefaultStructGen, StructGenerator}, + struct_field::{DefaultStructFieldGen, StructFieldGenerator}, + tuple_struct::{DefaultTupleStructGen, TupleStructGenerator}, + Generator, +}; #[derive(Default)] pub struct GeneratorBuilder<'input> { @@ -57,29 +59,21 @@ impl<'input> GeneratorBuilder<'input> { pub fn build(self) -> Generator<'input> { let mut gen = self.gen; - gen.base - .get_or_insert_with(|| Box::new(DefaultBaseGenerator {})); //.set_target_ns(&gen.target_ns); + gen.base.get_or_insert_with(|| Box::new(DefaultBaseGenerator {})); //.set_target_ns(&gen.target_ns); - gen.tuple_struct_gen - .get_or_insert_with(|| Box::new(DefaultTupleStructGen {})); + gen.tuple_struct_gen.get_or_insert_with(|| Box::new(DefaultTupleStructGen {})); - gen.struct_gen - .get_or_insert_with(|| Box::new(DefaultStructGen {})); + gen.struct_gen.get_or_insert_with(|| Box::new(DefaultStructGen {})); - gen.struct_field_gen - .get_or_insert_with(|| Box::new(DefaultStructFieldGen {})); + gen.struct_field_gen.get_or_insert_with(|| Box::new(DefaultStructFieldGen {})); - gen.enum_case_gen - .get_or_insert_with(|| Box::new(DefaultEnumCaseGen {})); + gen.enum_case_gen.get_or_insert_with(|| Box::new(DefaultEnumCaseGen {})); - gen.enum_gen - .get_or_insert_with(|| Box::new(DefaultEnumGen {})); + gen.enum_gen.get_or_insert_with(|| Box::new(DefaultEnumGen {})); - gen.alias_gen - .get_or_insert_with(|| Box::new(DefaultAliasGen {})); + gen.alias_gen.get_or_insert_with(|| Box::new(DefaultAliasGen {})); - gen.import_gen - .get_or_insert_with(|| Box::new(DefaultImportGen {})); + gen.import_gen.get_or_insert_with(|| Box::new(DefaultImportGen {})); gen } @@ -87,10 +81,10 @@ impl<'input> GeneratorBuilder<'input> { #[cfg(test)] mod test { - use crate::generator::builder::GeneratorBuilder; - use crate::generator::tuple_struct::TupleStructGenerator; - use crate::generator::Generator; - use crate::parser::types::{RsEntity, TupleStruct}; + use crate::{ + generator::{builder::GeneratorBuilder, tuple_struct::TupleStructGenerator, Generator}, + parser::types::{RsEntity, TupleStruct}, + }; fn test_generator_state(gen: &Generator) { assert!(gen.tuple_struct_gen.is_some()); diff --git a/xsd-parser/src/generator/default.rs b/xsd-parser/src/generator/default.rs index 87327ff..35bae27 100644 --- a/xsd-parser/src/generator/default.rs +++ b/xsd-parser/src/generator/default.rs @@ -1,10 +1,13 @@ -use crate::generator::utils::{filter_type_name, sanitize, split_comment_line, split_name}; -use crate::parser::types::TypeModifier; -use inflector::cases::pascalcase::to_pascal_case; -use inflector::cases::snakecase::to_snake_case; -use roxmltree::Namespace; use std::borrow::Cow; +use inflector::cases::{pascalcase::to_pascal_case, snakecase::to_snake_case}; +use roxmltree::Namespace; + +use crate::{ + generator::utils::{filter_type_name, sanitize, split_comment_line, split_name}, + parser::types::TypeModifier, +}; + pub fn default_format_comment(doc: Option<&str>, max_len: usize, indent: usize) -> String { doc.unwrap_or("") .lines() @@ -86,10 +89,9 @@ pub fn yaserde_for_element( }; match prefix { - Some(p) => format!( - "{}#[yaserde(prefix = \"{}\", rename = \"{}\")]\n", - indent, p, field_name - ), + Some(p) => { + format!("{}#[yaserde(prefix = \"{}\", rename = \"{}\")]\n", indent, p, field_name) + } None => format!("{}#[yaserde(rename = \"{}\")]\n", indent, field_name), } } @@ -154,8 +156,10 @@ mod test { ) .unwrap() .root_element() - .namespaces()[0] - .clone(), + .namespaces() + .next() + .cloned() + .unwrap(), ); assert_eq!(default_format_type("tt:Type", &ns), "Type"); assert_eq!(default_format_type("tt:TyName", &ns), "TyName"); @@ -183,17 +187,8 @@ mod test { assert_eq!(default_modify_type("Type", &[Array]), "Vec"); assert_eq!(default_modify_type("Type", &[Empty]), "()"); - assert_eq!( - default_modify_type("Type", &[Recursive, Option]), - "Vec" - ); - assert_eq!( - default_modify_type("Type", &[Recursive, Array, Option]), - "Vec" - ); - assert_eq!( - default_modify_type("Type", &[Recursive, Array, Empty]), - "()" - ); + assert_eq!(default_modify_type("Type", &[Recursive, Option]), "Vec"); + assert_eq!(default_modify_type("Type", &[Recursive, Array, Option]), "Vec"); + assert_eq!(default_modify_type("Type", &[Recursive, Array, Empty]), "()"); } } diff --git a/xsd-parser/src/generator/enum.rs b/xsd-parser/src/generator/enum.rs index b044f92..d314e72 100644 --- a/xsd-parser/src/generator/enum.rs +++ b/xsd-parser/src/generator/enum.rs @@ -1,8 +1,10 @@ -use crate::generator::validator::gen_validate_impl; -use crate::generator::Generator; -use crate::parser::types::{Enum, EnumSource}; use std::borrow::Cow; +use crate::{ + generator::{validator::gen_validate_impl, Generator}, + parser::types::{Enum, EnumSource}, +}; + pub trait EnumGenerator { fn generate(&self, entity: &Enum, gen: &Generator) -> String { let name = self.get_name(entity, gen); @@ -51,15 +53,11 @@ pub trait EnumGenerator { } fn get_type_name(&self, entity: &Enum, gen: &Generator) -> String { - gen.base() - .format_type_name(entity.type_name.as_str(), gen) - .into() + gen.base().format_type_name(entity.type_name.as_str(), gen).into() } fn get_name(&self, entity: &Enum, gen: &Generator) -> String { - gen.base() - .format_type_name(entity.name.as_str(), gen) - .into() + gen.base().format_type_name(entity.name.as_str(), gen).into() } fn macros(&self, entity: &Enum, gen: &Generator) -> Cow<'static, str> { diff --git a/xsd-parser/src/generator/enum_case.rs b/xsd-parser/src/generator/enum_case.rs index 9639e1b..a5580db 100644 --- a/xsd-parser/src/generator/enum_case.rs +++ b/xsd-parser/src/generator/enum_case.rs @@ -1,7 +1,7 @@ -use crate::generator::default::default_format_type; -use crate::generator::utils::split_name; -use crate::generator::Generator; -use crate::parser::types::{EnumCase, EnumSource}; +use crate::{ + generator::{default::default_format_type, utils::split_name, Generator}, + parser::types::{EnumCase, EnumSource}, +}; pub trait EnumCaseGenerator { fn generate(&self, entity: &EnumCase, gen: &Generator) -> String { @@ -29,17 +29,12 @@ pub trait EnumCaseGenerator { } fn get_type_name(&self, entity: &EnumCase, gen: &Generator) -> String { - let formatted_type = gen - .base() - .format_type_name(entity.type_name.as_ref().unwrap(), gen); - gen.base() - .modify_type(formatted_type.as_ref(), &entity.type_modifiers) - .into() + let formatted_type = gen.base().format_type_name(entity.type_name.as_ref().unwrap(), gen); + gen.base().modify_type(formatted_type.as_ref(), &entity.type_modifiers).into() } fn format_comment(&self, entity: &EnumCase, gen: &Generator) -> String { - gen.base() - .format_comment(entity.comment.as_deref(), gen.base().indent_size()) + gen.base().format_comment(entity.comment.as_deref(), gen.base().indent_size()) } fn macros(&self, entity: &EnumCase, gen: &Generator) -> String { diff --git a/xsd-parser/src/generator/import.rs b/xsd-parser/src/generator/import.rs index bed8ad1..09c377c 100644 --- a/xsd-parser/src/generator/import.rs +++ b/xsd-parser/src/generator/import.rs @@ -1,5 +1,4 @@ -use crate::generator::Generator; -use crate::parser::types::Import; +use crate::{generator::Generator, parser::types::Import}; pub trait ImportGenerator { fn generate(&self, entity: &Import, _gen: &Generator) -> String { diff --git a/xsd-parser/src/generator/mod.rs b/xsd-parser/src/generator/mod.rs index 5294733..8b2fb71 100644 --- a/xsd-parser/src/generator/mod.rs +++ b/xsd-parser/src/generator/mod.rs @@ -11,19 +11,18 @@ pub mod tuple_struct; mod utils; pub mod validator; +use std::{borrow::Borrow, cell::RefCell}; + use roxmltree::Namespace; -use std::borrow::Borrow; -use std::cell::RefCell; -use crate::generator::alias::AliasGenerator; -use crate::generator::base::BaseGenerator; -use crate::generator::enum_case::EnumCaseGenerator; -use crate::generator::import::ImportGenerator; -use crate::generator::r#enum::EnumGenerator; -use crate::generator::r#struct::StructGenerator; -use crate::generator::struct_field::StructFieldGenerator; -use crate::generator::tuple_struct::TupleStructGenerator; -use crate::parser::types::{RsEntity, RsFile}; +use crate::{ + generator::{ + alias::AliasGenerator, base::BaseGenerator, enum_case::EnumCaseGenerator, + import::ImportGenerator, r#enum::EnumGenerator, r#struct::StructGenerator, + struct_field::StructFieldGenerator, tuple_struct::TupleStructGenerator, + }, + parser::types::{RsEntity, RsFile}, +}; #[derive(Default)] pub struct Generator<'input> { @@ -44,11 +43,7 @@ impl<'input> Generator<'input> { pub fn generate_rs_file(&self, schema: &RsFile<'input>) -> String { *self.target_ns.borrow_mut() = schema.target_ns.clone(); *self.xsd_ns.borrow_mut() = schema.xsd_ns.clone(); - schema - .types - .iter() - .map(|entity| self.generate(entity)) - .collect() + schema.types.iter().map(|entity| self.generate(entity)).collect() } pub fn generate(&self, entity: &RsEntity) -> String { @@ -79,8 +74,10 @@ impl<'input> Generator<'input> { #[cfg(test)] mod test { - use crate::generator::builder::GeneratorBuilder; - use crate::parser::types::{RsEntity, RsFile, TupleStruct}; + use crate::{ + generator::builder::GeneratorBuilder, + parser::types::{RsEntity, RsFile, TupleStruct}, + }; #[test] fn test_generate_rs_file() { @@ -97,10 +94,8 @@ mod test { let comment = "// comment\n"; let macros = "#[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)]\n"; let validation = "impl Validate for Name {}\n"; - let expected = format!( - "{}{}pub struct Name (pub Type);\n\n{}", - comment, macros, validation - ); + let expected = + format!("{}{}pub struct Name (pub Type);\n\n{}", comment, macros, validation); assert_eq!(gen.generate_rs_file(&rs_file), expected); } } diff --git a/xsd-parser/src/generator/struct.rs b/xsd-parser/src/generator/struct.rs index 0d0a1e3..f6a641a 100644 --- a/xsd-parser/src/generator/struct.rs +++ b/xsd-parser/src/generator/struct.rs @@ -1,8 +1,10 @@ -use crate::generator::validator::gen_validate_impl; -use crate::generator::Generator; -use crate::parser::types::Struct; use std::borrow::Cow; +use crate::{ + generator::{validator::gen_validate_impl, Generator}, + parser::types::Struct, +}; + pub trait StructGenerator { fn generate(&self, entity: &Struct, gen: &Generator) -> String { format!( @@ -68,20 +70,12 @@ pub trait StructGenerator { fn shift(&self, text: &str, indent: &str) -> String { text.replace("\n\n\n", "\n") // TODO: fix this workaround replace .split('\n') - .map(|s| { - if !s.is_empty() { - format!("\n{}{}", indent, s) - } else { - "\n".to_string() - } - }) + .map(|s| if !s.is_empty() { format!("\n{}{}", indent, s) } else { "\n".to_string() }) .fold(indent.to_string(), |acc, x| acc + &x) } fn get_type_name(&self, entity: &Struct, gen: &Generator) -> String { - gen.base() - .format_type_name(entity.name.as_str(), gen) - .into() + gen.base().format_type_name(entity.name.as_str(), gen).into() } fn macros(&self, _entity: &Struct, gen: &Generator) -> Cow<'static, str> { @@ -116,10 +110,7 @@ pub trait StructGenerator { fn validation(&self, entity: &Struct, gen: &Generator) -> Cow<'static, str> { // Empty validation - Cow::Owned(gen_validate_impl( - self.get_type_name(entity, gen).as_str(), - "", - )) + Cow::Owned(gen_validate_impl(self.get_type_name(entity, gen).as_str(), "")) } } diff --git a/xsd-parser/src/generator/struct_field.rs b/xsd-parser/src/generator/struct_field.rs index ae1fba0..dee270c 100644 --- a/xsd-parser/src/generator/struct_field.rs +++ b/xsd-parser/src/generator/struct_field.rs @@ -1,8 +1,10 @@ -use crate::generator::default::{ - yaserde_for_attribute, yaserde_for_element, yaserde_for_flatten_element, +use crate::{ + generator::{ + default::{yaserde_for_attribute, yaserde_for_element, yaserde_for_flatten_element}, + Generator, + }, + parser::types::{StructField, StructFieldSource, TypeModifier}, }; -use crate::generator::Generator; -use crate::parser::types::{StructField, StructFieldSource, TypeModifier}; pub trait StructFieldGenerator { fn generate(&self, entity: &StructField, gen: &Generator) -> String { @@ -22,9 +24,7 @@ pub trait StructFieldGenerator { fn get_type_name(&self, entity: &StructField, gen: &Generator) -> String { gen.base() .modify_type( - gen.base() - .format_type_name(entity.type_name.as_str(), gen) - .as_ref(), + gen.base().format_type_name(entity.type_name.as_str(), gen).as_ref(), &entity.type_modifiers, ) .into() @@ -35,8 +35,7 @@ pub trait StructFieldGenerator { } fn format_comment(&self, entity: &StructField, gen: &Generator) -> String { - gen.base() - .format_comment(entity.comment.as_deref(), gen.base().indent_size()) + gen.base().format_comment(entity.comment.as_deref(), gen.base().indent_size()) } fn macros(&self, entity: &StructField, gen: &Generator) -> String { diff --git a/xsd-parser/src/generator/tuple_struct.rs b/xsd-parser/src/generator/tuple_struct.rs index 5ae162f..6e5496f 100644 --- a/xsd-parser/src/generator/tuple_struct.rs +++ b/xsd-parser/src/generator/tuple_struct.rs @@ -1,8 +1,13 @@ -use crate::generator::validator::{gen_facet_validation, gen_validate_impl}; -use crate::generator::Generator; -use crate::parser::types::TupleStruct; use std::borrow::Cow; +use crate::{ + generator::{ + validator::{gen_facet_validation, gen_validate_impl}, + Generator, + }, + parser::types::TupleStruct, +}; + pub trait TupleStructGenerator { fn generate(&self, entity: &TupleStruct, gen: &Generator) -> String { format!( @@ -23,18 +28,14 @@ pub trait TupleStructGenerator { fn get_type_name(&self, entity: &TupleStruct, gen: &Generator) -> String { gen.base() .modify_type( - gen.base() - .format_type_name(entity.type_name.as_str(), gen) - .as_ref(), + gen.base().format_type_name(entity.type_name.as_str(), gen).as_ref(), &entity.type_modifiers, ) .into() } fn get_name(&self, entity: &TupleStruct, gen: &Generator) -> String { - gen.base() - .format_type_name(entity.name.as_str(), gen) - .into() + gen.base().format_type_name(entity.name.as_str(), gen).into() } fn macros(&self, _entity: &TupleStruct, _gen: &Generator) -> Cow<'static, str> { @@ -51,10 +52,7 @@ pub trait TupleStructGenerator { .iter() .map(|f| gen_facet_validation(&f.facet_type, "0", &self.get_type_name(entity, gen))) .fold(String::new(), |x, y| (x + &y)); - Cow::Owned(gen_validate_impl( - self.get_name(entity, gen).as_str(), - body.as_str(), - )) + Cow::Owned(gen_validate_impl(self.get_name(entity, gen).as_str(), body.as_str())) } } diff --git a/xsd-parser/src/generator/utils.rs b/xsd-parser/src/generator/utils.rs index 98355ec..ed94780 100644 --- a/xsd-parser/src/generator/utils.rs +++ b/xsd-parser/src/generator/utils.rs @@ -217,8 +217,10 @@ mod test { ) .unwrap() .root_element() - .namespaces()[0] - .clone(), + .namespaces() + .next() + .cloned() + .unwrap(), ); let match_type = |name| match_built_in_type(name, &xsd_ns); diff --git a/xsd-parser/src/generator/validator.rs b/xsd-parser/src/generator/validator.rs index f8fa63c..fc6f93c 100644 --- a/xsd-parser/src/generator/validator.rs +++ b/xsd-parser/src/generator/validator.rs @@ -1,6 +1,7 @@ -use crate::parser::xsd_elements::FacetType; use std::borrow::Cow; +use crate::parser::xsd_elements::FacetType; + pub trait Validate { fn validate(&self) -> Result<(), String> { Ok(()) @@ -144,7 +145,7 @@ mod test { #[test] fn test_validator_for_tuple_struct() { - struct Foo(i64); + struct Foo(()); impl Validate for Foo { fn validate(&self) -> Result<(), String> { Err("Error".to_owned()) diff --git a/xsd-parser/src/parser/all.rs b/xsd-parser/src/parser/all.rs index dbbd42b..04d3e9b 100644 --- a/xsd-parser/src/parser/all.rs +++ b/xsd-parser/src/parser/all.rs @@ -2,10 +2,12 @@ use std::cell::RefCell; use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{RsEntity, Struct, StructField, TypeModifier}; -use crate::parser::utils::{enum_to_field, get_documentation, get_parent_name}; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::{RsEntity, Struct, StructField, TypeModifier}, + utils::{enum_to_field, get_documentation, get_parent_name}, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_all(node: &Node, parent: &Node) -> RsEntity { let name = get_parent_name(node); diff --git a/xsd-parser/src/parser/any.rs b/xsd-parser/src/parser/any.rs index e898fd8..b73cbcb 100644 --- a/xsd-parser/src/parser/any.rs +++ b/xsd-parser/src/parser/any.rs @@ -1,7 +1,10 @@ -use crate::parser::types::{RsEntity, StructField, StructFieldSource, TypeModifier}; -use crate::parser::utils::get_documentation; use roxmltree::Node; +use crate::parser::{ + types::{RsEntity, StructField, StructFieldSource, TypeModifier}, + utils::get_documentation, +}; + pub fn parse_any(node: &Node) -> RsEntity { RsEntity::StructField(StructField { name: "any".to_string(), diff --git a/xsd-parser/src/parser/any_attribute.rs b/xsd-parser/src/parser/any_attribute.rs index 9e0233a..b3a89f5 100644 --- a/xsd-parser/src/parser/any_attribute.rs +++ b/xsd-parser/src/parser/any_attribute.rs @@ -1,7 +1,10 @@ -use crate::parser::types::{RsEntity, StructField, StructFieldSource, TypeModifier}; -use crate::parser::utils::get_documentation; use roxmltree::Node; +use crate::parser::{ + types::{RsEntity, StructField, StructFieldSource, TypeModifier}, + utils::get_documentation, +}; + pub fn parse_any_attribute(node: &Node) -> RsEntity { RsEntity::StructField(StructField { name: "any_attribute".to_string(), diff --git a/xsd-parser/src/parser/attribute.rs b/xsd-parser/src/parser/attribute.rs index 43a2175..9d7ef18 100644 --- a/xsd-parser/src/parser/attribute.rs +++ b/xsd-parser/src/parser/attribute.rs @@ -1,9 +1,11 @@ use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{Alias, RsEntity, Struct, StructField, StructFieldSource, TypeModifier}; -use crate::parser::utils::get_documentation; -use crate::parser::xsd_elements::{ElementType, UseType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::{Alias, RsEntity, Struct, StructField, StructFieldSource, TypeModifier}, + utils::get_documentation, + xsd_elements::{ElementType, UseType, XsdNode}, +}; pub fn parse_attribute(node: &Node, parent: &Node) -> RsEntity { if parent.xsd_type() == ElementType::Schema { @@ -16,11 +18,7 @@ pub fn parse_attribute(node: &Node, parent: &Node) -> RsEntity { .expect("All attributes have name or ref") .to_string(); - let type_name = node - .attr_type() - .or_else(|| node.attr_ref()) - .unwrap_or("String") - .to_string(); + let type_name = node.attr_type().or_else(|| node.attr_ref()).unwrap_or("String").to_string(); let type_modifier = match node.attr_use() { UseType::Optional => TypeModifier::Option, @@ -48,9 +46,7 @@ fn parse_global_attribute(node: &Node) -> RsEntity { }); } - let name = node - .attr_name() - .unwrap_or_else(|| panic!("Name attribute required. {:?}", node)); + let name = node.attr_name().unwrap_or_else(|| panic!("Name attribute required. {:?}", node)); if let Some(ty) = node.attr_type() { return RsEntity::Alias(Alias { @@ -61,27 +57,20 @@ fn parse_global_attribute(node: &Node) -> RsEntity { }); } - if let Some(content) = node - .children() - .filter(|n| n.is_element() && n.xsd_type() == ElementType::SimpleType) - .last() + if let Some(content) = + node.children().filter(|n| n.is_element() && n.xsd_type() == ElementType::SimpleType).last() { let mut entity = parse_node(&content, node); entity.set_name(name); return entity; } - RsEntity::Struct(Struct { - name: name.to_string(), - ..Default::default() - }) + RsEntity::Struct(Struct { name: name.to_string(), ..Default::default() }) } #[cfg(test)] mod test { - use crate::parser::attribute::parse_global_attribute; - use crate::parser::types::RsEntity; - use crate::parser::utils::find_child; + use crate::parser::{attribute::parse_global_attribute, types::RsEntity, utils::find_child}; #[test] fn test_global_attribute_with_nested_type() { diff --git a/xsd-parser/src/parser/attribute_group.rs b/xsd-parser/src/parser/attribute_group.rs index e5a348e..4704b80 100644 --- a/xsd-parser/src/parser/attribute_group.rs +++ b/xsd-parser/src/parser/attribute_group.rs @@ -1,19 +1,19 @@ use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{Alias, RsEntity, Struct, StructField}; -use crate::parser::utils::get_documentation; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::{Alias, RsEntity, Struct, StructField}, + utils::get_documentation, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_attribute_group(node: &Node, parent: &Node) -> RsEntity { if parent.xsd_type() == ElementType::Schema { return parse_global_attribute_group(node); } - let reference = node - .attr_ref() - .expect("Non-global attributeGroups must be references.") - .to_string(); + let reference = + node.attr_ref().expect("Non-global attributeGroups must be references.").to_string(); RsEntity::Alias(Alias { name: reference.to_string(), @@ -24,9 +24,7 @@ pub fn parse_attribute_group(node: &Node, parent: &Node) -> RsEntity { } fn parse_global_attribute_group(node: &Node) -> RsEntity { - let name = node - .attr_name() - .unwrap_or_else(|| panic!("Name attribute required. {:?}", node)); + let name = node.attr_name().unwrap_or_else(|| panic!("Name attribute required. {:?}", node)); let fields = attributes_to_fields(node); @@ -51,9 +49,9 @@ pub fn attributes_to_fields(node: &Node) -> Vec { #[cfg(test)] mod test { - use crate::parser::attribute_group::parse_global_attribute_group; - use crate::parser::types::RsEntity; - use crate::parser::utils::find_child; + use crate::parser::{ + attribute_group::parse_global_attribute_group, types::RsEntity, utils::find_child, + }; #[test] fn test_global_attribute_with_nested_type() { diff --git a/xsd-parser/src/parser/choice.rs b/xsd-parser/src/parser/choice.rs index 7542866..f286613 100644 --- a/xsd-parser/src/parser/choice.rs +++ b/xsd-parser/src/parser/choice.rs @@ -1,8 +1,10 @@ use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{Enum, EnumSource, RsEntity}; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::{Enum, EnumSource, RsEntity}, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_choice(choice: &Node) -> RsEntity { let enum_cases = choice diff --git a/xsd-parser/src/parser/complex_content.rs b/xsd-parser/src/parser/complex_content.rs index bdfaea0..641e245 100644 --- a/xsd-parser/src/parser/complex_content.rs +++ b/xsd-parser/src/parser/complex_content.rs @@ -1,8 +1,10 @@ use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::RsEntity; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::RsEntity, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_complex_content(node: &Node) -> RsEntity { let content = node diff --git a/xsd-parser/src/parser/complex_type.rs b/xsd-parser/src/parser/complex_type.rs index bddde6c..bed4dcc 100644 --- a/xsd-parser/src/parser/complex_type.rs +++ b/xsd-parser/src/parser/complex_type.rs @@ -2,12 +2,14 @@ use std::cell::RefCell; use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{RsEntity, Struct, StructField, StructFieldSource}; -use crate::parser::utils::{ - attribute_groups_to_aliases, attributes_to_fields, get_documentation, get_parent_name, +use crate::parser::{ + node_parser::parse_node, + types::{RsEntity, Struct, StructField, StructFieldSource}, + utils::{ + attribute_groups_to_aliases, attributes_to_fields, get_documentation, get_parent_name, + }, + xsd_elements::{ElementType, XsdNode}, }; -use crate::parser::xsd_elements::{ElementType, XsdNode}; // A complex type can contain one and only one of the following elements, // which determines the type of content allowed in the complex type. @@ -35,14 +37,7 @@ pub fn parse_complex_type(node: &Node, parent: &Node) -> RsEntity { .filter(|n| n.is_element() && AVAILABLE_CONTENT_TYPES.contains(&n.xsd_type())) .last(); - if content.is_none() - || content - .unwrap() - .children() - .filter(|n| n.is_element()) - .count() - == 0 - { + if content.is_none() || content.unwrap().children().filter(|n| n.is_element()).count() == 0 { //No content (or empty), only attributes return RsEntity::Struct(Struct { diff --git a/xsd-parser/src/parser/element.rs b/xsd-parser/src/parser/element.rs index df84031..19d5cbd 100644 --- a/xsd-parser/src/parser/element.rs +++ b/xsd-parser/src/parser/element.rs @@ -1,12 +1,14 @@ use roxmltree::Node; -use crate::parser::constants::attribute; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{ - Alias, EnumCase, EnumSource, RsEntity, Struct, StructField, StructFieldSource, TypeModifier, +use crate::parser::{ + constants::attribute, + node_parser::parse_node, + types::{ + Alias, EnumCase, EnumSource, RsEntity, Struct, StructField, StructFieldSource, TypeModifier, + }, + utils::get_documentation, + xsd_elements::{max_occurs, min_occurs, ElementType, MaxOccurs, XsdNode}, }; -use crate::parser::utils::get_documentation; -use crate::parser::xsd_elements::{max_occurs, min_occurs, ElementType, MaxOccurs, XsdNode}; const SUPPORTED_CONTENT_TYPES: [ElementType; 2] = [ElementType::SimpleType, ElementType::ComplexType]; @@ -75,10 +77,8 @@ fn parse_field_of_sequence(node: &Node, _: &Node) -> RsEntity { .to_string(); if node.has_attribute(attribute::TYPE) || node.has_attribute(attribute::REF) { - let type_name = node - .attr_type() - .unwrap_or_else(|| node.attr_ref().unwrap_or("String")) - .to_string(); + let type_name = + node.attr_type().unwrap_or_else(|| node.attr_ref().unwrap_or("String")).to_string(); return RsEntity::StructField(StructField { name, @@ -94,12 +94,7 @@ fn parse_field_of_sequence(node: &Node, _: &Node) -> RsEntity { .children() .filter(|n| SUPPORTED_CONTENT_TYPES.contains(&n.xsd_type())) .last() - .unwrap_or_else(|| { - panic!( - "Must have content if no 'type' or 'ref' attribute: {:?}", - node - ) - }); + .unwrap_or_else(|| panic!("Must have content if no 'type' or 'ref' attribute: {:?}", node)); let mut field_type = parse_node(&content_node, node); @@ -116,9 +111,7 @@ fn parse_field_of_sequence(node: &Node, _: &Node) -> RsEntity { } fn parse_global_element(node: &Node) -> RsEntity { - let name = node - .attr_name() - .expect("Name required if the element is a child of the schema"); + let name = node.attr_name().expect("Name required if the element is a child of the schema"); if node.has_attribute(attribute::TYPE) { return RsEntity::Alias(Alias { @@ -129,10 +122,8 @@ fn parse_global_element(node: &Node) -> RsEntity { }); } - let content_node = node - .children() - .filter(|n| SUPPORTED_CONTENT_TYPES.contains(&n.xsd_type())) - .last(); + let content_node = + node.children().filter(|n| SUPPORTED_CONTENT_TYPES.contains(&n.xsd_type())).last(); if let Some(content) = content_node { let mut content_entity = parse_node(&content, node); @@ -180,9 +171,7 @@ pub fn element_modifier(node: &Node) -> TypeModifier { #[cfg(test)] mod test { - use crate::parser::element::*; - use crate::parser::types::RsEntity; - use crate::parser::utils::find_child; + use crate::parser::{element::*, types::RsEntity, utils::find_child}; #[test] fn test_global_element_without_type() { diff --git a/xsd-parser/src/parser/extension.rs b/xsd-parser/src/parser/extension.rs index 81800b5..1341b5a 100644 --- a/xsd-parser/src/parser/extension.rs +++ b/xsd-parser/src/parser/extension.rs @@ -1,13 +1,15 @@ -use crate::parser::constants::{attribute, tag}; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{RsEntity, Struct, StructField, StructFieldSource}; -use crate::parser::utils::{ - attribute_groups_to_aliases, attributes_to_fields, get_base, get_documentation, -}; -use crate::parser::xsd_elements::{ElementType, ExtensionType, XsdNode}; -use roxmltree::Node; use std::cell::RefCell; +use roxmltree::Node; + +use crate::parser::{ + constants::{attribute, tag}, + node_parser::parse_node, + types::{RsEntity, Struct, StructField, StructFieldSource}, + utils::{attribute_groups_to_aliases, attributes_to_fields, get_base, get_documentation}, + xsd_elements::{ElementType, ExtensionType, XsdNode}, +}; + const AVAILABLE_CONTENT_TYPES: [ElementType; 6] = [ ElementType::All, // Not presented in ONVIF ElementType::Attribute, @@ -48,9 +50,7 @@ fn simple_content_extension(node: &Node) -> RsEntity { } fn complex_content_extension(node: &Node) -> RsEntity { - let base = node - .attribute(attribute::BASE) - .expect("The base value is required"); + let base = node.attribute(attribute::BASE).expect("The base value is required"); let mut fields = attributes_to_fields(node); diff --git a/xsd-parser/src/parser/import.rs b/xsd-parser/src/parser/import.rs index e10f55b..c19d993 100644 --- a/xsd-parser/src/parser/import.rs +++ b/xsd-parser/src/parser/import.rs @@ -1,14 +1,14 @@ -use crate::parser::constants::attribute; -use crate::parser::types::{Import, RsEntity}; use roxmltree::Node; +use crate::parser::{ + constants::attribute, + types::{Import, RsEntity}, +}; + pub fn parse_import(node: &Node) -> RsEntity { RsEntity::Import(Import { name: node.attribute(attribute::NAMESPACE).unwrap_or("").into(), - location: node - .attribute(attribute::SCHEMA_LOCATION) - .unwrap_or("") - .into(), + location: node.attribute(attribute::SCHEMA_LOCATION).unwrap_or("").into(), comment: None, }) } diff --git a/xsd-parser/src/parser/list.rs b/xsd-parser/src/parser/list.rs index b9bdfe8..a5db2c1 100644 --- a/xsd-parser/src/parser/list.rs +++ b/xsd-parser/src/parser/list.rs @@ -1,16 +1,15 @@ use roxmltree::Node; -use crate::parser::constants::attribute; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{RsEntity, TupleStruct, TypeModifier}; -use crate::parser::utils::find_child; +use crate::parser::{ + constants::attribute, + node_parser::parse_node, + types::{RsEntity, TupleStruct, TypeModifier}, + utils::find_child, +}; pub fn parse_list(list: &Node) -> RsEntity { let mut result = match list.attribute(attribute::ITEM_TYPE) { - Some(item_type) => TupleStruct { - type_name: item_type.to_string(), - ..Default::default() - }, + Some(item_type) => TupleStruct { type_name: item_type.to_string(), ..Default::default() }, None => { let nested_simple_type = find_child(list, "simpleType").expect( "itemType not allowed if the content contains a simpleType element. Otherwise, required." diff --git a/xsd-parser/src/parser/mod.rs b/xsd-parser/src/parser/mod.rs index 0138dc3..e03275f 100644 --- a/xsd-parser/src/parser/mod.rs +++ b/xsd-parser/src/parser/mod.rs @@ -23,10 +23,13 @@ mod union; mod utils; pub mod xsd_elements; -use crate::parser::schema::parse_schema; -use crate::parser::types::{RsEntity, RsFile}; use std::collections::HashMap; +use crate::parser::{ + schema::parse_schema, + types::{RsEntity, RsFile}, +}; + // FIXME: Actually pass up errors #[allow(clippy::result_unit_err)] pub fn parse(text: &str) -> Result { @@ -35,11 +38,8 @@ pub fn parse(text: &str) -> Result { let mut map = HashMap::new(); - let schema = root - .children() - .filter(|e| e.is_element()) - .last() - .expect("Schema element is required"); + let schema = + root.children().filter(|e| e.is_element()).last().expect("Schema element is required"); let schema_rs = parse_schema(&schema); for ty in &schema_rs.types { diff --git a/xsd-parser/src/parser/node_parser.rs b/xsd-parser/src/parser/node_parser.rs index eab87b2..2cc0219 100644 --- a/xsd-parser/src/parser/node_parser.rs +++ b/xsd-parser/src/parser/node_parser.rs @@ -1,24 +1,26 @@ use roxmltree::Node; -use crate::parser::all::parse_all; -use crate::parser::any::parse_any; -use crate::parser::any_attribute::parse_any_attribute; -use crate::parser::attribute::parse_attribute; -use crate::parser::attribute_group::parse_attribute_group; -use crate::parser::choice::parse_choice; -use crate::parser::complex_content::parse_complex_content; -use crate::parser::complex_type::parse_complex_type; -use crate::parser::element::parse_element; -use crate::parser::extension::parse_extension; -use crate::parser::import::parse_import; -use crate::parser::list::parse_list; -use crate::parser::restriction::parse_restriction; -use crate::parser::sequence::parse_sequence; -use crate::parser::simple_content::parse_simple_content; -use crate::parser::simple_type::parse_simple_type; -use crate::parser::types::RsEntity; -use crate::parser::union::parse_union; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + all::parse_all, + any::parse_any, + any_attribute::parse_any_attribute, + attribute::parse_attribute, + attribute_group::parse_attribute_group, + choice::parse_choice, + complex_content::parse_complex_content, + complex_type::parse_complex_type, + element::parse_element, + extension::parse_extension, + import::parse_import, + list::parse_list, + restriction::parse_restriction, + sequence::parse_sequence, + simple_content::parse_simple_content, + simple_type::parse_simple_type, + types::RsEntity, + union::parse_union, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_node(node: &Node, parent: &Node) -> RsEntity { use ElementType::*; @@ -42,10 +44,6 @@ pub fn parse_node(node: &Node, parent: &Node) -> RsEntity { SimpleType => parse_simple_type(node, parent), Union => parse_union(node), - _ => unreachable!( - "Unsupported node:\n {:?}\nparent = {:?}\n", - node, - node.parent() - ), + _ => unreachable!("Unsupported node:\n {:?}\nparent = {:?}\n", node, node.parent()), } } diff --git a/xsd-parser/src/parser/restriction.rs b/xsd-parser/src/parser/restriction.rs index 4901923..76eb173 100644 --- a/xsd-parser/src/parser/restriction.rs +++ b/xsd-parser/src/parser/restriction.rs @@ -1,17 +1,21 @@ use std::cell::RefCell; -use crate::parser::constants::tag; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{ - Enum, EnumCase, EnumSource, Facet, RsEntity, Struct, StructField, StructFieldSource, - TupleStruct, -}; -use crate::parser::utils::{ - attribute_groups_to_aliases, attributes_to_fields, get_base, get_documentation, get_parent_name, -}; -use crate::parser::xsd_elements::{ElementType, FacetType, RestrictionType, XsdNode}; use roxmltree::Node; +use crate::parser::{ + constants::tag, + node_parser::parse_node, + types::{ + Enum, EnumCase, EnumSource, Facet, RsEntity, Struct, StructField, StructFieldSource, + TupleStruct, + }, + utils::{ + attribute_groups_to_aliases, attributes_to_fields, get_base, get_documentation, + get_parent_name, + }, + xsd_elements::{ElementType, FacetType, RestrictionType, XsdNode}, +}; + const AVAILABLE_CONTENT_TYPES: [ElementType; 7] = [ ElementType::All, // Not presented in ONVIF ElementType::AnyAttribute, @@ -49,11 +53,7 @@ fn simple_type_restriction(node: &Node) -> RsEntity { } }; - RsEntity::TupleStruct(TupleStruct { - type_name: base.to_string(), - facets, - ..Default::default() - }) + RsEntity::TupleStruct(TupleStruct { type_name: base.to_string(), facets, ..Default::default() }) } fn simple_content_restriction(node: &Node) -> RsEntity { @@ -103,10 +103,7 @@ fn complex_content_restriction(node: &Node) -> RsEntity { fn facets(node: &Node) -> Vec { node.children() .filter_map(|n| match n.xsd_type() { - ElementType::Facet(x) => Some(Facet { - facet_type: x, - comment: get_documentation(&n), - }), + ElementType::Facet(x) => Some(Facet { facet_type: x, comment: get_documentation(&n) }), _ => None, }) .collect() @@ -136,9 +133,7 @@ fn is_simple_enumerations(node: &Node) -> bool { } fn is_simple_enumeration(node: &Node) -> bool { - let val = node - .attr_value() - .expect("Value required for xsd:enumeration"); + let val = node.attr_value().expect("Value required for xsd:enumeration"); !val.is_empty() && val.chars().all(|c| c.is_alphanumeric() || c == '-') } diff --git a/xsd-parser/src/parser/schema.rs b/xsd-parser/src/parser/schema.rs index 0b65989..36be5ef 100644 --- a/xsd-parser/src/parser/schema.rs +++ b/xsd-parser/src/parser/schema.rs @@ -1,20 +1,25 @@ use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::RsFile; -use crate::parser::utils::target_namespace; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::RsFile, + utils::target_namespace, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_schema<'input>(schema: &Node<'_, 'input>) -> RsFile<'input> { + let mut xsd_namespaces = schema + .namespaces() + .filter(|namespace| namespace.uri() == "http://www.w3.org/2001/XMLSchema"); + RsFile { name: "".into(), namespace: None, target_ns: target_namespace(schema).cloned(), - xsd_ns: schema - .namespaces() - .iter() - .rev() - .find(|a| a.uri() == "http://www.w3.org/2001/XMLSchema") + xsd_ns: xsd_namespaces + .clone() + .find(|namespace| namespace.name().is_some()) + .or_else(|| xsd_namespaces.next()) .cloned(), types: schema .children() @@ -37,6 +42,24 @@ pub fn parse_schema<'input>(schema: &Node<'_, 'input>) -> RsFile<'input> { mod test { use crate::parser::schema::parse_schema; + #[test] + fn test_single_xsd_ns() { + let doc = roxmltree::Document::parse( + r#" + + + "#, + ) + .unwrap(); + + let res = parse_schema(&doc.root_element()); + assert_eq!(res.xsd_ns.unwrap().name().unwrap(), "xs"); + } + #[test] fn test_multiple_xsd_ns() { let doc = roxmltree::Document::parse( @@ -54,6 +77,6 @@ mod test { .unwrap(); let res = parse_schema(&doc.root_element()); - assert_eq!(res.xsd_ns.unwrap().name().unwrap(), "xsd"); + assert_eq!(res.xsd_ns.unwrap().name().unwrap(), "xs"); } } diff --git a/xsd-parser/src/parser/sequence.rs b/xsd-parser/src/parser/sequence.rs index a14a537..48b8a19 100644 --- a/xsd-parser/src/parser/sequence.rs +++ b/xsd-parser/src/parser/sequence.rs @@ -2,10 +2,12 @@ use std::cell::RefCell; use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{RsEntity, Struct, StructField, TypeModifier}; -use crate::parser::utils::{enum_to_field, get_documentation, get_parent_name}; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::{RsEntity, Struct, StructField, TypeModifier}, + utils::{enum_to_field, get_documentation, get_parent_name}, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_sequence(sequence: &Node, parent: &Node) -> RsEntity { let name = get_parent_name(sequence); diff --git a/xsd-parser/src/parser/simple_content.rs b/xsd-parser/src/parser/simple_content.rs index de6e2b8..4e3bd3b 100644 --- a/xsd-parser/src/parser/simple_content.rs +++ b/xsd-parser/src/parser/simple_content.rs @@ -1,8 +1,10 @@ use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::RsEntity; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::RsEntity, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_simple_content(node: &Node) -> RsEntity { let content = node diff --git a/xsd-parser/src/parser/simple_type.rs b/xsd-parser/src/parser/simple_type.rs index 1983d5f..b78ba7f 100644 --- a/xsd-parser/src/parser/simple_type.rs +++ b/xsd-parser/src/parser/simple_type.rs @@ -1,9 +1,11 @@ use roxmltree::Node; -use crate::parser::node_parser::parse_node; -use crate::parser::types::RsEntity; -use crate::parser::utils::get_documentation; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + node_parser::parse_node, + types::RsEntity, + utils::get_documentation, + xsd_elements::{ElementType, XsdNode}, +}; pub fn parse_simple_type(node: &Node, parent: &Node) -> RsEntity { let name = node.attr_name(); @@ -34,8 +36,7 @@ pub fn parse_simple_type(node: &Node, parent: &Node) -> RsEntity { #[cfg(test)] mod test { use super::*; - use crate::parser::types::TypeModifier; - use crate::parser::utils::find_child; + use crate::parser::{types::TypeModifier, utils::find_child}; #[test] fn test_parse_simple_type_with_list() { @@ -65,10 +66,7 @@ mod test { RsEntity::TupleStruct(ts) => { assert_eq!(ts.name, "SomeType"); assert_eq!(ts.type_name, "xs:SSD"); - assert_eq!( - ts.type_modifiers, - vec![TypeModifier::Array, TypeModifier::Array] - ); + assert_eq!(ts.type_modifiers, vec![TypeModifier::Array, TypeModifier::Array]); assert_eq!(ts.comment.unwrap().trim(), "Some text"); assert!(ts.subtypes.is_empty()); } diff --git a/xsd-parser/src/parser/tests.rs b/xsd-parser/src/parser/tests.rs index b9b61c9..acc0bd4 100644 --- a/xsd-parser/src/parser/tests.rs +++ b/xsd-parser/src/parser/tests.rs @@ -4,8 +4,7 @@ mod test { #[test] fn test_extension_base() { - use crate::parser::parse; - use crate::parser::types::RsEntity; + use crate::parser::{parse, types::RsEntity}; let text = r#" { pub name: String, @@ -37,10 +36,7 @@ impl Struct { } pub fn extend_base(&self, types: &HashMap<&String, &Self>) { - self.fields - .borrow_mut() - .iter_mut() - .for_each(|f| f.extend_base(types)); + self.fields.borrow_mut().iter_mut().for_each(|f| f.extend_base(types)); let mut fields = self .fields @@ -49,26 +45,17 @@ impl Struct { .filter(|f| f.name.as_str() == tag::BASE) .flat_map(|f| { let key = f.type_name.split(':').last().unwrap().to_string(); - types - .get(&key) - .map(|s| s.fields.borrow().clone()) - .unwrap_or_default() + types.get(&key).map(|s| s.fields.borrow().clone()).unwrap_or_default() }) .filter(|f| { //TODO: remove this workaround for fields names clash - !self - .fields - .borrow() - .iter() - .any(|field| field.name == f.name) + !self.fields.borrow().iter().any(|field| field.name == f.name) }) .collect::>(); self.fields.borrow_mut().append(&mut fields); - self.fields - .borrow_mut() - .retain(|field| field.name.as_str() != tag::BASE); + self.fields.borrow_mut().retain(|field| field.name.as_str() != tag::BASE); for subtype in &self.subtypes { if let RsEntity::Struct(s) = subtype { @@ -84,10 +71,7 @@ impl Struct { .iter() .flat_map(|f| { let key = f.original.split(':').last().unwrap().to_string(); - types - .get(&key) - .map(|s| s.fields.borrow().clone()) - .unwrap_or_default() + types.get(&key).map(|s| s.fields.borrow().clone()).unwrap_or_default() }) .collect::>(); diff --git a/xsd-parser/src/parser/union.rs b/xsd-parser/src/parser/union.rs index 011717e..4c47ff6 100644 --- a/xsd-parser/src/parser/union.rs +++ b/xsd-parser/src/parser/union.rs @@ -1,19 +1,18 @@ +use std::cell::RefCell; + use roxmltree::Node; -use crate::parser::constants::attribute; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{Enum, EnumCase, EnumSource, RsEntity, Struct}; -use crate::parser::utils::{ - attributes_to_fields, enum_to_field, get_documentation, get_parent_name, +use crate::parser::{ + constants::attribute, + node_parser::parse_node, + types::{Enum, EnumCase, EnumSource, RsEntity, Struct}, + utils::{attributes_to_fields, enum_to_field, get_documentation, get_parent_name}, + xsd_elements::{ElementType, XsdNode}, }; -use crate::parser::xsd_elements::{ElementType, XsdNode}; -use std::cell::RefCell; pub fn parse_union(union: &Node) -> RsEntity { - let mut cases = union - .attribute(attribute::MEMBER_TYPES) - .map(create_enum_cases) - .unwrap_or_default(); + let mut cases = + union.attribute(attribute::MEMBER_TYPES).map(create_enum_cases).unwrap_or_default(); let subtypes = union .children() @@ -51,10 +50,7 @@ pub fn parse_union(union: &Node) -> RsEntity { } else { union_enum.name = format!("{}Choice", get_parent_name(union)); fields.push(enum_to_field(union_enum)); - RsEntity::Struct(Struct { - fields: RefCell::new(fields), - ..Default::default() - }) + RsEntity::Struct(Struct { fields: RefCell::new(fields), ..Default::default() }) } } @@ -79,9 +75,11 @@ fn enum_subtype_from_node(node: &Node, parent: &Node, index: usize) -> RsEntity #[cfg(test)] mod test { - use crate::parser::types::RsEntity; - use crate::parser::union::{create_enum_cases, parse_union}; - use crate::parser::utils::find_child; + use crate::parser::{ + types::RsEntity, + union::{create_enum_cases, parse_union}, + utils::find_child, + }; #[test] fn test_create_enum() { diff --git a/xsd-parser/src/parser/utils.rs b/xsd-parser/src/parser/utils.rs index 2b9e4ac..4f35e01 100644 --- a/xsd-parser/src/parser/utils.rs +++ b/xsd-parser/src/parser/utils.rs @@ -2,21 +2,22 @@ use std::str; use roxmltree::{Namespace, Node}; -use crate::parser::constants::attribute; -use crate::parser::node_parser::parse_node; -use crate::parser::types::{Alias, Enum, RsEntity, StructField, StructFieldSource}; -use crate::parser::xsd_elements::{ElementType, XsdNode}; +use crate::parser::{ + constants::attribute, + node_parser::parse_node, + types::{Alias, Enum, RsEntity, StructField, StructFieldSource}, + xsd_elements::{ElementType, XsdNode}, +}; pub fn target_namespace<'a, 'input>(node: &Node<'a, 'input>) -> Option<&'a Namespace<'input>> { match node.attribute(attribute::TARGET_NAMESPACE) { - Some(tn) => node.namespaces().iter().find(|a| a.uri() == tn), + Some(tn) => node.namespaces().find(|a| a.uri() == tn), None => None, } } pub fn find_child<'a, 'input>(node: &Node<'a, 'input>, tag_name: &str) -> Option> { - node.children() - .find(|e| e.is_element() && e.tag_name().name() == tag_name) + node.children().find(|e| e.is_element() && e.tag_name().name() == tag_name) } pub fn get_documentation(node: &Node<'_, '_>) -> Option { @@ -42,8 +43,7 @@ pub fn get_parent_name<'a>(node: &Node<'a, '_>) -> &'a str { } pub fn get_base<'a>(node: &Node<'a, '_>) -> &'a str { - node.attribute(attribute::BASE) - .expect("The base value is required") + node.attribute(attribute::BASE).expect("The base value is required") } pub fn attributes_to_fields(node: &Node) -> Vec { diff --git a/xsd-parser/src/parser/xsd_elements.rs b/xsd-parser/src/parser/xsd_elements.rs index 1241ab7..bbeda21 100644 --- a/xsd-parser/src/parser/xsd_elements.rs +++ b/xsd-parser/src/parser/xsd_elements.rs @@ -211,20 +211,14 @@ pub enum MaxOccurs { } pub fn min_occurs(node: &roxmltree::Node) -> MinOccurs { - node.attribute(attribute::MIN_OCCURS) - .and_then(|v| v.parse::().ok()) - .unwrap_or(1) + node.attribute(attribute::MIN_OCCURS).and_then(|v| v.parse::().ok()).unwrap_or(1) } pub fn max_occurs(node: &roxmltree::Node) -> MaxOccurs { match node.attribute(attribute::MAX_OCCURS) { Some(s) => match s { "unbounded" => MaxOccurs::Unbounded, - s => s - .parse::() - .ok() - .map(MaxOccurs::Bounded) - .unwrap_or(MaxOccurs::None), + s => s.parse::().ok().map(MaxOccurs::Bounded).unwrap_or(MaxOccurs::None), }, None => MaxOccurs::None, } diff --git a/xsd-parser/tests/any/mod.rs b/xsd-parser/tests/any/mod.rs index 268031e..e151f6e 100644 --- a/xsd-parser/tests/any/mod.rs +++ b/xsd-parser/tests/any/mod.rs @@ -12,12 +12,7 @@ fn deserialization_works() { let de: expected::FooType = yaserde::de::from_str(ser).unwrap(); - assert_eq!( - de, - expected::FooType { - name: "abcd".to_string() - } - ); + assert_eq!(de, expected::FooType { name: "abcd".to_string() }); } #[test] diff --git a/xsd-parser/tests/choice/mod.rs b/xsd-parser/tests/choice/mod.rs index ced4ed7..9e307a6 100644 --- a/xsd-parser/tests/choice/mod.rs +++ b/xsd-parser/tests/choice/mod.rs @@ -4,6 +4,7 @@ use super::utils; fn deserialization_works() { mod expected { use std::str::FromStr; + use xsd_macro_utils::*; use yaserde_derive::{YaDeserialize, YaSerialize}; @@ -16,9 +17,7 @@ fn deserialization_works() { assert_eq!( de, - expected::FooType { - foo_type_choice: expected::FooTypeChoice::Baz(expected::BazType(3)) - } + expected::FooType { foo_type_choice: expected::FooTypeChoice::Baz(expected::BazType(3)) } ); } diff --git a/xsd-parser/tests/complex_type_subtypes_clash/mod.rs b/xsd-parser/tests/complex_type_subtypes_clash/mod.rs index 1b7c9cf..57586f0 100644 --- a/xsd-parser/tests/complex_type_subtypes_clash/mod.rs +++ b/xsd-parser/tests/complex_type_subtypes_clash/mod.rs @@ -13,12 +13,7 @@ fn deserialization_works() { let de: expected::FooType = yaserde::de::from_str(ser).unwrap(); - assert_eq!( - de, - expected::FooType { - extension: expected::foo_type::ExtensionType {} - } - ); + assert_eq!(de, expected::FooType { extension: expected::foo_type::ExtensionType {} }); } #[test] diff --git a/xsd-parser/tests/enumeration/mod.rs b/xsd-parser/tests/enumeration/mod.rs index 621762f..2829003 100644 --- a/xsd-parser/tests/enumeration/mod.rs +++ b/xsd-parser/tests/enumeration/mod.rs @@ -4,6 +4,7 @@ use super::utils; fn deserialization_works() { mod expected { use std::str::FromStr; + use xsd_macro_utils::*; use xsd_parser::generator::validator::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; diff --git a/xsd-parser/tests/extension_base/mod.rs b/xsd-parser/tests/extension_base/mod.rs index d556b71..8b3502f 100644 --- a/xsd-parser/tests/extension_base/mod.rs +++ b/xsd-parser/tests/extension_base/mod.rs @@ -13,14 +13,7 @@ fn deserialization_works() { let de: expected::FooType = yaserde::de::from_str(ser).unwrap(); - assert_eq!( - de, - expected::FooType { - a: 150.0, - b: 3, - c: "string".to_string(), - } - ); + assert_eq!(de, expected::FooType { a: 150.0, b: 3, c: "string".to_string() }); } #[test] diff --git a/xsd-parser/tests/extension_base_two_files/mod.rs b/xsd-parser/tests/extension_base_two_files/mod.rs index fae356a..7399568 100644 --- a/xsd-parser/tests/extension_base_two_files/mod.rs +++ b/xsd-parser/tests/extension_base_two_files/mod.rs @@ -11,14 +11,7 @@ fn deserialization_works() { let de: expected::FooType = yaserde::de::from_str(ser).unwrap(); - assert_eq!( - de, - expected::FooType { - a: 150.0, - b: 3, - c: "string".to_string(), - } - ); + assert_eq!(de, expected::FooType { a: 150.0, b: 3, c: "string".to_string() }); } #[test] diff --git a/xsd-parser/tests/ref_to_attribute/mod.rs b/xsd-parser/tests/ref_to_attribute/mod.rs index 378a2bf..4b1a851 100644 --- a/xsd-parser/tests/ref_to_attribute/mod.rs +++ b/xsd-parser/tests/ref_to_attribute/mod.rs @@ -4,6 +4,7 @@ use super::utils; fn deserialization_works() { mod expected { use std::str::FromStr; + use xsd_macro_utils::*; use xsd_parser::generator::validator::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; @@ -15,12 +16,7 @@ fn deserialization_works() { let de: expected::FooType = yaserde::de::from_str(ser).unwrap(); - assert_eq!( - de, - expected::FooType { - id: Some(expected::Id("abcd".to_string())) - } - ); + assert_eq!(de, expected::FooType { id: Some(expected::Id("abcd".to_string())) }); } #[test] diff --git a/xsd-parser/tests/simple_type/mod.rs b/xsd-parser/tests/simple_type/mod.rs index 8f3667d..a4843ee 100644 --- a/xsd-parser/tests/simple_type/mod.rs +++ b/xsd-parser/tests/simple_type/mod.rs @@ -4,6 +4,7 @@ use super::utils; fn deserialization_works() { mod expected { use std::str::FromStr; + use xsd_macro_utils::*; trait Validate { diff --git a/xsd-parser/tests/tuple_with_integer/mod.rs b/xsd-parser/tests/tuple_with_integer/mod.rs index a8a958c..7a88f83 100644 --- a/xsd-parser/tests/tuple_with_integer/mod.rs +++ b/xsd-parser/tests/tuple_with_integer/mod.rs @@ -1,11 +1,13 @@ -use super::utils; use num_bigint::ToBigInt; use xsd_types::types::Integer; +use super::utils; + #[test] fn deserialization_works() { mod expected { use std::str::FromStr; + use xsd_macro_utils::*; use xsd_types::types::Integer; @@ -16,10 +18,7 @@ fn deserialization_works() { let de: expected::FooType = yaserde::de::from_str(ser).unwrap(); - assert_eq!( - de, - expected::FooType(Integer::from_bigint(3.to_bigint().unwrap())) - ); + assert_eq!(de, expected::FooType(Integer::from_bigint(3.to_bigint().unwrap()))); } #[test] diff --git a/xsd-parser/tests/tuple_with_string/mod.rs b/xsd-parser/tests/tuple_with_string/mod.rs index 345c9e9..ef829ba 100644 --- a/xsd-parser/tests/tuple_with_string/mod.rs +++ b/xsd-parser/tests/tuple_with_string/mod.rs @@ -4,6 +4,7 @@ use super::utils; fn deserialization_works() { mod expected { use std::str::FromStr; + use xsd_macro_utils::*; include!("expected.rs"); diff --git a/xsd-parser/tests/tuple_with_vec/mod.rs b/xsd-parser/tests/tuple_with_vec/mod.rs index 4d9d82f..86f41c4 100644 --- a/xsd-parser/tests/tuple_with_vec/mod.rs +++ b/xsd-parser/tests/tuple_with_vec/mod.rs @@ -4,6 +4,7 @@ use super::utils; fn deserialization_works() { mod expected { use std::str::FromStr; + use xsd_macro_utils::*; include!("expected.rs"); diff --git a/xsd-parser/tests/utils.rs b/xsd-parser/tests/utils.rs index c9818a1..6447325 100644 --- a/xsd-parser/tests/utils.rs +++ b/xsd-parser/tests/utils.rs @@ -1,5 +1,4 @@ -use xsd_parser::generator::builder::GeneratorBuilder; -use xsd_parser::parser::parse; +use xsd_parser::{generator::builder::GeneratorBuilder, parser::parse}; pub fn generate(input: &str) -> String { let f = parse(input).unwrap(); diff --git a/xsd-parser/tests/xsd_string/mod.rs b/xsd-parser/tests/xsd_string/mod.rs index 3ce6a3d..77f7243 100644 --- a/xsd-parser/tests/xsd_string/mod.rs +++ b/xsd-parser/tests/xsd_string/mod.rs @@ -13,12 +13,7 @@ fn deserialization_works() { let de: expected::FooType = yaserde::de::from_str(ser).unwrap(); - assert_eq!( - de, - expected::FooType { - text: "abcd".to_string() - } - ); + assert_eq!(de, expected::FooType { text: "abcd".to_string() }); } #[test] diff --git a/xsd-types/src/types/date.rs b/xsd-types/src/types/date.rs index def40b4..34abc5b 100644 --- a/xsd-types/src/types/date.rs +++ b/xsd-types/src/types/date.rs @@ -1,9 +1,10 @@ -use crate::types::utils::parse_timezone; +use std::{fmt, str::FromStr}; + use chrono::{format::strftime::StrftimeItems, FixedOffset, NaiveDate}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; +use crate::types::utils::parse_timezone; + #[derive(PartialEq, Debug, UtilsDefaultSerde)] pub struct Date { pub value: NaiveDate, @@ -12,10 +13,7 @@ pub struct Date { impl Date { pub fn from_chrono_naive_date(date: NaiveDate) -> Self { - Date { - value: date, - timezone: None, - } + Date { value: date, timezone: None } } pub fn to_chrono_naive_date(&self) -> NaiveDate { @@ -25,10 +23,7 @@ impl Date { impl Default for Date { fn default() -> Date { - Self { - value: NaiveDate::from_ymd_opt(1, 1, 1).unwrap(), - timezone: None, - } + Self { value: NaiveDate::from_ymd_opt(1, 1, 1).unwrap(), timezone: None } } } @@ -71,10 +66,7 @@ impl FromStr for Date { }); } - Ok(Date { - value: parse_naive_date(s)?, - timezone: None, - }) + Ok(Date { value: parse_naive_date(s)?, timezone: None }) } } @@ -90,19 +82,17 @@ impl fmt::Display for Date { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn date_parse_test() { // No timezone. assert_eq!( Date::from_str("2020-02-02"), - Ok(Date { - value: NaiveDate::from_ymd_opt(2020, 2, 2).unwrap(), - timezone: None - }) + Ok(Date { value: NaiveDate::from_ymd_opt(2020, 2, 2).unwrap(), timezone: None }) ); // Timezone "Z". @@ -137,11 +127,8 @@ mod tests { fn date_display_test() { // No timezone. assert_eq!( - Date { - value: NaiveDate::from_ymd_opt(2020, 2, 2).unwrap(), - timezone: None - } - .to_string(), + Date { value: NaiveDate::from_ymd_opt(2020, 2, 2).unwrap(), timezone: None } + .to_string(), "2020-02-02" ); @@ -214,14 +201,8 @@ mod tests { "#; let m: Message = yaserde::de::from_str(s).unwrap(); - assert_eq!( - m.created_at.value, - NaiveDate::from_ymd_opt(2020, 2, 2).unwrap() - ); - assert_eq!( - m.created_at.timezone, - Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()), - ); + assert_eq!(m.created_at.value, NaiveDate::from_ymd_opt(2020, 2, 2).unwrap()); + assert_eq!(m.created_at.timezone, Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()),); assert_eq!(m.text, "Hello world".to_string()); } } diff --git a/xsd-types/src/types/datetime.rs b/xsd-types/src/types/datetime.rs index 643bfa8..75f7139 100644 --- a/xsd-types/src/types/datetime.rs +++ b/xsd-types/src/types/datetime.rs @@ -1,6 +1,6 @@ +use std::{fmt, str::FromStr}; + use chrono::{format::ParseError, DateTime as CDateTime, FixedOffset}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; #[derive(PartialEq, PartialOrd, Debug, UtilsDefaultSerde)] @@ -20,9 +20,7 @@ impl DateTime { impl Default for DateTime { fn default() -> DateTime { - Self { - value: CDateTime::parse_from_rfc3339("0001-01-01T00:00:00Z").unwrap(), - } + Self { value: CDateTime::parse_from_rfc3339("0001-01-01T00:00:00Z").unwrap() } } } @@ -36,11 +34,7 @@ impl FromStr for DateTime { // 'Z' (which equals "+00:00") in case there is no timezone provided. fn from_str(s: &str) -> Result { let tz_provided = s.ends_with('Z') || s.contains('+') || s.matches('-').count() == 3; - let s_with_timezone = if tz_provided { - s.to_string() - } else { - format!("{}Z", s) - }; + let s_with_timezone = if tz_provided { s.to_string() } else { format!("{}Z", s) }; match CDateTime::parse_from_rfc3339(&s_with_timezone) { Ok(cdt) => Ok(DateTime { value: cdt }), Err(err) => Err(err), @@ -56,98 +50,60 @@ impl fmt::Display for DateTime { #[cfg(test)] mod tests { - use super::*; - use crate::utils::xml_eq::assert_xml_eq; use chrono::NaiveDate; use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; + use crate::utils::xml_eq::assert_xml_eq; + #[test] fn datetime_parse_test() { // No timezone. let offset = FixedOffset::east_opt(0).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); - assert_eq!( - DateTime::from_str("2020-03-07T04:40:00"), - Ok(DateTime { value: dt }) - ); + assert_eq!(DateTime::from_str("2020-03-07T04:40:00"), Ok(DateTime { value: dt })); // Timezone "Z". - assert_eq!( - DateTime::from_str("2020-03-07T04:40:00Z"), - Ok(DateTime { value: dt }) - ); + assert_eq!(DateTime::from_str("2020-03-07T04:40:00Z"), Ok(DateTime { value: dt })); // Positive offset. let offset = FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); - assert_eq!( - DateTime::from_str("2020-03-07T04:40:00+06:30"), - Ok(DateTime { value: dt }) - ); + assert_eq!(DateTime::from_str("2020-03-07T04:40:00+06:30"), Ok(DateTime { value: dt })); // Negative offset. let offset = FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); - assert_eq!( - DateTime::from_str("2020-03-07T04:40:00-06:30"), - Ok(DateTime { value: dt }) - ); + assert_eq!(DateTime::from_str("2020-03-07T04:40:00-06:30"), Ok(DateTime { value: dt })); } #[test] fn datetime_display_test() { // Timezone +00:00. let offset = FixedOffset::east_opt(0).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); - assert_eq!( - DateTime { value: dt }.to_string(), - "2020-03-07T04:40:00+00:00" - ); + assert_eq!(DateTime { value: dt }.to_string(), "2020-03-07T04:40:00+00:00"); // Positive offset. let offset = FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); - assert_eq!( - DateTime { value: dt }.to_string(), - "2020-03-07T04:40:00+06:30" - ); + assert_eq!(DateTime { value: dt }.to_string(), "2020-03-07T04:40:00+06:30"); // Negative offset. let offset = FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); - assert_eq!( - DateTime { value: dt }.to_string(), - "2020-03-07T04:40:00-06:30" - ); + assert_eq!(DateTime { value: dt }.to_string(), "2020-03-07T04:40:00-06:30"); } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] @@ -170,16 +126,10 @@ mod tests { "#; let offset = FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); - let m = Message { - created_at: DateTime { value: dt }, - text: "Hello world".to_string(), - }; + let m = Message { created_at: DateTime { value: dt }, text: "Hello world".to_string() }; let actual = yaserde::ser::to_string(&m).unwrap(); assert_xml_eq(&actual, expected); } @@ -195,11 +145,8 @@ mod tests { let m: Message = yaserde::de::from_str(s).unwrap(); let offset = FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); assert_eq!(m.created_at.value, dt); diff --git a/xsd-types/src/types/datetimestamp.rs b/xsd-types/src/types/datetimestamp.rs index e853f81..167d7c4 100644 --- a/xsd-types/src/types/datetimestamp.rs +++ b/xsd-types/src/types/datetimestamp.rs @@ -1,9 +1,10 @@ -use crate::types::datetime::DateTime; +use std::{fmt, str::FromStr}; + use chrono::{format::ParseError, DateTime as CDateTime, FixedOffset}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; +use crate::types::datetime::DateTime; + // The only difference from DateTime is that the time zone expression is required at the end of the value. #[derive(Default, PartialEq, PartialOrd, Debug, UtilsDefaultSerde)] pub struct DateTimeStamp { @@ -12,9 +13,7 @@ pub struct DateTimeStamp { impl DateTimeStamp { pub fn from_chrono_datetime(datetime: CDateTime) -> Self { - DateTimeStamp { - value: DateTime::from_chrono_datetime(datetime), - } + DateTimeStamp { value: DateTime::from_chrono_datetime(datetime) } } pub fn to_chrono_datetime(&self) -> CDateTime { @@ -41,20 +40,18 @@ impl fmt::Display for DateTimeStamp { #[cfg(test)] mod tests { - use super::*; - use crate::utils::xml_eq::assert_xml_eq; use chrono::NaiveDate; use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; + use crate::utils::xml_eq::assert_xml_eq; + #[test] fn datetime_parse_test() { // No timezone. let offset = FixedOffset::east_opt(0).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); assert!(DateTimeStamp::from_str("2020-03-07T04:40:00").is_err()); // Timezone "Z". @@ -65,11 +62,8 @@ mod tests { // Positive offset. let offset = FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); assert_eq!( DateTimeStamp::from_str("2020-03-07T04:40:00+06:30"), @@ -78,11 +72,8 @@ mod tests { // Negative offset. let offset = FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); assert_eq!( DateTimeStamp::from_str("2020-03-07T04:40:00-06:30"), @@ -94,11 +85,8 @@ mod tests { fn datetime_display_test() { // Timezone +00:00. let offset = FixedOffset::east_opt(0).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); assert_eq!( DateTimeStamp::from_chrono_datetime(dt).to_string(), @@ -107,11 +95,8 @@ mod tests { // Positive offset. let offset = FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); assert_eq!( DateTimeStamp::from_chrono_datetime(dt).to_string(), @@ -120,11 +105,8 @@ mod tests { // Negative offset. let offset = FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); assert_eq!( DateTimeStamp::from_chrono_datetime(dt).to_string(), @@ -152,11 +134,8 @@ mod tests { "#; let offset = FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); let m = Message { created_at: DateTimeStamp::from_chrono_datetime(dt), @@ -177,11 +156,8 @@ mod tests { let m: Message = yaserde::de::from_str(s).unwrap(); let offset = FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap(); - let dt_utc = NaiveDate::from_ymd_opt(2020, 3, 7) - .unwrap() - .and_hms_opt(4, 40, 0) - .unwrap() - - offset; + let dt_utc = + NaiveDate::from_ymd_opt(2020, 3, 7).unwrap().and_hms_opt(4, 40, 0).unwrap() - offset; let dt = CDateTime::::from_naive_utc_and_offset(dt_utc, offset); assert_eq!(m.created_at.value, DateTime::from_chrono_datetime(dt)); diff --git a/xsd-types/src/types/decimal.rs b/xsd-types/src/types/decimal.rs index d98347b..b28b2da 100644 --- a/xsd-types/src/types/decimal.rs +++ b/xsd-types/src/types/decimal.rs @@ -1,6 +1,6 @@ +use std::{fmt, str::FromStr}; + use bigdecimal::{BigDecimal, ParseBigDecimalError}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; #[derive(Default, PartialEq, PartialOrd, Debug, UtilsDefaultSerde)] @@ -32,11 +32,12 @@ impl fmt::Display for Decimal { #[cfg(test)] mod tests { - use super::*; - use crate::utils::xml_eq::assert_xml_eq; use num_bigint::ToBigInt; use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; + use crate::utils::xml_eq::assert_xml_eq; + #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "t", namespace = "t: test")] pub struct DecimalPair { @@ -73,13 +74,7 @@ mod tests { "#; let i: DecimalPair = yaserde::de::from_str(s).unwrap(); - assert_eq!( - i.first.to_bigdecimal(), - BigDecimal::new(1234.to_bigint().unwrap(), 5) - ); - assert_eq!( - i.second.to_bigdecimal(), - BigDecimal::new((-1234).to_bigint().unwrap(), 2) - ); + assert_eq!(i.first.to_bigdecimal(), BigDecimal::new(1234.to_bigint().unwrap(), 5)); + assert_eq!(i.second.to_bigdecimal(), BigDecimal::new((-1234).to_bigint().unwrap(), 2)); } } diff --git a/xsd-types/src/types/duration.rs b/xsd-types/src/types/duration.rs index 575807f..8ff29a2 100644 --- a/xsd-types/src/types/duration.rs +++ b/xsd-types/src/types/duration.rs @@ -1,6 +1,5 @@ -use std::fmt; -use std::fmt::Write; -use std::str::FromStr; +use std::{fmt, fmt::Write, str::FromStr}; + use xsd_macro_utils::UtilsDefaultSerde; #[derive(Default, PartialEq, PartialOrd, Debug, UtilsDefaultSerde)] @@ -208,11 +207,7 @@ impl FromStr for Duration { impl fmt::Display for Duration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut s = if self.is_negative { - "-P".to_string() - } else { - "P".to_string() - }; + let mut s = if self.is_negative { "-P".to_string() } else { "P".to_string() }; let mut date_str = String::new(); if self.years > 0 { diff --git a/xsd-types/src/types/gday.rs b/xsd-types/src/types/gday.rs index 6656410..e92c9c5 100644 --- a/xsd-types/src/types/gday.rs +++ b/xsd-types/src/types/gday.rs @@ -1,10 +1,10 @@ -use crate::types::utils::parse_timezone; +use std::{fmt, str::FromStr}; use chrono::FixedOffset; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; +use crate::types::utils::parse_timezone; + #[derive(PartialEq, Debug, UtilsDefaultSerde)] pub struct GDay { pub value: i32, @@ -16,19 +16,13 @@ impl GDay { if !(1..=31).contains(&day) { return Err("gDay value should lie between 1 and 31".to_string()); } - Ok(GDay { - value: day, - timezone, - }) + Ok(GDay { value: day, timezone }) } } impl Default for GDay { fn default() -> GDay { - Self { - value: 1, - timezone: None, - } + Self { value: 1, timezone: None } } } @@ -84,28 +78,20 @@ impl fmt::Display for GDay { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn gday_parse_test() { // No timezone. - assert_eq!( - GDay::from_str("---25"), - Ok(GDay { - value: 25, - timezone: None - }) - ); + assert_eq!(GDay::from_str("---25"), Ok(GDay { value: 25, timezone: None })); // Timezone "Z". assert_eq!( GDay::from_str("---25Z"), - Ok(GDay { - value: 25, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - }) + Ok(GDay { value: 25, timezone: Some(FixedOffset::east_opt(0).unwrap()) }) ); // Positive offset. @@ -139,42 +125,25 @@ mod tests { #[test] fn gday_display_test() { // No timezone. - assert_eq!( - GDay { - value: 3, - timezone: None - } - .to_string(), - "---03" - ); + assert_eq!(GDay { value: 3, timezone: None }.to_string(), "---03"); // Timezone +00:00. assert_eq!( - GDay { - value: 3, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - } - .to_string(), + GDay { value: 3, timezone: Some(FixedOffset::east_opt(0).unwrap()) }.to_string(), "---03+00:00" ); // Positive offset. assert_eq!( - GDay { - value: 3, - timezone: Some(FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap()) - } - .to_string(), + GDay { value: 3, timezone: Some(FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap()) } + .to_string(), "---03+06:30" ); // Negative offset. assert_eq!( - GDay { - value: 3, - timezone: Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()) - } - .to_string(), + GDay { value: 3, timezone: Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()) } + .to_string(), "---03-06:30" ); } @@ -218,10 +187,7 @@ mod tests { "#; let m: Message = yaserde::de::from_str(s).unwrap(); assert_eq!(m.created_at.value, 29); - assert_eq!( - m.created_at.timezone, - Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()), - ); + assert_eq!(m.created_at.timezone, Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()),); assert_eq!(m.text, "Hello world".to_string()); } } diff --git a/xsd-types/src/types/gmonth.rs b/xsd-types/src/types/gmonth.rs index 9745bcf..73008fb 100644 --- a/xsd-types/src/types/gmonth.rs +++ b/xsd-types/src/types/gmonth.rs @@ -1,10 +1,10 @@ -use crate::types::utils::parse_timezone; +use std::{fmt, str::FromStr}; use chrono::FixedOffset; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; +use crate::types::utils::parse_timezone; + #[derive(PartialEq, Debug, UtilsDefaultSerde)] pub struct GMonth { pub value: i32, @@ -16,19 +16,13 @@ impl GMonth { if !(1..=12).contains(&month) { return Err("GMonth value should lie between 1 and 12".to_string()); } - Ok(GMonth { - value: month, - timezone, - }) + Ok(GMonth { value: month, timezone }) } } impl Default for GMonth { fn default() -> GMonth { - Self { - value: 1, - timezone: None, - } + Self { value: 1, timezone: None } } } @@ -84,28 +78,20 @@ impl fmt::Display for GMonth { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn gmonth_parse_test() { // No timezone. - assert_eq!( - GMonth::from_str("--12"), - Ok(GMonth { - value: 12, - timezone: None - }) - ); + assert_eq!(GMonth::from_str("--12"), Ok(GMonth { value: 12, timezone: None })); // Timezone "Z". assert_eq!( GMonth::from_str("--12Z"), - Ok(GMonth { - value: 12, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - }) + Ok(GMonth { value: 12, timezone: Some(FixedOffset::east_opt(0).unwrap()) }) ); // Positive offset. @@ -139,42 +125,25 @@ mod tests { #[test] fn gmonth_display_test() { // No timezone. - assert_eq!( - GMonth { - value: 3, - timezone: None - } - .to_string(), - "--03" - ); + assert_eq!(GMonth { value: 3, timezone: None }.to_string(), "--03"); // Timezone +00:00. assert_eq!( - GMonth { - value: 3, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - } - .to_string(), + GMonth { value: 3, timezone: Some(FixedOffset::east_opt(0).unwrap()) }.to_string(), "--03+00:00" ); // Positive offset. assert_eq!( - GMonth { - value: 3, - timezone: Some(FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap()) - } - .to_string(), + GMonth { value: 3, timezone: Some(FixedOffset::east_opt(6 * 3600 + 30 * 60).unwrap()) } + .to_string(), "--03+06:30" ); // Negative offset. assert_eq!( - GMonth { - value: 3, - timezone: Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()) - } - .to_string(), + GMonth { value: 3, timezone: Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()) } + .to_string(), "--03-06:30" ); } @@ -218,10 +187,7 @@ mod tests { "#; let m: Message = yaserde::de::from_str(s).unwrap(); assert_eq!(m.created_at.value, 9); - assert_eq!( - m.created_at.timezone, - Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()), - ); + assert_eq!(m.created_at.timezone, Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()),); assert_eq!(m.text, "Hello world".to_string()); } } diff --git a/xsd-types/src/types/gmonthday.rs b/xsd-types/src/types/gmonthday.rs index b72a307..cf1c70a 100644 --- a/xsd-types/src/types/gmonthday.rs +++ b/xsd-types/src/types/gmonthday.rs @@ -1,12 +1,10 @@ -use crate::types::gday::GDay; -use crate::types::gmonth::GMonth; -use crate::types::utils::parse_timezone; +use std::{fmt, str::FromStr}; use chrono::FixedOffset; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; +use crate::types::{gday::GDay, gmonth::GMonth, utils::parse_timezone}; + #[derive(PartialEq, Debug, UtilsDefaultSerde)] pub struct GMonthDay { pub month: i32, @@ -29,35 +27,21 @@ impl GMonthDay { return Err("Day value within GMonthDay is to big for specified month".to_string()); } - Ok(GMonthDay { - month, - day, - timezone, - }) + Ok(GMonthDay { month, day, timezone }) } pub fn gmonth(self) -> GMonth { - GMonth { - value: self.month, - timezone: self.timezone, - } + GMonth { value: self.month, timezone: self.timezone } } pub fn gday(self) -> GDay { - GDay { - value: self.day, - timezone: self.timezone, - } + GDay { value: self.day, timezone: self.timezone } } } impl Default for GMonthDay { fn default() -> GMonthDay { - Self { - month: 1, - day: 1, - timezone: None, - } + Self { month: 1, day: 1, timezone: None } } } @@ -126,30 +110,23 @@ impl fmt::Display for GMonthDay { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn gmonthday_parse_test() { // No timezone. assert_eq!( GMonthDay::from_str("--12-20"), - Ok(GMonthDay { - month: 12, - day: 20, - timezone: None - }) + Ok(GMonthDay { month: 12, day: 20, timezone: None }) ); // Timezone "Z". assert_eq!( GMonthDay::from_str("--12-20Z"), - Ok(GMonthDay { - month: 12, - day: 20, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - }) + Ok(GMonthDay { month: 12, day: 20, timezone: Some(FixedOffset::east_opt(0).unwrap()) }) ); // Positive offset. @@ -190,24 +167,12 @@ mod tests { #[test] fn gmonthday_display_test() { // No timezone. - assert_eq!( - GMonthDay { - month: 3, - day: 2, - timezone: None - } - .to_string(), - "--03-02" - ); + assert_eq!(GMonthDay { month: 3, day: 2, timezone: None }.to_string(), "--03-02"); // Timezone +00:00. assert_eq!( - GMonthDay { - month: 3, - day: 2, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - } - .to_string(), + GMonthDay { month: 3, day: 2, timezone: Some(FixedOffset::east_opt(0).unwrap()) } + .to_string(), "--03-02+00:00" ); @@ -275,10 +240,7 @@ mod tests { let m: Message = yaserde::de::from_str(s).unwrap(); assert_eq!(m.created_at.month, 7); assert_eq!(m.created_at.day, 9); - assert_eq!( - m.created_at.timezone, - Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()), - ); + assert_eq!(m.created_at.timezone, Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()),); assert_eq!(m.text, "Hello world".to_string()); } } diff --git a/xsd-types/src/types/gyear.rs b/xsd-types/src/types/gyear.rs index b75a2f1..d347513 100644 --- a/xsd-types/src/types/gyear.rs +++ b/xsd-types/src/types/gyear.rs @@ -1,9 +1,10 @@ -use crate::types::utils::parse_timezone; +use std::{fmt, str::FromStr}; + use chrono::FixedOffset; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; +use crate::types::utils::parse_timezone; + #[derive(PartialEq, Debug, UtilsDefaultSerde)] pub struct GYear { pub value: i32, @@ -15,19 +16,13 @@ impl GYear { if year == 0 { return Err("bad gYear format: year 0 occurred".to_string()); } - Ok(GYear { - value: year, - timezone, - }) + Ok(GYear { value: year, timezone }) } } impl Default for GYear { fn default() -> GYear { - Self { - value: 1, - timezone: None, - } + Self { value: 1, timezone: None } } } @@ -102,28 +97,20 @@ impl fmt::Display for GYear { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn gyear_parse_test() { // No timezone. - assert_eq!( - GYear::from_str("2020"), - Ok(GYear { - value: 2020, - timezone: None - }) - ); + assert_eq!(GYear::from_str("2020"), Ok(GYear { value: 2020, timezone: None })); // Timezone "Z". assert_eq!( GYear::from_str("2020Z"), - Ok(GYear { - value: 2020, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - }) + Ok(GYear { value: 2020, timezone: Some(FixedOffset::east_opt(0).unwrap()) }) ); // Positive offset. @@ -172,22 +159,11 @@ mod tests { #[test] fn gyear_display_test() { // No timezone. - assert_eq!( - GYear { - value: 987, - timezone: None - } - .to_string(), - "0987" - ); + assert_eq!(GYear { value: 987, timezone: None }.to_string(), "0987"); // Timezone +00:00. assert_eq!( - GYear { - value: 987, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - } - .to_string(), + GYear { value: 987, timezone: Some(FixedOffset::east_opt(0).unwrap()) }.to_string(), "0987+00:00" ); @@ -271,10 +247,7 @@ mod tests { "#; let m: Message = yaserde::de::from_str(s).unwrap(); assert_eq!(m.created_at.value, 2007); - assert_eq!( - m.created_at.timezone, - Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()), - ); + assert_eq!(m.created_at.timezone, Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()),); assert_eq!(m.text, "Hello world".to_string()); } } diff --git a/xsd-types/src/types/gyearmonth.rs b/xsd-types/src/types/gyearmonth.rs index 8056c69..b919d76 100644 --- a/xsd-types/src/types/gyearmonth.rs +++ b/xsd-types/src/types/gyearmonth.rs @@ -1,12 +1,10 @@ -use crate::types::gmonth::GMonth; -use crate::types::gyear::GYear; -use crate::types::utils::parse_timezone; +use std::{fmt, str::FromStr}; use chrono::FixedOffset; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; +use crate::types::{gmonth::GMonth, gyear::GYear, utils::parse_timezone}; + #[derive(PartialEq, Debug, UtilsDefaultSerde)] pub struct GYearMonth { pub year: i32, @@ -24,35 +22,21 @@ impl GYearMonth { return Err("Month value within GYearMonth should lie between 1 and 12".to_string()); } - Ok(GYearMonth { - year, - month, - timezone, - }) + Ok(GYearMonth { year, month, timezone }) } pub fn gyear(self) -> GYear { - GYear { - value: self.year, - timezone: self.timezone, - } + GYear { value: self.year, timezone: self.timezone } } pub fn gmonth(self) -> GMonth { - GMonth { - value: self.month, - timezone: self.timezone, - } + GMonth { value: self.month, timezone: self.timezone } } } impl Default for GYearMonth { fn default() -> GYearMonth { - Self { - year: 1, - month: 1, - timezone: None, - } + Self { year: 1, month: 1, timezone: None } } } @@ -142,20 +126,17 @@ impl fmt::Display for GYearMonth { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn gyearmonth_parse_test() { // No timezone. assert_eq!( GYearMonth::from_str("2020-03"), - Ok(GYearMonth { - year: 2020, - month: 3, - timezone: None - }) + Ok(GYearMonth { year: 2020, month: 3, timezone: None }) ); // Timezone "Z". @@ -223,24 +204,12 @@ mod tests { #[test] fn gyearmonth_display_test() { // No timezone. - assert_eq!( - GYearMonth { - year: 987, - month: 6, - timezone: None - } - .to_string(), - "0987-06" - ); + assert_eq!(GYearMonth { year: 987, month: 6, timezone: None }.to_string(), "0987-06"); // Timezone +00:00. assert_eq!( - GYearMonth { - year: 987, - month: 6, - timezone: Some(FixedOffset::east_opt(0).unwrap()) - } - .to_string(), + GYearMonth { year: 987, month: 6, timezone: Some(FixedOffset::east_opt(0).unwrap()) } + .to_string(), "0987-06+00:00" ); @@ -330,10 +299,7 @@ mod tests { let m: Message = yaserde::de::from_str(s).unwrap(); assert_eq!(m.created_at.year, 2007); assert_eq!(m.created_at.month, 2); - assert_eq!( - m.created_at.timezone, - Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()), - ); + assert_eq!(m.created_at.timezone, Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()),); assert_eq!(m.text, "Hello world".to_string()); } } diff --git a/xsd-types/src/types/integer.rs b/xsd-types/src/types/integer.rs index 3638d0c..e26ed50 100644 --- a/xsd-types/src/types/integer.rs +++ b/xsd-types/src/types/integer.rs @@ -1,6 +1,6 @@ +use std::{fmt, str::FromStr}; + use num_bigint::{BigInt, ParseBigIntError, ToBigInt}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; // https://www.w3.org/TR/xmlschema-2/#integer @@ -35,9 +35,10 @@ impl fmt::Display for Integer { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn integer_parse_test() { @@ -46,17 +47,11 @@ mod tests { Ok(Integer(BigInt::from_str("12678967543233").unwrap())) ); - assert_eq!( - Integer::from_str("+100000"), - Ok(Integer(100000.to_bigint().unwrap())) - ); + assert_eq!(Integer::from_str("+100000"), Ok(Integer(100000.to_bigint().unwrap()))); assert_eq!(Integer::from_str("0"), Ok(Integer(0.to_bigint().unwrap()))); - assert_eq!( - Integer::from_str("-1"), - Ok(Integer((-1).to_bigint().unwrap())) - ); + assert_eq!(Integer::from_str("-1"), Ok(Integer((-1).to_bigint().unwrap()))); // Invalid values. assert!(Integer::from_str("A").is_err()); diff --git a/xsd-types/src/types/negative_integer.rs b/xsd-types/src/types/negative_integer.rs index 59961f1..f9b79a1 100644 --- a/xsd-types/src/types/negative_integer.rs +++ b/xsd-types/src/types/negative_integer.rs @@ -1,6 +1,6 @@ +use std::{fmt, str::FromStr}; + use num_bigint::{BigInt, ToBigInt}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; // https://www.w3.org/TR/xmlschema-2/#negativeInteger @@ -40,17 +40,16 @@ impl fmt::Display for NegativeInteger { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn negative_integer_parse_test() { assert_eq!( NegativeInteger::from_str("-12678967543233"), - Ok(NegativeInteger( - BigInt::from_str("-12678967543233").unwrap() - )) + Ok(NegativeInteger(BigInt::from_str("-12678967543233").unwrap())) ); assert_eq!( @@ -58,10 +57,7 @@ mod tests { Ok(NegativeInteger((-100000).to_bigint().unwrap())) ); - assert_eq!( - NegativeInteger::from_str("-1"), - Ok(NegativeInteger((-1).to_bigint().unwrap())) - ); + assert_eq!(NegativeInteger::from_str("-1"), Ok(NegativeInteger((-1).to_bigint().unwrap()))); // Invalid values. assert!(NegativeInteger::from_str("0").is_err()); @@ -82,10 +78,7 @@ mod tests { "-12678967543233" ); - assert_eq!( - NegativeInteger((-100000).to_bigint().unwrap()).to_string(), - "-100000" - ); + assert_eq!(NegativeInteger((-100000).to_bigint().unwrap()).to_string(), "-100000"); assert_eq!(NegativeInteger((-1).to_bigint().unwrap()).to_string(), "-1"); } diff --git a/xsd-types/src/types/non_negative_integer.rs b/xsd-types/src/types/non_negative_integer.rs index d53f79a..58c4161 100644 --- a/xsd-types/src/types/non_negative_integer.rs +++ b/xsd-types/src/types/non_negative_integer.rs @@ -1,6 +1,6 @@ +use std::{fmt, str::FromStr}; + use num_bigint::{BigUint, ToBigUint}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; // https://www.w3.org/TR/xmlschema-2/#nonNegativeInteger @@ -40,17 +40,16 @@ impl fmt::Display for NonNegativeInteger { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn non_negative_integer_parse_test() { assert_eq!( NonNegativeInteger::from_str("12678967543233"), - Ok(NonNegativeInteger( - BigUint::from_str("12678967543233").unwrap() - )) + Ok(NonNegativeInteger(BigUint::from_str("12678967543233").unwrap())) ); assert_eq!( @@ -79,10 +78,7 @@ mod tests { "12678967543233" ); - assert_eq!( - NonNegativeInteger(100000.to_biguint().unwrap()).to_string(), - "100000" - ); + assert_eq!(NonNegativeInteger(100000.to_biguint().unwrap()).to_string(), "100000"); assert_eq!(NonNegativeInteger(0.to_biguint().unwrap()).to_string(), "0"); } diff --git a/xsd-types/src/types/non_positive_integer.rs b/xsd-types/src/types/non_positive_integer.rs index 134e3d8..3fd1ada 100644 --- a/xsd-types/src/types/non_positive_integer.rs +++ b/xsd-types/src/types/non_positive_integer.rs @@ -1,6 +1,6 @@ +use std::{fmt, str::FromStr}; + use num_bigint::{BigInt, ToBigInt}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; // https://www.w3.org/TR/xmlschema-2/#nonPositiveInteger @@ -40,17 +40,16 @@ impl fmt::Display for NonPositiveInteger { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn non_positive_integer_parse_test() { assert_eq!( NonPositiveInteger::from_str("-12678967543233"), - Ok(NonPositiveInteger( - BigInt::from_str("-12678967543233").unwrap() - )) + Ok(NonPositiveInteger(BigInt::from_str("-12678967543233").unwrap())) ); assert_eq!( @@ -84,17 +83,11 @@ mod tests { "-12678967543233" ); - assert_eq!( - NonPositiveInteger((-100000).to_bigint().unwrap()).to_string(), - "-100000" - ); + assert_eq!(NonPositiveInteger((-100000).to_bigint().unwrap()).to_string(), "-100000"); assert_eq!(NonPositiveInteger(0.to_bigint().unwrap()).to_string(), "0"); - assert_eq!( - NonPositiveInteger((-1).to_bigint().unwrap()).to_string(), - "-1" - ); + assert_eq!(NonPositiveInteger((-1).to_bigint().unwrap()).to_string(), "-1"); } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] diff --git a/xsd-types/src/types/positive_integer.rs b/xsd-types/src/types/positive_integer.rs index d91f21e..c516415 100644 --- a/xsd-types/src/types/positive_integer.rs +++ b/xsd-types/src/types/positive_integer.rs @@ -1,6 +1,6 @@ +use std::{fmt, str::FromStr}; + use num_bigint::{BigUint, ToBigUint}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; // https://www.w3.org/TR/xmlschema-2/#positiveInteger @@ -40,17 +40,16 @@ impl fmt::Display for PositiveInteger { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn positive_integer_parse_test() { assert_eq!( PositiveInteger::from_str("12678967543233"), - Ok(PositiveInteger( - BigUint::from_str("12678967543233").unwrap() - )) + Ok(PositiveInteger(BigUint::from_str("12678967543233").unwrap())) ); assert_eq!( @@ -77,10 +76,7 @@ mod tests { "12678967543233" ); - assert_eq!( - PositiveInteger(100000.to_biguint().unwrap()).to_string(), - "100000" - ); + assert_eq!(PositiveInteger(100000.to_biguint().unwrap()).to_string(), "100000"); } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] diff --git a/xsd-types/src/types/time.rs b/xsd-types/src/types/time.rs index 3ab6f53..f752b0f 100644 --- a/xsd-types/src/types/time.rs +++ b/xsd-types/src/types/time.rs @@ -1,9 +1,10 @@ -use crate::types::utils::parse_timezone; +use std::{fmt, str::FromStr}; + use chrono::{format::strftime::StrftimeItems, FixedOffset, NaiveTime}; -use std::fmt; -use std::str::FromStr; use xsd_macro_utils::UtilsDefaultSerde; +use crate::types::utils::parse_timezone; + #[derive(PartialEq, Debug, UtilsDefaultSerde)] pub struct Time { pub value: NaiveTime, @@ -12,10 +13,7 @@ pub struct Time { impl Time { pub fn from_chrono_naive_time(time: NaiveTime) -> Self { - Time { - value: time, - timezone: None, - } + Time { value: time, timezone: None } } pub fn to_chrono_naive_time(&self) -> NaiveTime { @@ -25,10 +23,7 @@ impl Time { impl Default for Time { fn default() -> Time { - Self { - value: NaiveTime::from_hms_opt(0, 0, 0).unwrap(), - timezone: None, - } + Self { value: NaiveTime::from_hms_opt(0, 0, 0).unwrap(), timezone: None } } } @@ -75,10 +70,7 @@ impl FromStr for Time { }); } - Ok(Time { - value: parse_naive_time(s)?, - timezone: None, - }) + Ok(Time { value: parse_naive_time(s)?, timezone: None }) } } @@ -94,19 +86,17 @@ impl fmt::Display for Time { #[cfg(test)] mod tests { + use yaserde_derive::{YaDeserialize, YaSerialize}; + use super::*; use crate::utils::xml_eq::assert_xml_eq; - use yaserde_derive::{YaDeserialize, YaSerialize}; #[test] fn time_parse_test() { // No timezone. assert_eq!( Time::from_str("04:40:00"), - Ok(Time { - value: NaiveTime::from_hms_opt(4, 40, 0).unwrap(), - timezone: None - }) + Ok(Time { value: NaiveTime::from_hms_opt(4, 40, 0).unwrap(), timezone: None }) ); // Timezone "Z". @@ -141,11 +131,7 @@ mod tests { fn time_display_test() { // No timezone. assert_eq!( - Time { - value: NaiveTime::from_hms_opt(4, 40, 0).unwrap(), - timezone: None - } - .to_string(), + Time { value: NaiveTime::from_hms_opt(4, 40, 0).unwrap(), timezone: None }.to_string(), "04:40:00" ); @@ -218,14 +204,8 @@ mod tests { "#; let m: Message = yaserde::de::from_str(s).unwrap(); - assert_eq!( - m.created_at.value, - NaiveTime::from_hms_opt(4, 40, 0).unwrap() - ); - assert_eq!( - m.created_at.timezone, - Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap()) - ); + assert_eq!(m.created_at.value, NaiveTime::from_hms_opt(4, 40, 0).unwrap()); + assert_eq!(m.created_at.timezone, Some(FixedOffset::west_opt(6 * 3600 + 30 * 60).unwrap())); assert_eq!(m.text, "Hello world".to_string()); } } diff --git a/xsd-types/src/types/utils.rs b/xsd-types/src/types/utils.rs index 4a3a75c..bb4dc88 100644 --- a/xsd-types/src/types/utils.rs +++ b/xsd-types/src/types/utils.rs @@ -51,16 +51,10 @@ mod tests { ); // Positive offset max. - assert_eq!( - parse_timezone("+14:00"), - Ok(FixedOffset::east_opt(14 * 3600).unwrap()) - ); + assert_eq!(parse_timezone("+14:00"), Ok(FixedOffset::east_opt(14 * 3600).unwrap())); // Negative offset max. - assert_eq!( - parse_timezone("-14:00"), - Ok(FixedOffset::west_opt(14 * 3600).unwrap()) - ); + assert_eq!(parse_timezone("-14:00"), Ok(FixedOffset::west_opt(14 * 3600).unwrap())); // Invalid values. assert!(parse_timezone("06:30").is_err()); diff --git a/xsd-types/src/utils/yaserde.rs b/xsd-types/src/utils/yaserde.rs index 96bedad..6af7592 100644 --- a/xsd-types/src/utils/yaserde.rs +++ b/xsd-types/src/utils/yaserde.rs @@ -1,4 +1,5 @@ use std::io::{Read, Write}; + use yaserde::{de, ser}; pub fn serialize( @@ -7,9 +8,7 @@ pub fn serialize( writer: &mut ser::Serializer, ser_fn: impl FnOnce(&S) -> String, ) -> Result<(), String> { - let name = writer - .get_start_event_name() - .unwrap_or_else(|| default_name.to_string()); + let name = writer.get_start_event_name().unwrap_or_else(|| default_name.to_string()); if !writer.skip_start_end() { writer @@ -18,9 +17,7 @@ pub fn serialize( } writer - .write(xml::writer::XmlEvent::characters( - ser_fn(self_bypass).as_str(), - )) + .write(xml::writer::XmlEvent::characters(ser_fn(self_bypass).as_str())) .map_err(|_e| "Element value write failed".to_string())?; if !writer.skip_start_end() {