sval-2.6.1/.cargo_vcs_info.json0000644000000001360000000000100120070ustar { "git": { "sha1": "3cbda0f19ac37260b44f16233944529f04666e05" }, "path_in_vcs": "" }sval-2.6.1/.github/workflows/buffer.yml000064400000000000000000000027271046102023000162000ustar 00000000000000name: buffer on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./buffer run: cargo hack test --feature-powerset bench: name: Bench runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./buffer run: cargo hack bench --feature-powerset --no-run embedded: name: Build (embedded) runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: | rustup default nightly rustup target add thumbv6m-none-eabi - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./buffer run: cargo hack check --each-feature --exclude-features std,alloc -Z avoid-dev-deps --target thumbv6m-none-eabi sval-2.6.1/.github/workflows/derive.yml000064400000000000000000000011551046102023000161770ustar 00000000000000name: derive on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./derive run: cargo hack test --feature-powerset - name: Powerset (Tests) working-directory: ./derive/test run: cargo hack test --feature-powerset sval-2.6.1/.github/workflows/dynamic.yml000064400000000000000000000020471046102023000163460ustar 00000000000000name: dynamic on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./dynamic run: cargo hack test --feature-powerset embedded: name: Build (embedded) runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: | rustup default nightly rustup target add thumbv6m-none-eabi - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./fmt run: cargo hack check --each-feature --exclude-features std,alloc -Z avoid-dev-deps --target thumbv6m-none-eabi sval-2.6.1/.github/workflows/fmt.yml000064400000000000000000000022251046102023000155060ustar 00000000000000name: fmt on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./fmt run: cargo hack test --feature-powerset - name: Powerset (Tests) working-directory: ./fmt/test run: cargo hack test --feature-powerset embedded: name: Build (embedded) runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: | rustup default nightly rustup target add thumbv6m-none-eabi - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./fmt run: cargo hack check --each-feature --exclude-features std,alloc -Z avoid-dev-deps --target thumbv6m-none-eabi sval-2.6.1/.github/workflows/json.yml000064400000000000000000000022311046102023000156660ustar 00000000000000name: json on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./json run: cargo hack test --feature-powerset - name: Powerset (Tests) working-directory: ./json/test run: cargo hack test --feature-powerset embedded: name: Build (embedded) runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: | rustup default nightly rustup target add thumbv6m-none-eabi - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./json run: cargo hack check --each-feature --exclude-features std,alloc -Z avoid-dev-deps --target thumbv6m-none-eabi sval-2.6.1/.github/workflows/ref.yml000064400000000000000000000020371046102023000154750ustar 00000000000000name: ref on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./ref run: cargo hack test --feature-powerset embedded: name: Build (embedded) runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: | rustup default nightly rustup target add thumbv6m-none-eabi - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./ref run: cargo hack check --each-feature --exclude-features std,alloc -Z avoid-dev-deps --target thumbv6m-none-eabi sval-2.6.1/.github/workflows/serde.yml000064400000000000000000000022351046102023000160230ustar 00000000000000name: serde on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./serde run: cargo hack test --feature-powerset - name: Powerset (Tests) working-directory: ./serde/test run: cargo hack test --feature-powerset embedded: name: Build (embedded) runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: | rustup default nightly rustup target add thumbv6m-none-eabi - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./serde run: cargo hack check --each-feature --exclude-features std,alloc -Z avoid-dev-deps --target thumbv6m-none-eabi sval-2.6.1/.github/workflows/sval.yml000064400000000000000000000023441046102023000156670ustar 00000000000000name: sval on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ${{ matrix.os }} strategy: fail-fast: true matrix: os: - ubuntu-latest - macos-latest - windows-latest rust: - stable - beta - nightly steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset run: cargo hack test --feature-powerset - name: All run: cargo test --all embedded: name: Build (embedded) runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: | rustup default nightly rustup target add thumbv6m-none-eabi - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset run: cargo hack check --each-feature --exclude-features std,alloc -Z avoid-dev-deps --target thumbv6m-none-eabi sval-2.6.1/.github/workflows/test.yml000064400000000000000000000007561046102023000157060ustar 00000000000000name: test on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: check: name: Test runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust toolchain run: rustup default nightly - name: Install cargo-hack run: cargo install cargo-hack - name: Powerset working-directory: ./test run: cargo hack test --feature-powerset sval-2.6.1/.gitignore000064400000000000000000000000231046102023000125620ustar 00000000000000/target Cargo.lock sval-2.6.1/CODE_OF_CONDUCT.md000064400000000000000000000064041046102023000134020ustar 00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq sval-2.6.1/Cargo.lock0000644000000030100000000000100077540ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "humantime" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "proc-macro2" version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" dependencies = [ "proc-macro2", ] [[package]] name = "sval" version = "2.6.1" dependencies = [ "humantime", "sval_derive", ] [[package]] name = "sval_derive" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab29cd7668e0c4e2829e8f38c3fd6927fc65c388d4898400a7e8cf04c040e3f6" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "syn" version = "2.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2efbeae7acf4eabd6bcdcbd11c92f45231ddda7539edc7806bd1a04a03b24616" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" sval-2.6.1/Cargo.toml0000644000000021060000000000100100040ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "sval" version = "2.6.1" authors = ["Ashley Mannix "] description = "Streaming, structured value serialization" documentation = "https://docs.rs/sval" readme = "README.md" keywords = [ "serialization", "no_std", ] categories = [ "encoding", "no-std", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/sval-rs/sval" [package.metadata.docs.rs] features = ["std"] [dependencies.sval_derive] version = "2.6.1" optional = true [dev-dependencies.humantime] version = "2" [features] alloc = [] derive = ["dep:sval_derive"] std = ["alloc"] sval-2.6.1/Cargo.toml.orig000064400000000000000000000015551046102023000134740ustar 00000000000000[package] name = "sval" version = "2.6.1" authors = ["Ashley Mannix "] edition = "2021" license = "Apache-2.0 OR MIT" documentation = "https://docs.rs/sval" description = "Streaming, structured value serialization" repository = "https://github.com/sval-rs/sval" readme = "README.md" keywords = ["serialization", "no_std"] categories = ["encoding", "no-std"] [package.metadata.docs.rs] features = ["std"] [workspace] members = [ "derive", "derive/test", "dynamic", "fmt", "fmt/test", "buffer", "serde", "serde/test", "json", "json/test", "test", "experiments", ] [features] std = ["alloc"] alloc = [] derive = ["dep:sval_derive"] [dependencies.sval_derive] version = "2.6.1" path = "derive" optional = true [dev-dependencies.sval_derive] path = "derive" [dev-dependencies.humantime] version = "2" sval-2.6.1/LICENSE-APACHE000064400000000000000000000251371046102023000125330ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. sval-2.6.1/LICENSE-MIT000064400000000000000000000020501046102023000122300ustar 00000000000000MIT License Copyright (c) 2020 sval-rs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. sval-2.6.1/README.md000064400000000000000000000042421046102023000120600ustar 00000000000000# `sval`: Streaming, structured values [![Rust](https://github.com/sval-rs/sval/workflows/sval/badge.svg)](https://github.com/sval-rs/sval/actions) [![Latest version](https://img.shields.io/crates/v/sval.svg)](https://crates.io/crates/sval) [![Documentation Latest](https://docs.rs/sval/badge.svg)](https://docs.rs/sval) `sval` is a lightweight serialization-only framework that treats values like a flat stream of tokens. It's well suited to self-describing text formats like JSON. ## How is this different from `serde`? `serde` is the de-facto serialization framework for Rust and is well suited to the majority of use cases. `sval` is like a light blend of `serde::ser` and `serde::de` that is smaller in scope. It makes a few key different design decisions than `serde` that make it effective for working with self-describing formats: 1. The API is flat rather than using recursion to stream nested datastructures. 2. All values with dynamic sizes, including text strings, can be streamed in multiple calls. 3. Borrowing is an optional optimization. 4. The core data model is small, with tags for extensibility. # Data-model - Values: - `null`: the absence of any other meaningful value. - Booleans: `true` and `false`. - Text strings: stream of UTF8-encoded bytes. - Binary strings: stream of arbtirary bytes. - Numbers: - Integers: `u8`-`u128`, `i8`-`i128`. - Binary floating point: `f32`-`f64`. - Maps: heterogeneous collection of key-value pairs. - Sequences: heterogeneous collection of values. - Tags: out-of-band type hints. - Tagged values: a tag associated with a value. - Records: tagged maps where keys are well-known labels. - Tuples: tagged sequences. - Enums: tagged variants, where variants are enums, tags, tagged values, records, or tuples. `sval` includes built-in tags that extend its data-model with some common datatypes: - Rust primitives: - `()`. - `Option`. - Arbitrary-precision decimal floating point numbers. Other built-in tags may be added in the future. Libraries may also define their own tags. ## Current status This project has a complete and stable API, but isn't well documented yet. sval-2.6.1/examples/stream/mod.rs000064400000000000000000000001551046102023000150360ustar 00000000000000/*! This file structure is here just so we can share this stream with multiple examples. */ pub mod simple; sval-2.6.1/examples/stream/simple.rs000064400000000000000000000021761046102023000155550ustar 00000000000000pub struct MyStream; impl<'sval> sval::Stream<'sval> for MyStream { fn null(&mut self) -> sval::Result { print!("null"); Ok(()) } fn bool(&mut self, v: bool) -> sval::Result { print!("{}", v); Ok(()) } fn i64(&mut self, v: i64) -> sval::Result { print!("{}", v); Ok(()) } fn f64(&mut self, v: f64) -> sval::Result { print!("{}", v); Ok(()) } fn text_begin(&mut self, _: Option) -> sval::Result { print!("\""); Ok(()) } fn text_fragment_computed(&mut self, fragment: &str) -> sval::Result { print!("{}", fragment.escape_debug()); Ok(()) } fn text_end(&mut self) -> sval::Result { print!("\""); Ok(()) } fn seq_begin(&mut self, _: Option) -> sval::Result { print!("[ "); Ok(()) } fn seq_value_begin(&mut self) -> sval::Result { Ok(()) } fn seq_value_end(&mut self) -> sval::Result { print!(", "); Ok(()) } fn seq_end(&mut self) -> sval::Result { print!("]"); Ok(()) } } sval-2.6.1/examples/stream_simple.rs000064400000000000000000000016101046102023000156250ustar 00000000000000/*! Streams have a simple core data-model that consists of: - Nulls: the lack of any meaningful value. - Booleans: `true` and `false`. - Signed integers. - Binary floating point numbers. - Text strings. - Sequences of values. This example implements a simple stream that writes directly to stdout. */ pub mod stream; fn main() -> sval::Result { stream(42)?; stream(true)?; stream(Some(42))?; stream(None::)?; #[cfg(feature = "alloc")] stream({ use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); map })?; #[cfg(feature = "alloc")] stream(vec![vec!["Hello", "world"], vec!["Hello", "world"]])?; Ok(()) } fn stream(v: impl sval::Value) -> sval::Result { v.stream(&mut stream::simple::MyStream)?; println!(); Ok(()) } sval-2.6.1/examples/tags.rs000064400000000000000000000056561046102023000137350ustar 00000000000000/*! Tags can be used to define new data types for streams to interpret differently. Some tags are built-in to `sval`, but libraries can define their own. This example defines a tag for Unix timestamps, where a 64bit number is interpreted as seconds since the Unix Epoch. */ #[macro_use] extern crate sval_derive; pub const UNIX_TIMESTAMP: sval::Tag = sval::Tag::new("unixts"); #[derive(Value)] #[sval(tag = "UNIX_TIMESTAMP")] pub struct Timestamp(u64); fn main() -> sval::Result { stream(Timestamp(1675154443))?; Ok(()) } // This is the same stream as the `stream_simple` case, except with an extra // `u64` method that handles our timestamps pub struct MyStream { is_unix_ts: bool, } impl<'sval> sval::Stream<'sval> for MyStream { fn tagged_begin( &mut self, tag: Option<&sval::Tag>, _: Option<&sval::Label>, _: Option<&sval::Index>, ) -> sval::Result { if let Some(&UNIX_TIMESTAMP) = tag { self.is_unix_ts = true; } Ok(()) } fn tagged_end( &mut self, tag: Option<&sval::Tag>, _: Option<&sval::Label>, _: Option<&sval::Index>, ) -> sval::Result { if let Some(&UNIX_TIMESTAMP) = tag { self.is_unix_ts = false; } Ok(()) } fn u64(&mut self, v: u64) -> sval::Result { // If the value is tagged as a Unix timestamp then print it using a human-readable RFC3339 format if self.is_unix_ts { print!( "{}", humantime::format_rfc3339( std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(v) ) ); } else { print!("{}", v); } Ok(()) } fn null(&mut self) -> sval::Result { print!("null"); Ok(()) } fn bool(&mut self, v: bool) -> sval::Result { print!("{}", v); Ok(()) } fn i64(&mut self, v: i64) -> sval::Result { print!("{}", v); Ok(()) } fn f64(&mut self, v: f64) -> sval::Result { print!("{}", v); Ok(()) } fn text_begin(&mut self, _: Option) -> sval::Result { print!("\""); Ok(()) } fn text_fragment_computed(&mut self, fragment: &str) -> sval::Result { print!("{}", fragment.escape_debug()); Ok(()) } fn text_end(&mut self) -> sval::Result { print!("\""); Ok(()) } fn seq_begin(&mut self, _: Option) -> sval::Result { print!("[ "); Ok(()) } fn seq_value_begin(&mut self) -> sval::Result { Ok(()) } fn seq_value_end(&mut self) -> sval::Result { print!(", "); Ok(()) } fn seq_end(&mut self) -> sval::Result { print!("]"); Ok(()) } } fn stream(v: impl sval::Value) -> sval::Result { v.stream(&mut MyStream { is_unix_ts: false })?; println!(); Ok(()) } sval-2.6.1/examples/value_derive.rs000064400000000000000000000010531046102023000154340ustar 00000000000000/*! Values are Rust structures that represent a single instance of some datatype. This example implements the `Value` trait automatically using Rust's `#[derive]` attribute. */ #[macro_use] extern crate sval_derive; pub mod stream; #[derive(Value)] pub struct MyData<'a> { id: u64, title: &'a str, } fn main() -> sval::Result { stream(MyData { id: 547, title: "Some data", })?; Ok(()) } fn stream(v: impl sval::Value) -> sval::Result { v.stream(&mut stream::simple::MyStream)?; println!(); Ok(()) } sval-2.6.1/src/data/binary.rs000064400000000000000000000047271046102023000141430ustar 00000000000000use crate::{tags, Result, Stream, Value}; /** An adapter that streams a slice of 8bit unsigned integers as binary. For fixed-size arrays, see the [`BinaryArray`] type. */ #[repr(transparent)] pub struct BinarySlice([u8]); impl BinarySlice { /** Treat a slice of 8bit unsigned integers as binary. */ pub fn new<'a>(binary: &'a [u8]) -> &'a Self { // SAFETY: `Binary` and `[u8]` have the same ABI unsafe { &*(binary as *const _ as *const BinarySlice) } } /** Get a reference to the underlying slice. */ pub fn as_slice(&self) -> &[u8] { &self.0 } } impl AsRef<[u8]> for BinarySlice { fn as_ref(&self) -> &[u8] { &self.0 } } impl Value for BinarySlice { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.binary_begin(Some(self.0.len()))?; stream.binary_fragment(&self.0)?; stream.binary_end() } fn to_binary(&self) -> Option<&[u8]> { Some(&self.0) } } /** An adapter that streams a slice of 8bit unsigned integers as binary with a fixed size. This type is like [`BinarySlice`], but for fixed-size arrays. */ #[repr(transparent)] pub struct BinaryArray([u8; N]); impl BinaryArray { /** Treat a slice of 8bit unsigned integers as binary. */ pub fn new<'a>(binary: &'a [u8; N]) -> &'a Self { // SAFETY: `Binary` and `[u8; N]` have the same ABI unsafe { &*(binary as *const _ as *const BinaryArray) } } /** Get a reference to the underlying slice. */ pub fn as_slice(&self) -> &[u8; N] { &self.0 } } impl AsRef<[u8; N]> for BinaryArray { fn as_ref(&self) -> &[u8; N] { &self.0 } } impl Value for BinaryArray { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.tagged_begin(Some(&tags::CONSTANT_SIZE), None, None)?; stream.binary_begin(Some(self.0.len()))?; stream.binary_fragment(&self.0)?; stream.binary_end()?; stream.tagged_end(Some(&tags::CONSTANT_SIZE), None, None) } fn to_binary(&self) -> Option<&[u8]> { Some(&self.0) } } #[cfg(test)] mod tests { use super::*; #[test] fn binary_cast() { assert_eq!(Some(b"abc" as &[u8]), BinarySlice::new(b"abc").to_binary()); assert_eq!(Some(b"abc" as &[u8]), BinaryArray::new(b"abc").to_binary()); } } sval-2.6.1/src/data/map.rs000064400000000000000000000024761046102023000134330ustar 00000000000000#[cfg(feature = "alloc")] mod alloc_support { use crate::{std::collections::BTreeMap, Result, Stream, Value}; impl Value for BTreeMap { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.map_begin(Some(self.len()))?; for (k, v) in self { stream.map_key_begin()?; stream.value(k)?; stream.map_key_end()?; stream.map_value_begin()?; stream.value(v)?; stream.map_value_end()?; } stream.map_end() } } } #[cfg(feature = "std")] mod std_support { use crate::{ std::{collections::HashMap, hash::BuildHasher}, Result, Stream, Value, }; impl Value for HashMap { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.map_begin(Some(self.len()))?; for (k, v) in self { stream.map_key_begin()?; stream.value(k)?; stream.map_key_end()?; stream.map_value_begin()?; stream.value(v)?; stream.map_value_end()?; } stream.map_end() } } } sval-2.6.1/src/data/number.rs000064400000000000000000000071361046102023000141440ustar 00000000000000use crate::{ std::{ fmt::{self, Write as _}, write, }, tags, Result, Stream, Value, }; macro_rules! stream_default { ($($fi:ident => $i:ty, $fu:ident => $u:ty,)*) => { $( pub(crate) fn $fi<'sval>(v: $i, stream: &mut (impl Stream<'sval> + ?Sized)) -> crate::Result { stream_number(stream, v) } pub(crate) fn $fu<'sval>(v: $u, stream: &mut (impl Stream<'sval> + ?Sized)) -> crate::Result { stream_number(stream, v) } )* }; } macro_rules! impl_value { ($( $convert:ident => $ty:ident, )+) => { $( impl Value for $ty { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> crate::Result { stream.$ty(*self) } fn $convert(&self) -> Option<$ty> { Some(*self) } } )+ }; } stream_default!( stream_i128 => i128, stream_u128 => u128, ); impl_value!( to_u8 => u8, to_u16 => u16, to_u32 => u32, to_u64 => u64, to_u128 => u128, to_i8 => i8, to_i16 => i16, to_i32 => i32, to_i64 => i64, to_i128 => i128, to_f32 => f32, to_f64 => f64, ); fn stream_number<'sval, T: fmt::Display>( mut stream: &mut (impl Stream<'sval> + ?Sized), text: T, ) -> Result { struct Writer(S); impl<'a, S: Stream<'a>> fmt::Write for Writer { fn write_str(&mut self, s: &str) -> fmt::Result { self.0.text_fragment_computed(s).map_err(|_| fmt::Error)?; Ok(()) } } stream.tagged_begin(Some(&tags::NUMBER), None, None)?; stream.text_begin(None)?; write!(Writer(&mut stream), "{}", text).map_err(|_| crate::Error::new())?; stream.text_end()?; stream.tagged_end(Some(&tags::NUMBER), None, None) } #[cfg(test)] mod tests { use super::*; #[test] fn number_cast() { assert_eq!(Some(1u8), 1u8.to_u8()); assert_eq!(Some(2u16), 2u16.to_u16()); assert_eq!(Some(3u32), 3u32.to_u32()); assert_eq!(Some(4u64), 4u64.to_u64()); assert_eq!(Some(42u128), 42u128.to_u128()); assert_eq!(Some(1i8), 1i8.to_i8()); assert_eq!(Some(2i16), 2i16.to_i16()); assert_eq!(Some(3i32), 3i32.to_i32()); assert_eq!(Some(4i64), 4i64.to_i64()); assert_eq!(Some(42i128), 42i128.to_i128()); assert_eq!(Some(3f32), 3f32.to_f32()); assert_eq!(Some(4f64), 4f64.to_f64()); } #[test] fn number_tag() { struct Number(&'static str); impl Value for Number { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.tagged_begin(Some(&tags::NUMBER), None, None)?; stream.value(self.0)?; stream.tagged_end(Some(&tags::NUMBER), None, None) } } assert_eq!(Some(tags::NUMBER), 1u8.tag()); assert_eq!(Some(tags::NUMBER), 1u16.tag()); assert_eq!(Some(tags::NUMBER), 1u32.tag()); assert_eq!(Some(tags::NUMBER), 1u64.tag()); assert_eq!(Some(tags::NUMBER), 1u128.tag()); assert_eq!(Some(tags::NUMBER), 1i8.tag()); assert_eq!(Some(tags::NUMBER), 1i16.tag()); assert_eq!(Some(tags::NUMBER), 1i32.tag()); assert_eq!(Some(tags::NUMBER), 1i64.tag()); assert_eq!(Some(tags::NUMBER), 1i128.tag()); assert_eq!(Some(tags::NUMBER), 1f32.tag()); assert_eq!(Some(tags::NUMBER), 1f64.tag()); assert_eq!(Some(tags::NUMBER), Number("42").tag()); } } sval-2.6.1/src/data/option.rs000064400000000000000000000064111046102023000141570ustar 00000000000000use crate::{tags, Index, Label, Result, Stream, Value}; impl Value for Option { fn stream<'a, S: Stream<'a> + ?Sized>(&'a self, stream: &mut S) -> Result { if let Some(some) = self { stream.tagged_begin( Some(&tags::RUST_OPTION_SOME), Some(&Label::new("Some")), Some(&Index::new(1)), )?; stream.value(some)?; stream.tagged_end( Some(&tags::RUST_OPTION_SOME), Some(&Label::new("Some")), Some(&Index::new(1)), ) } else { stream.tag( Some(&tags::RUST_OPTION_NONE), Some(&Label::new("None")), Some(&Index::new(0)), ) } } fn to_bool(&self) -> Option { self.as_ref().and_then(|value| value.to_bool()) } fn to_f32(&self) -> Option { self.as_ref().and_then(|value| value.to_f32()) } fn to_f64(&self) -> Option { self.as_ref().and_then(|value| value.to_f64()) } fn to_i8(&self) -> Option { self.as_ref().and_then(|value| value.to_i8()) } fn to_i16(&self) -> Option { self.as_ref().and_then(|value| value.to_i16()) } fn to_i32(&self) -> Option { self.as_ref().and_then(|value| value.to_i32()) } fn to_i64(&self) -> Option { self.as_ref().and_then(|value| value.to_i64()) } fn to_i128(&self) -> Option { self.as_ref().and_then(|value| value.to_i128()) } fn to_u8(&self) -> Option { self.as_ref().and_then(|value| value.to_u8()) } fn to_u16(&self) -> Option { self.as_ref().and_then(|value| value.to_u16()) } fn to_u32(&self) -> Option { self.as_ref().and_then(|value| value.to_u32()) } fn to_u64(&self) -> Option { self.as_ref().and_then(|value| value.to_u64()) } fn to_u128(&self) -> Option { self.as_ref().and_then(|value| value.to_u128()) } fn to_text(&self) -> Option<&str> { self.as_ref().and_then(|value| value.to_text()) } fn to_binary(&self) -> Option<&[u8]> { self.as_ref().and_then(|value| value.to_binary()) } } #[cfg(test)] mod tests { use super::*; #[test] fn option_cast() { assert_eq!(Some(1u8), Some(1u8).to_u8()); assert_eq!(Some(2u16), Some(2u16).to_u16()); assert_eq!(Some(3u32), Some(3u32).to_u32()); assert_eq!(Some(4u64), Some(4u64).to_u64()); assert_eq!(Some(42u128), Some(42u128).to_u128()); assert_eq!(Some(1i8), Some(1i8).to_i8()); assert_eq!(Some(2i16), Some(2i16).to_i16()); assert_eq!(Some(3i32), Some(3i32).to_i32()); assert_eq!(Some(4i64), Some(4i64).to_i64()); assert_eq!(Some(42i128), Some(42i128).to_i128()); assert_eq!(Some(3f32), Some(3f32).to_f32()); assert_eq!(Some(4f64), Some(4f64).to_f64()); assert_eq!(Some(true), Some(true).to_bool()); assert_eq!(Some("a string"), Some("a string").to_text()); } #[test] fn option_tag() { assert_eq!(Some(tags::RUST_OPTION_SOME), Some(42).tag()); assert_eq!(Some(tags::RUST_OPTION_NONE), None::.tag()); } } sval-2.6.1/src/data/seq.rs000064400000000000000000000117101046102023000134350ustar 00000000000000use crate::{tags, Index, Result, Stream, Value}; impl Value for [T] { fn stream<'a, S: Stream<'a> + ?Sized>(&'a self, stream: &mut S) -> Result { stream.seq_begin(Some(self.len()))?; for elem in self { stream.seq_value_begin()?; stream.value(elem)?; stream.seq_value_end()?; } stream.seq_end() } } impl Value for [T; N] { fn stream<'a, S: Stream<'a> + ?Sized>(&'a self, stream: &mut S) -> Result { stream.tagged_begin(Some(&tags::CONSTANT_SIZE), None, None)?; stream.seq_begin(Some(self.len()))?; for elem in self { stream.seq_value_begin()?; stream.value(elem)?; stream.seq_value_end()?; } stream.seq_end()?; stream.tagged_end(Some(&tags::CONSTANT_SIZE), None, None) } } macro_rules! tuple { ($( $len:expr => ( $(self.$i:tt: $ty:ident,)+ ), )+) => { $( impl<$($ty: Value),+> Value for ($($ty,)+) { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.tuple_begin(None, None, None, Some($len))?; $( stream.tuple_value_begin(None, &Index::new($i))?; stream.value(&self.$i)?; stream.tuple_value_end(None, &Index::new($i))?; )+ stream.tuple_end(None, None, None) } } )+ } } tuple! { 1 => ( self.0: T0, ), 2 => ( self.0: T0, self.1: T1, ), 3 => ( self.0: T0, self.1: T1, self.2: T2, ), 4 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, ), 5 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, ), 6 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, ), 7 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, ), 8 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, ), 9 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, self.8: T8, ), 10 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, self.8: T8, self.9: T9, ), 11 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, self.8: T8, self.9: T9, self.10: T10, ), 12 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, self.8: T8, self.9: T9, self.10: T10, self.11: T11, ), 13 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, self.8: T8, self.9: T9, self.10: T10, self.11: T11, self.12: T12, ), 14 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, self.8: T8, self.9: T9, self.10: T10, self.11: T11, self.12: T12, self.13: T13, ), 15 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, self.8: T8, self.9: T9, self.10: T10, self.11: T11, self.12: T12, self.13: T13, self.14: T14, ), 16 => ( self.0: T0, self.1: T1, self.2: T2, self.3: T3, self.4: T4, self.5: T5, self.6: T6, self.7: T7, self.8: T8, self.9: T9, self.10: T10, self.11: T11, self.12: T12, self.13: T13, self.14: T14, self.15: T15, ), } #[cfg(feature = "alloc")] mod alloc_support { use super::*; use crate::std::vec::Vec; impl Value for Vec { fn stream<'a, S: Stream<'a> + ?Sized>(&'a self, stream: &mut S) -> Result { (&**self).stream(stream) } } } #[cfg(test)] mod tests { use super::*; #[test] fn array_tag() { assert_eq!(Some(tags::CONSTANT_SIZE), [true, false].tag()); } } sval-2.6.1/src/data/tags.rs000064400000000000000000000021661046102023000136100ustar 00000000000000/*! Built-in tags for fundamental types. */ use super::Tag; /** A tag for a value that represents the `Some` variant of a Rust `Option`. # Valid datatypes - `tagged` */ pub const RUST_OPTION_SOME: Tag = Tag::new("RUST_OPTION_SOME"); /** A tag for a value that represents the `None` variant of a Rust `Option`. # Valid datatypes - `tag` */ pub const RUST_OPTION_NONE: Tag = Tag::new("RUST_OPTION_NONE"); /** A tag for Rust's `()` type. # Valid datatypes - `tag` */ pub const RUST_UNIT: Tag = Tag::new("RUST_UNIT"); /** A tag for arbitrary-precision decimal numbers. # Valid datatypes - `text` # Grammar ```text ^(?[+-])?(?[0-9]+)(?:\.(?[0-9]+))?(?:[eE](?[+-])?(?[0-9]+))?$ ``` Examples of valid numbers include: - `1` - `+1` - `-1` - `001` - `123.456` - `1e2` - `123.456e789` - `123.456e+789` - `123.456e-789` */ pub const NUMBER: Tag = Tag::new("NUMBER"); /** A tag for values that have a constant size. # Valid datatypes Any datatype that accepts a size hint. - `text` - `binary` - `map` - `seq` - `record` - `tuple` */ pub const CONSTANT_SIZE: Tag = Tag::new("CONSTANT_SIZE"); sval-2.6.1/src/data/text.rs000064400000000000000000000062621046102023000136370ustar 00000000000000use crate::{ std::fmt::{self, Write as _}, Error, Result, Stream, Tag, Value, }; /** Stream a [`fmt::Display`] as text into a [`Stream`]. This function can be used to stream a value as text using its `Display` implementation. */ pub fn stream_display<'sval>( stream: &mut (impl Stream<'sval> + ?Sized), value: impl fmt::Display, ) -> Result { stream.text_begin(None)?; stream_display_fragments(stream, value)?; stream.text_end() } /** Stream a [`fmt::Display`] as text fragments into a [`Stream`], without calling [`Stream::text_begin`] or [`Stream::text_end`]. This function can be used to stream a part of a larger value. */ pub fn stream_display_fragments<'sval>( stream: &mut (impl Stream<'sval> + ?Sized), value: impl fmt::Display, ) -> Result { write!( Writer(|fragment: &str| stream .text_fragment_computed(fragment) .map_err(|_| fmt::Error)), "{}", value ) .map_err(|_| Error::new()) } struct Writer(F); impl fmt::Result> fmt::Write for Writer { fn write_str(&mut self, s: &str) -> fmt::Result { (self.0)(s).map_err(|_| fmt::Error) } } impl Value for char { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { let mut buf = [0; 4]; let value = &*self.encode_utf8(&mut buf); stream.text_begin(Some(value.len()))?; stream.text_fragment_computed(value)?; stream.text_end() } } impl Value for str { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.text_begin(Some(self.len()))?; stream.text_fragment(self)?; stream.text_end() } fn tag(&self) -> Option { None } fn to_text(&self) -> Option<&str> { Some(self) } } #[cfg(feature = "alloc")] mod alloc_support { use super::*; use crate::std::string::String; impl Value for String { fn stream<'a, S: Stream<'a> + ?Sized>(&'a self, stream: &mut S) -> Result { (&**self).stream(stream) } fn tag(&self) -> Option { None } #[inline] fn to_text(&self) -> Option<&str> { Some(self) } } } #[cfg(test)] mod tests { use super::*; struct TextLike(&'static str); struct TextLikeComputed(&'static str); impl Value for TextLike { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { self.0.stream(stream) } } impl Value for TextLikeComputed { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.text_begin(Some(self.0.len()))?; stream.text_fragment_computed(self.0)?; stream.text_end() } } #[test] fn string_cast() { assert_eq!(Some("a string"), "a string".to_text()); assert_eq!(Some("a string"), TextLike("a string").to_text()); assert_eq!(None, TextLikeComputed("123").to_text()); } #[test] fn string_tag() { assert_eq!(None, TextLike("123").tag()); assert_eq!(None, TextLikeComputed("123").tag()); } } sval-2.6.1/src/data.rs000064400000000000000000000273141046102023000126540ustar 00000000000000mod binary; mod map; mod number; mod option; mod seq; mod text; pub mod tags; use crate::{ std::{ borrow::Borrow, fmt, hash::{Hash, Hasher}, marker::PhantomData, }, Result, Stream, Value, }; #[cfg(feature = "alloc")] use crate::std::string::String; pub(crate) use self::number::*; pub use self::{binary::*, text::*}; /** A textual label for some value. */ pub struct Label<'computed> { // This field may point to some external data borrowed for `'computed` // or to the `_value_owned` field. It could be a `Cow<'computed, str>`, // but this way is cheaper to access because it avoids checking the // `Cow` variant value_computed: *const str, // Only one `backing_field_*` may be `Some` backing_field_static: Option<&'static str>, #[cfg(feature = "alloc")] backing_field_owned: Option, _marker: PhantomData<&'computed str>, } // SAFETY: Label doesn't mutate or synchronize: it acts just like a `&str` unsafe impl<'computed> Send for Label<'computed> {} // SAFETY: Label doesn't mutate or synchronize: it acts just like a `&str` unsafe impl<'computed> Sync for Label<'computed> {} #[cfg(not(feature = "alloc"))] impl<'computed> Clone for Label<'computed> { fn clone(&self) -> Self { Label { value_computed: self.value_computed, backing_field_static: self.backing_field_static, _marker: PhantomData, } } } impl<'computed> Label<'computed> { /** Create a new label from a static string value. For labels that can't satisfy the `'static` lifetime, use [`Label::new_computed`]. For labels that need owned values, use [`Label::new_owned`]. */ pub const fn new(label: &'static str) -> Self { Label { value_computed: label as *const str, backing_field_static: Some(label), #[cfg(feature = "alloc")] backing_field_owned: None, _marker: PhantomData, } } /** Create a new label from a string value borrowed for the `'computed` lifetime. */ pub const fn new_computed(label: &'computed str) -> Self { Label { value_computed: label as *const str, backing_field_static: None, #[cfg(feature = "alloc")] backing_field_owned: None, _marker: PhantomData, } } /** Get the value of the label as a string. */ pub const fn as_str(&self) -> &str { // SAFETY: The borrow of the `value_computed` field can't outlive // the label itself, so even if `value_computed` points to `_value_owned` // it will never dangle. unsafe { &*self.value_computed } } /** Try get the value of the label as a static string. For labels that were created over computed data this method will return `None`. */ pub const fn as_static_str(&self) -> Option<&'static str> { self.backing_field_static } } impl<'a, 'b> PartialEq> for Label<'a> { fn eq(&self, other: &Label<'b>) -> bool { self.as_str() == other.as_str() } } impl<'a> Eq for Label<'a> {} impl<'a> Hash for Label<'a> { fn hash(&self, state: &mut H) { self.as_str().hash(state) } } impl<'a> Borrow for Label<'a> { fn borrow(&self) -> &str { self.as_str() } } impl<'a> fmt::Debug for Label<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_tuple("Label").field(&self.as_str()).finish() } } /** A type tag for a value. Tags are additional hints that a stream may use to interpret a value differently, or to avoid some unnecessary work. The contents of a tag aren't considered public, only equality between two tag identifiers. */ #[derive(Clone, PartialEq, Eq)] pub struct Tag { id: u64, data: &'static str, } impl Tag { /** Create a new tag from a static string value. */ pub const fn new(data: &'static str) -> Self { // Fast, non-cryptographic hash used by rustc and Firefox. // Adapted from: https://github.com/rust-lang/rustc-hash/blob/master/src/lib.rs to work in CTFE // // We use hashes for quick tag comparison, if they collide then we'll compare the full value const fn compute_id(bytes: &[u8]) -> u64 { // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. const K: u64 = 0x517cc1b727220a95u64; let mut hash = 0u64; let mut b = 0; while b + 8 <= bytes.len() { let i = [ bytes[b + 0], bytes[b + 1], bytes[b + 2], bytes[b + 3], bytes[b + 4], bytes[b + 5], bytes[b + 6], bytes[b + 7], ]; let i = u64::from_ne_bytes(i); hash = (hash.rotate_left(5) ^ i).wrapping_mul(K); b += 8; } if b + 4 <= bytes.len() { let i = [bytes[b + 0], bytes[b + 1], bytes[b + 2], bytes[b + 3]]; let i = u32::from_ne_bytes(i) as u64; hash = (hash.rotate_left(5) ^ i).wrapping_mul(K); b += 4; } if b + 2 <= bytes.len() { let i = [bytes[b + 0], bytes[b + 1]]; let i = u16::from_ne_bytes(i) as u64; hash = (hash.rotate_left(5) ^ i).wrapping_mul(K); b += 2; } if b + 1 <= bytes.len() { let i = bytes[b + 0] as u64; hash = (hash.rotate_left(5) ^ i).wrapping_mul(K); } hash } Tag { id: compute_id(data.as_bytes()), data, } } } impl fmt::Debug for Tag { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_tuple("Tag").field(&self.data).finish() } } /** The index of a value in its parent context. */ #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Index(usize); impl Index { /** Create a new index from a numeric value. */ pub const fn new(index: usize) -> Self { Index(index) } /** Create a new index from a 32bit numeric value. */ pub const fn new_u32(index: u32) -> Self { Index(index as usize) } /** Try get the index as a numeric value. */ pub const fn to_usize(&self) -> Option { Some(self.0) } /** Try get the index as a 32-bit numeric value. */ pub const fn to_u32(&self) -> Option { if self.0 <= u32::MAX as usize { Some(self.0 as u32) } else { None } } } impl fmt::Debug for Index { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_tuple("Index").field(&self.0).finish() } } impl Value for () { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.tag(Some(&tags::RUST_UNIT), None, None) } } impl Value for bool { fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result { stream.bool(*self) } fn tag(&self) -> Option { None } fn to_bool(&self) -> Option { Some(*self) } } #[cfg(feature = "alloc")] mod alloc_support { use super::*; use crate::std::string::String; impl<'computed> Clone for Label<'computed> { fn clone(&self) -> Self { if let Some(ref owned) = self.backing_field_owned { Label::new_owned(owned.clone()) } else { Label { value_computed: self.value_computed, backing_field_static: self.backing_field_static, backing_field_owned: None, _marker: PhantomData, } } } } impl<'computed> Label<'computed> { /** Create an owned label from this one. This method will allocate if the label isn't based on a static string. */ pub fn to_owned(&self) -> Label<'static> { if let Some(backing_field_static) = self.backing_field_static { Label::new(backing_field_static) } else { Label::new_owned(self.as_str().into()) } } } impl Label<'static> { /** Create a new label from an owned string value. */ pub fn new_owned(label: String) -> Self { Label { value_computed: label.as_str() as *const str, backing_field_static: None, backing_field_owned: Some(label), _marker: PhantomData, } } } } #[cfg(test)] mod tests { use super::*; #[test] fn unit_tag() { assert_eq!(Some(tags::RUST_UNIT), ().tag()); } #[test] fn label_send_sync() { fn assert() {} assert::