├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── pull_request_template.md └── workflows │ └── rust-ci.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── crates ├── mirror-mirror-macros │ ├── Cargo.toml │ └── src │ │ ├── derive_reflect │ │ ├── attrs.rs │ │ ├── enum_.rs │ │ ├── mod.rs │ │ ├── struct_named.rs │ │ └── tuple_struct.rs │ │ └── lib.rs └── mirror-mirror │ ├── Cargo.toml │ └── src │ ├── array.rs │ ├── enum_.rs │ ├── foreign_impls │ ├── array.rs │ ├── boxed.rs │ ├── btree_map.rs │ ├── glam.rs │ ├── glam │ │ ├── mat2.rs │ │ ├── quat.rs │ │ └── vec4.rs │ ├── hash_map.rs │ ├── kollect │ │ ├── linear_map.rs │ │ ├── linear_set.rs │ │ ├── mod.rs │ │ ├── ordered_map.rs │ │ ├── ordered_set.rs │ │ ├── unordered_map.rs │ │ └── unordered_set.rs │ ├── macaw.rs │ ├── mod.rs │ ├── vec.rs │ ├── vec_deque.rs │ └── via_scalar.rs │ ├── get_field.rs │ ├── iter.rs │ ├── key_path.rs │ ├── lib.rs │ ├── list.rs │ ├── map.rs │ ├── reflect_eq.rs │ ├── set.rs │ ├── struct_.rs │ ├── tests │ ├── array.rs │ ├── enum_.rs │ ├── key_path.rs │ ├── list.rs │ ├── map.rs │ ├── meta.rs │ ├── mod.rs │ ├── simple_type_name.rs │ ├── struct_.rs │ ├── tuple.rs │ ├── tuple_struct.rs │ ├── type_info.rs │ └── value.rs │ ├── try_visit.rs │ ├── tuple.rs │ ├── tuple_struct.rs │ ├── type_info │ ├── graph.rs │ ├── mod.rs │ ├── pretty_print.rs │ └── simple_type_name.rs │ └── value.rs └── deny.toml /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Documentation for this file can be found on the GitHub website here: 2 | # https://docs.github.com/en/free-pro-team@latest/github/creating-cloning-and-archiving-repositories/about-code-owners 3 | 4 | * @davidpdrsn 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Device:** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### Checklist 2 | 3 | * [ ] I have read the [Contributor Guide](../../CONTRIBUTING.md) 4 | * [ ] I have read and agree to the [Code of Conduct](../../CODE_OF_CONDUCT.md) 5 | * [ ] I have added a description of my changes and why I'd like them included in the section below 6 | 7 | ### Description of Changes 8 | 9 | Describe your changes here 10 | 11 | ### Related Issues 12 | 13 | List related issues here 14 | -------------------------------------------------------------------------------- /.github/workflows/rust-ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | pull_request: {} 6 | 7 | name: CI 8 | jobs: 9 | lint: 10 | name: Lint 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - uses: actions-rs/toolchain@v1 15 | with: 16 | toolchain: stable 17 | override: true 18 | - uses: Swatinem/rust-cache@v1 19 | - name: check rustfmt 20 | run: | 21 | rustup component add rustfmt 22 | cargo fmt -- --check --color always 23 | - run: cargo fetch 24 | - name: cargo clippy 25 | run: | 26 | rustup component add clippy 27 | cargo clippy --all-targets --all-features -- -D warnings 28 | - uses: EmbarkStudios/cargo-deny-action@v2 29 | 30 | cargo-hack: 31 | runs-on: ubuntu-latest 32 | steps: 33 | - uses: actions/checkout@v3 34 | - uses: actions-rs/toolchain@v1 35 | with: 36 | toolchain: stable 37 | override: true 38 | - uses: Swatinem/rust-cache@v1 39 | - name: Install cargo-hack 40 | run: | 41 | curl -LsSf https://github.com/taiki-e/cargo-hack/releases/latest/download/cargo-hack-x86_64-unknown-linux-gnu.tar.gz | tar xzf - -C ~/.cargo/bin 42 | - name: cargo hack check 43 | run: cargo hack check --each-feature --no-dev-deps --all 44 | 45 | check-docs: 46 | runs-on: ubuntu-latest 47 | steps: 48 | - uses: actions/checkout@master 49 | - uses: actions-rs/toolchain@v1 50 | with: 51 | toolchain: stable 52 | override: true 53 | profile: minimal 54 | - uses: Swatinem/rust-cache@v1 55 | - name: cargo doc 56 | env: 57 | RUSTDOCFLAGS: "-D broken-intra-doc-links" 58 | run: cargo doc --all-features --no-deps 59 | 60 | build-wasm: 61 | runs-on: ubuntu-latest 62 | steps: 63 | - uses: actions/checkout@v3 64 | - uses: actions-rs/toolchain@v1 65 | with: 66 | toolchain: stable 67 | override: true 68 | - uses: Swatinem/rust-cache@v1 69 | - run: rustup target add wasm32-unknown-unknown 70 | - run: cargo build --target wasm32-unknown-unknown --all-features 71 | 72 | test: 73 | name: Test 74 | strategy: 75 | matrix: 76 | # no need to test on all platforms since we don't use platform specific APIs 77 | # and mac and window are generally the slowest on github actions 78 | # os: [ubuntu-latest, windows-latest, macOS-latest] 79 | os: [ubuntu-latest] 80 | runs-on: ${{ matrix.os }} 81 | steps: 82 | - uses: actions/checkout@v3 83 | - uses: actions-rs/toolchain@v1 84 | with: 85 | toolchain: stable 86 | override: true 87 | - uses: Swatinem/rust-cache@v1 88 | - run: cargo fetch 89 | - name: cargo test build 90 | run: cargo build --tests 91 | - name: cargo test 92 | run: cargo test 93 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | # Unreleased (RC released as `0.2.0-rc.1`) 9 | 10 | - **breaking:** Remove `Reflect::type_descriptor`. Instead capture the type 11 | descriptor explicitly with `::type_descriptor()` ([#90]) 12 | - **breaking:** Make `KeyPath::pop` return the popped key ([#110]) 13 | - **breaking:** Remove `Reflect::type_id` ([#109]) 14 | - **breaking:** `no-std` support has been removed ([#119]) 15 | - **fixed:** Iterating over fields and variants in type descriptors is now done 16 | in the same order as defined in the code ([#119]) 17 | - **fixed:** Support derive reflect for `HashMap` ([#119]) 18 | - **breaking:** Add `Array::swap` ([#136]) 19 | - **breaking:** Add `List::try_insert` ([#136]) 20 | - **breaking:** `List::push` renamed to `List::try_push` ([#136]) 21 | - **breaking:** `Map::insert` renamed to `Map::try_insert` ([#136]) 22 | - **breaking:** `Map::remove` renamed to `Map::try_remove` ([#136]) 23 | - **breaking:** Update to kollect `0.5` 24 | - **breaking:** Add reflected sets ([#140]) 25 | - **fixed:** Fix `<[T; N]>::from_reflect` for `Value::List`. It used to fail but now works 26 | - **fixed:** `Vec::as_array`, `Vec::as_array_mut`, `Vec::into_array` now 27 | correctly return `Some(_)`. 28 | - **fixed:** `Value::as_array`, `Value::as_array_mut`, `Value::into_array` now 29 | correctly return `Some(_)`. 30 | - **breaking:** Require `glam` version from `0.28` to `0.30` 31 | - **breaking:** Require `glam` version to be >= `0.30.3` when `speedy` feature is enabled 32 | - **changed:** No longer require `Sized` for `SimpleTypeName::new_from_type` 33 | - **added:** Support pretty printing trait objects 34 | 35 | [#90]: https://github.com/EmbarkStudios/mirror-mirror/pull/90 36 | [#110]: https://github.com/EmbarkStudios/mirror-mirror/pull/110 37 | [#109]: https://github.com/EmbarkStudios/mirror-mirror/pull/109 38 | [#119]: https://github.com/EmbarkStudios/mirror-mirror/pull/119 39 | [#136]: https://github.com/EmbarkStudios/mirror-mirror/pull/136 40 | [#140]: https://github.com/EmbarkStudios/mirror-mirror/pull/140 41 | 42 | # 0.1.20 (15. April, 2023) 43 | 44 | - **change:** Remove transitive dependencies on num-traits and ordered-float ([#143]) 45 | 46 | [#143]: https://github.com/EmbarkStudios/mirror-mirror/pull/143 47 | 48 | # 0.1.19 (26. February, 2023) 49 | 50 | - Allow a `glam` version range between `0.22` and `0.25`, inclusive. 51 | 52 | # 0.1.18 (22. February, 2023) 53 | 54 | - Update internal dependencies 55 | 56 | # 0.1.17 (23. January, 2023) 57 | 58 | - Update internal dependencies 59 | 60 | # 0.1.16 (11. September, 2023) 61 | 62 | - **added:** Add `reflect_eq` ([#126]) 63 | 64 | [#126]: https://github.com/EmbarkStudios/mirror-mirror/pull/126 65 | 66 | # 0.1.15 (08. August, 2023) 67 | 68 | - **added:** Implement serialization traits for `ScalarOwned` ([#117]) 69 | - **fixed:** Use `core::any::type_name` to determine `type_name` for `ScalarType` variants ([#124]) 70 | 71 | [#124]: https://github.com/EmbarkStudios/mirror-mirror/pull/124 72 | [#117]: https://github.com/EmbarkStudios/mirror-mirror/pull/117 73 | 74 | # 0.1.14 (11. April, 2023) 75 | 76 | - **change:** Make use of deterministic hashes for `NodeId` and `TypeDescriptor` ([#115]) 77 | 78 | [#115]: https://github.com/EmbarkStudios/mirror-mirror/pull/115 79 | 80 | # 0.1.13 (29. March, 2023) 81 | 82 | - **fixed:** Require less strict `speedy` version ([#114]) 83 | 84 | [#114]: https://github.com/EmbarkStudios/mirror-mirror/pull/114 85 | 86 | # 0.1.12 (21. March, 2023) 87 | 88 | - **change:** Update to syn 2.0 ([#113]) 89 | 90 | [#113]: https://github.com/EmbarkStudios/mirror-mirror/pull/113 91 | 92 | # 0.1.11 (20. March, 2023) 93 | 94 | - **added:** Implement serialization traits for `ScalarOwned` 95 | 96 | # 0.1.14 (11. April, 2023) 97 | 98 | - **change:** Make use of deterministic hashes for `NodeId` and `TypeDescriptor` ([#115]) 99 | 100 | [#115]: https://github.com/EmbarkStudios/mirror-mirror/pull/115 101 | 102 | # 0.1.13 (29. March, 2023) 103 | 104 | - **fixed:** Require less strict `speedy` version ([#114]) 105 | 106 | [#114]: https://github.com/EmbarkStudios/mirror-mirror/pull/114 107 | 108 | # 0.1.12 (21. March, 2023) 109 | 110 | - **change:** Update to syn 2.0 ([#113]) 111 | 112 | [#113]: https://github.com/EmbarkStudios/mirror-mirror/pull/113 113 | 114 | # 0.1.11 (20. March, 2023) 115 | 116 | - **added:** Implement `Reflect`, and friends, for `Infallible` ([#111]) 117 | - **change:** Update to syn 2.0 ([#112]) 118 | 119 | [#111]: https://github.com/EmbarkStudios/mirror-mirror/pull/111 120 | [#112]: https://github.com/EmbarkStudios/mirror-mirror/pull/112 121 | 122 | # 0.1.10 (03. March, 2023) 123 | 124 | - **fixed:** Fully qualify `FromReflect` in generated code ([#107]) 125 | 126 | [#90]: https://github.com/EmbarkStudios/mirror-mirror/pull/90 127 | [#107]: https://github.com/EmbarkStudios/mirror-mirror/pull/107 128 | 129 | # 0.1.9 (24. February, 2023) 130 | 131 | - **added:** Add `StructValue::with_capacity`, 132 | `TupleStructValue::with_capacity`, and `TupleValue::with_capacity` ([#106]) 133 | - **added:** Add `EnumValue::new_struct_variant_with_capacity` and 134 | `EnumValue::new_struct_variant_with_capacity` constructors ([#106]) 135 | - **fixed:** In `Reflect::to_value` for enums, only generate a catch all branch 136 | if the enum has a variant with `#[reflect(skip)]` ([#105]) 137 | - **added:** Add a `has_default_value` method to types in `type_info` ([#104]) 138 | 139 | [#105]: https://github.com/EmbarkStudios/mirror-mirror/pull/105 140 | [#104]: https://github.com/EmbarkStudios/mirror-mirror/pull/104 141 | [#106]: https://github.com/EmbarkStudios/mirror-mirror/pull/106 142 | 143 | # 0.1.8 (23. February, 2023) 144 | 145 | - **added:** Make `Key` and `KeyPath` impl `Hash` ([#103]) 146 | 147 | [#103]: https://github.com/EmbarkStudios/mirror-mirror/pull/103 148 | 149 | # 0.1.7 (23. February, 2023) 150 | 151 | - **added:** Implement `PartialEq`, `Eq`, `Hash` for types in `type_info` ([#100] [#101]) 152 | 153 | [#100]: https://github.com/EmbarkStudios/mirror-mirror/pull/100 154 | [#101]: https://github.com/EmbarkStudios/mirror-mirror/pull/101 155 | 156 | # 0.1.6 (16. February, 2023) 157 | 158 | - **fixed:** Fix inconsistent ordering when iterating over fields in struct 159 | values and struct types. Same for struct variants ([#98]) 160 | 161 | [#98]: https://github.com/EmbarkStudios/mirror-mirror/pull/98 162 | 163 | # 0.1.5 (14. February, 2023) 164 | 165 | - **added:** Add visitor API ([#92]) 166 | - **added:** Add `fields_len` methods to the following types ([#94]) 167 | - `StructType` 168 | - `TupleStructType` 169 | - `TupleType` 170 | - `Variant` 171 | - `StructVariant` 172 | - `TupleStructVariant` 173 | - **added:** Add `EnumType::variants_len` ([#94]) 174 | - **added:** Support setting a default value for `OpaqueType` ([#97]) 175 | - **added:** Support pretty printing types ([#95]) 176 | 177 | [#92]: https://github.com/EmbarkStudios/mirror-mirror/pull/92 178 | [#94]: https://github.com/EmbarkStudios/mirror-mirror/pull/94 179 | [#95]: https://github.com/EmbarkStudios/mirror-mirror/pull/95 180 | [#97]: https://github.com/EmbarkStudios/mirror-mirror/pull/97 181 | 182 | # 0.1.4 (13. February, 2023) 183 | 184 | - **added:** Implement `Hash` to `Value` ([#93]) 185 | 186 | [#93]: https://github.com/EmbarkStudios/mirror-mirror/pull/93 187 | 188 | # 0.1.3 (08. February, 2023) 189 | 190 | - **fixed:** Make `SimpleTypeName` support types defined inside unnamed constants ([#91]) 191 | 192 | [#91]: https://github.com/EmbarkStudios/mirror-mirror/pull/91 193 | 194 | # 0.1.2 (03. February, 2023) 195 | 196 | - **added:** Add `impl From for KeyPath` ([#88]) 197 | 198 | [#88]: https://github.com/EmbarkStudios/mirror-mirror/pull/88 199 | 200 | # 0.1.1 (17. January, 2023) 201 | 202 | - **added:** Add `Reflect` impls for [`glam`] types ([#85]) 203 | - **added:** Add `Reflect` impls for [`macaw`] types ([#85]) 204 | 205 | [#85]: https://github.com/EmbarkStudios/mirror-mirror/pull/85 206 | [`glam`]: https://crates.io/crates/glam 207 | [`macaw`]: https://crates.io/crates/macaw 208 | 209 | # 0.1.0 (12. January, 2023) 210 | 211 | - Initial release. 212 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at opensource@embark-studios.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Embark Contributor Guidelines 2 | 3 | Welcome! This project is created by the team at [Embark Studios](https://embark.games). We're glad you're interested in contributing! We welcome contributions from people of all backgrounds who are interested in making great software with us. 4 | 5 | At Embark, we aspire to empower everyone to create interactive experiences. To do this, we're exploring and pushing the boundaries of new technologies, and sharing our learnings with the open source community. 6 | 7 | If you have ideas for collaboration, email us at opensource@embark-studios.com. 8 | 9 | We're also hiring full-time engineers to work with us in Stockholm! Check out our current job postings [here](https://www.embark-studios.com/jobs). 10 | 11 | ## Issues 12 | 13 | ### Feature Requests 14 | 15 | If you have ideas or how to improve our projects, you can suggest features by opening a GitHub issue. Make sure to include details about the feature or change, and describe any uses cases it would enable. 16 | 17 | Feature requests will be tagged as `enhancement` and their status will be updated in the comments of the issue. 18 | 19 | ### Bugs 20 | 21 | When reporting a bug or unexpected behavior in a project, make sure your issue describes steps to reproduce the behavior, including the platform you were using, what steps you took, and any error messages. 22 | 23 | Reproducible bugs will be tagged as `bug` and their status will be updated in the comments of the issue. 24 | 25 | ### Wontfix 26 | 27 | Issues will be closed and tagged as `wontfix` if we decide that we do not wish to implement it, usually due to being misaligned with the project vision or out of scope. We will comment on the issue with more detailed reasoning. 28 | 29 | ## Contribution Workflow 30 | 31 | ### Open Issues 32 | 33 | If you're ready to contribute, start by looking at our open issues tagged as [`help wanted`](../../issues?q=is%3Aopen+is%3Aissue+label%3A"help+wanted") or [`good first issue`](../../issues?q=is%3Aopen+is%3Aissue+label%3A"good+first+issue"). 34 | 35 | You can comment on the issue to let others know you're interested in working on it or to ask questions. 36 | 37 | ### Making Changes 38 | 39 | 1. Fork the repository. 40 | 41 | 2. Create a new feature branch. 42 | 43 | 3. Make your changes. Ensure that there are no build errors by running the project with your changes locally. 44 | 45 | 4. Open a pull request with a name and description of what you did. You can read more about working with pull requests on GitHub [here](https://help.github.com/en/articles/creating-a-pull-request-from-a-fork). 46 | 47 | 5. A maintainer will review your pull request and may ask you to make changes. 48 | 49 | ## Code Guidelines 50 | 51 | ### Rust 52 | 53 | You can read about our standards and recommendations for working with Rust [here](https://github.com/EmbarkStudios/rust-ecosystem/blob/main/guidelines.md). 54 | 55 | ### Python 56 | 57 | We recommend following [PEP8 conventions](https://www.python.org/dev/peps/pep-0008/) when working with Python modules. 58 | 59 | ### JavaScript & TypeScript 60 | 61 | We use [Prettier](https://prettier.io/) with the default settings to auto-format our JavaScript and TypeScript code. 62 | 63 | ## Licensing 64 | 65 | Unless otherwise specified, all Embark open source projects shall comply with the Rust standard licensing model (MIT + Apache 2.0) and are thereby licensed under a dual license, allowing licensees to choose either MIT OR Apache-2.0 at their option. 66 | 67 | ## Contributor Terms 68 | 69 | Thank you for your interest in Embark Studios’ open source project. By providing a contribution (new or modified code, other input, feedback or suggestions etc.) you agree to these Contributor Terms. 70 | 71 | You confirm that each of your contributions has been created by you and that you are the copyright owner. You also confirm that you have the right to provide the contribution to us and that you do it under the Rust dual licence model (MIT + Apache 2.0). 72 | 73 | If you want to contribute something that is not your original creation, you may submit it to Embark Studios separately from any contribution, including details of its source and of any license or other restriction (such as related patents, trademarks, agreements etc.) 74 | 75 | Please also note that our projects are released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md) to ensure that they are welcoming places for everyone to contribute. By participating in any Embark Studios open source project, you agree to keep to the Contributor Code of Conduct. 76 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "ahash" 7 | version = "0.8.11" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" 10 | dependencies = [ 11 | "cfg-if", 12 | "once_cell", 13 | "version_check", 14 | "zerocopy", 15 | ] 16 | 17 | [[package]] 18 | name = "autocfg" 19 | version = "1.3.0" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" 22 | 23 | [[package]] 24 | name = "base64" 25 | version = "0.21.7" 26 | source = "registry+https://github.com/rust-lang/crates.io-index" 27 | checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" 28 | 29 | [[package]] 30 | name = "bitflags" 31 | version = "2.5.0" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" 34 | dependencies = [ 35 | "serde", 36 | ] 37 | 38 | [[package]] 39 | name = "cfg-if" 40 | version = "1.0.0" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 43 | 44 | [[package]] 45 | name = "critical-section" 46 | version = "1.2.0" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" 49 | 50 | [[package]] 51 | name = "equivalent" 52 | version = "1.0.1" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" 55 | 56 | [[package]] 57 | name = "foldhash" 58 | version = "0.1.5" 59 | source = "registry+https://github.com/rust-lang/crates.io-index" 60 | checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" 61 | 62 | [[package]] 63 | name = "glam" 64 | version = "0.25.0" 65 | source = "registry+https://github.com/rust-lang/crates.io-index" 66 | checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" 67 | 68 | [[package]] 69 | name = "glam" 70 | version = "0.30.3" 71 | source = "registry+https://github.com/rust-lang/crates.io-index" 72 | checksum = "6b46b9ca4690308844c644e7c634d68792467260e051c8543e0c7871662b3ba7" 73 | dependencies = [ 74 | "speedy", 75 | ] 76 | 77 | [[package]] 78 | name = "hashbrown" 79 | version = "0.14.5" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" 82 | 83 | [[package]] 84 | name = "indexmap" 85 | version = "2.2.6" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" 88 | dependencies = [ 89 | "equivalent", 90 | "hashbrown", 91 | "serde", 92 | ] 93 | 94 | [[package]] 95 | name = "kollect" 96 | version = "0.5.0" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | checksum = "48a306ef61dbda898613bca39744d438a64748a42220d0184a3581c7db9902fc" 99 | dependencies = [ 100 | "foldhash", 101 | "indexmap", 102 | "rustc-hash", 103 | "serde", 104 | "speedy", 105 | ] 106 | 107 | [[package]] 108 | name = "libm" 109 | version = "0.2.8" 110 | source = "registry+https://github.com/rust-lang/crates.io-index" 111 | checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" 112 | 113 | [[package]] 114 | name = "macaw" 115 | version = "0.30.0" 116 | source = "registry+https://github.com/rust-lang/crates.io-index" 117 | checksum = "4c96b82556b0d4aa25cd4771b64ef9bde7c120afb588a083fcb242bf01e4a09b" 118 | dependencies = [ 119 | "glam 0.30.3", 120 | "num-traits", 121 | ] 122 | 123 | [[package]] 124 | name = "memoffset" 125 | version = "0.9.1" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" 128 | dependencies = [ 129 | "autocfg", 130 | ] 131 | 132 | [[package]] 133 | name = "mirror-mirror" 134 | version = "0.1.21" 135 | source = "registry+https://github.com/rust-lang/crates.io-index" 136 | checksum = "ce46b22b6b229dc16c1b01990353e6e849d067dfcb7c1dd77dddb38983b22ada" 137 | dependencies = [ 138 | "ahash", 139 | "mirror-mirror-macros 0.1.4", 140 | "once_cell", 141 | "serde", 142 | "speedy", 143 | "syn", 144 | "tiny-ordered-float", 145 | ] 146 | 147 | [[package]] 148 | name = "mirror-mirror" 149 | version = "0.2.0-rc.1" 150 | dependencies = [ 151 | "ahash", 152 | "glam 0.30.3", 153 | "kollect", 154 | "macaw", 155 | "mirror-mirror 0.1.21", 156 | "mirror-mirror-macros 0.2.0-rc.1", 157 | "once_cell", 158 | "ron", 159 | "serde", 160 | "speedy", 161 | "syn", 162 | "tiny-ordered-float", 163 | ] 164 | 165 | [[package]] 166 | name = "mirror-mirror-macros" 167 | version = "0.1.4" 168 | source = "registry+https://github.com/rust-lang/crates.io-index" 169 | checksum = "873a8136d73249ded007bc60b4a2e0fc44558469e622f86a84e906361fb79131" 170 | dependencies = [ 171 | "proc-macro2", 172 | "quote", 173 | "syn", 174 | ] 175 | 176 | [[package]] 177 | name = "mirror-mirror-macros" 178 | version = "0.2.0-rc.1" 179 | dependencies = [ 180 | "kollect", 181 | "mirror-mirror 0.2.0-rc.1", 182 | "proc-macro2", 183 | "quote", 184 | "syn", 185 | ] 186 | 187 | [[package]] 188 | name = "num-traits" 189 | version = "0.2.19" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 192 | dependencies = [ 193 | "autocfg", 194 | "libm", 195 | ] 196 | 197 | [[package]] 198 | name = "once_cell" 199 | version = "1.19.0" 200 | source = "registry+https://github.com/rust-lang/crates.io-index" 201 | checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" 202 | dependencies = [ 203 | "critical-section", 204 | "portable-atomic", 205 | ] 206 | 207 | [[package]] 208 | name = "portable-atomic" 209 | version = "1.6.0" 210 | source = "registry+https://github.com/rust-lang/crates.io-index" 211 | checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0" 212 | 213 | [[package]] 214 | name = "proc-macro2" 215 | version = "1.0.81" 216 | source = "registry+https://github.com/rust-lang/crates.io-index" 217 | checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" 218 | dependencies = [ 219 | "unicode-ident", 220 | ] 221 | 222 | [[package]] 223 | name = "quote" 224 | version = "1.0.36" 225 | source = "registry+https://github.com/rust-lang/crates.io-index" 226 | checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" 227 | dependencies = [ 228 | "proc-macro2", 229 | ] 230 | 231 | [[package]] 232 | name = "ron" 233 | version = "0.8.1" 234 | source = "registry+https://github.com/rust-lang/crates.io-index" 235 | checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94" 236 | dependencies = [ 237 | "base64", 238 | "bitflags", 239 | "serde", 240 | "serde_derive", 241 | ] 242 | 243 | [[package]] 244 | name = "rustc-hash" 245 | version = "1.1.0" 246 | source = "registry+https://github.com/rust-lang/crates.io-index" 247 | checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" 248 | 249 | [[package]] 250 | name = "serde" 251 | version = "1.0.200" 252 | source = "registry+https://github.com/rust-lang/crates.io-index" 253 | checksum = "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f" 254 | dependencies = [ 255 | "serde_derive", 256 | ] 257 | 258 | [[package]] 259 | name = "serde_derive" 260 | version = "1.0.200" 261 | source = "registry+https://github.com/rust-lang/crates.io-index" 262 | checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb" 263 | dependencies = [ 264 | "proc-macro2", 265 | "quote", 266 | "syn", 267 | ] 268 | 269 | [[package]] 270 | name = "speedy" 271 | version = "0.8.7" 272 | source = "registry+https://github.com/rust-lang/crates.io-index" 273 | checksum = "da1992073f0e55aab599f4483c460598219b4f9ff0affa124b33580ab511e25a" 274 | dependencies = [ 275 | "glam 0.25.0", 276 | "memoffset", 277 | "speedy-derive", 278 | ] 279 | 280 | [[package]] 281 | name = "speedy-derive" 282 | version = "0.8.7" 283 | source = "registry+https://github.com/rust-lang/crates.io-index" 284 | checksum = "658f2ca5276b92c3dfd65fa88316b4e032ace68f88d7570b43967784c0bac5ac" 285 | dependencies = [ 286 | "proc-macro2", 287 | "quote", 288 | "syn", 289 | ] 290 | 291 | [[package]] 292 | name = "syn" 293 | version = "2.0.60" 294 | source = "registry+https://github.com/rust-lang/crates.io-index" 295 | checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" 296 | dependencies = [ 297 | "proc-macro2", 298 | "quote", 299 | "unicode-ident", 300 | ] 301 | 302 | [[package]] 303 | name = "tiny-ordered-float" 304 | version = "0.4.0" 305 | source = "registry+https://github.com/rust-lang/crates.io-index" 306 | checksum = "3a43fe20b81bb52ecac2d82b661775b44608cdf3ea717603d69280091f126575" 307 | 308 | [[package]] 309 | name = "unicode-ident" 310 | version = "1.0.12" 311 | source = "registry+https://github.com/rust-lang/crates.io-index" 312 | checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" 313 | 314 | [[package]] 315 | name = "version_check" 316 | version = "0.9.4" 317 | source = "registry+https://github.com/rust-lang/crates.io-index" 318 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 319 | 320 | [[package]] 321 | name = "zerocopy" 322 | version = "0.7.33" 323 | source = "registry+https://github.com/rust-lang/crates.io-index" 324 | checksum = "087eca3c1eaf8c47b94d02790dd086cd594b912d2043d4de4bfdd466b3befb7c" 325 | dependencies = [ 326 | "zerocopy-derive", 327 | ] 328 | 329 | [[package]] 330 | name = "zerocopy-derive" 331 | version = "0.7.33" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "6f4b6c273f496d8fd4eaf18853e6b448760225dc030ff2c485a786859aea6393" 334 | dependencies = [ 335 | "proc-macro2", 336 | "quote", 337 | "syn", 338 | ] 339 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = ["crates/*"] 4 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Embark Studios 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | # `🪞 mirror-mirror` 10 | **Powerful reflection library for Rust** 11 | 12 | [![Embark](https://img.shields.io/badge/embark-open%20source-blueviolet.svg)](https://embark.dev) 13 | [![Embark](https://img.shields.io/badge/discord-ark-%237289da.svg?logo=discord)](https://discord.gg/dAuKfZS) 14 | [![Crates.io](https://img.shields.io/crates/v/mirror-mirror.svg)](https://crates.io/crates/mirror-mirror) 15 | [![Docs](https://docs.rs/mirror-mirror/badge.svg)](https://docs.rs/mirror-mirror) 16 | [![Git Docs](https://img.shields.io/badge/git%20main%20docs-published-blue)](https://embarkstudios.github.io/presser/presser/index.html) 17 | [![dependency status](https://deps.rs/repo/github/EmbarkStudios/mirror-mirror/status.svg)](https://deps.rs/repo/github/EmbarkStudios/mirror-mirror) 18 | [![Build status](https://github.com/EmbarkStudios/physx-rs/workflows/CI/badge.svg)](https://github.com/EmbarkStudios/physx-rs/actions) 19 |
20 | 21 | ## Contributing 22 | 23 | [![Contributor Covenant](https://img.shields.io/badge/contributor%20covenant-v1.4-ff69b4.svg)](CODE_OF_CONDUCT.md) 24 | 25 | We welcome community contributions to this project. 26 | 27 | Please read our [Contributor Guide](CONTRIBUTING.md) for more information on how to get started. 28 | Please also read our [Contributor Terms](CONTRIBUTING.md#contributor-terms) before you make any contributions. 29 | 30 | Any contribution intentionally submitted for inclusion in an Embark Studios project, shall comply with the Rust standard licensing model (MIT OR Apache 2.0) and therefore be dual licensed as described below, without any additional terms or conditions: 31 | 32 | ### License 33 | 34 | This contribution is dual licensed under EITHER OF 35 | 36 | - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ) 37 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 38 | 39 | at your option. 40 | 41 | For clarity, "your" refers to Embark or any other licensee/user of the contribution. 42 | -------------------------------------------------------------------------------- /crates/mirror-mirror-macros/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mirror-mirror-macros" 3 | version = "0.2.0-rc.1" # remember to bump the version `mirror-mirror` depends on 4 | edition = "2021" 5 | authors = ["Embark ", "David Pedersen "] 6 | repository = "https://github.com/EmbarkStudios/mirror-mirror" 7 | homepage = "https://github.com/EmbarkStudios/mirror-mirror" 8 | license = "MIT OR Apache-2.0" 9 | rust-version = "1.65" 10 | description = "Macros for the mirror-mirror crate" 11 | 12 | [lib] 13 | proc-macro = true 14 | 15 | [dependencies] 16 | kollect = { version = "0.5", default-features = false } 17 | proc-macro2 = "1.0.47" 18 | quote = "1.0.21" 19 | syn = { version = "2.0.2", features = ["full", "parsing", "visit"] } 20 | 21 | [dev-dependencies] 22 | mirror-mirror = { path = "../mirror-mirror", version = "0.2.0-rc.1", default-features = false } 23 | 24 | [package.metadata.docs.rs] 25 | all-features = true 26 | rustdoc-args = ["--cfg", "docsrs"] 27 | -------------------------------------------------------------------------------- /crates/mirror-mirror-macros/src/derive_reflect/mod.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use quote::quote_spanned; 3 | use syn::spanned::Spanned; 4 | use syn::DeriveInput; 5 | use syn::ImplGenerics; 6 | use syn::TypeGenerics; 7 | use syn::WhereClause; 8 | 9 | mod attrs; 10 | mod enum_; 11 | mod struct_named; 12 | mod tuple_struct; 13 | 14 | struct Generics<'a> { 15 | impl_generics: ImplGenerics<'a>, 16 | type_generics: TypeGenerics<'a>, 17 | where_clause: Option<&'a WhereClause>, 18 | } 19 | 20 | pub(crate) fn expand(item: DeriveInput) -> syn::Result { 21 | let (impl_generics, type_generics, where_clause) = item.generics.split_for_impl(); 22 | let generics = Generics { 23 | impl_generics, 24 | type_generics, 25 | where_clause, 26 | }; 27 | 28 | let ident = &item.ident; 29 | let span = item.span(); 30 | let attrs = attrs::ItemAttrs::parse(&item.attrs)?; 31 | let crate_name = attrs.crate_name.clone(); 32 | 33 | let tokens = match item.data { 34 | syn::Data::Struct(data) => match data.fields { 35 | syn::Fields::Named(named) => struct_named::expand(ident, named, attrs, &generics)?, 36 | syn::Fields::Unnamed(unnamed) => { 37 | tuple_struct::expand(ident, unnamed, attrs, &generics)? 38 | } 39 | // bevy_reflect only implements `Struct` for unit structs, not `TupleStruct` 40 | // so lets just do the same here 41 | syn::Fields::Unit => struct_named::expand( 42 | ident, 43 | syn::FieldsNamed { 44 | brace_token: Default::default(), 45 | named: Default::default(), 46 | }, 47 | attrs, 48 | &generics, 49 | )?, 50 | }, 51 | syn::Data::Enum(enum_) => enum_::expand(ident, enum_, attrs, &generics)?, 52 | syn::Data::Union(_) => { 53 | return Err(syn::Error::new( 54 | span, 55 | "`#[derive(Reflect)]` doesn't support unions", 56 | )) 57 | } 58 | }; 59 | 60 | let Generics { 61 | impl_generics, 62 | type_generics, 63 | where_clause, 64 | } = generics; 65 | 66 | Ok(quote_spanned! {span=> 67 | #[allow( 68 | clippy::implicit_clone, 69 | clippy::redundant_clone, 70 | clippy::clone_on_copy, 71 | unused_variables, 72 | )] 73 | const _: () = { 74 | 75 | #[allow(unused_imports)] 76 | use #crate_name::*; 77 | #[allow(unused_imports)] 78 | use #crate_name::__private::*; 79 | 80 | #tokens 81 | 82 | impl #impl_generics From<#ident #type_generics> for Value #where_clause { 83 | fn from(data: #ident #type_generics) -> Value { 84 | data.to_value() 85 | } 86 | } 87 | }; 88 | }) 89 | } 90 | 91 | fn trivial_reflect_methods() -> TokenStream { 92 | quote::quote! { 93 | fn as_any(&self) -> &dyn Any { 94 | self 95 | } 96 | 97 | fn as_any_mut(&mut self) -> &mut dyn Any { 98 | self 99 | } 100 | 101 | fn as_reflect(&self) -> &dyn Reflect { 102 | self 103 | } 104 | 105 | fn as_reflect_mut(&mut self) -> &mut dyn Reflect { 106 | self 107 | } 108 | 109 | fn into_any(self: Box) -> Box { 110 | self 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /crates/mirror-mirror-macros/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn( 2 | clippy::all, 3 | clippy::dbg_macro, 4 | clippy::todo, 5 | clippy::empty_enum, 6 | clippy::enum_glob_use, 7 | clippy::mem_forget, 8 | clippy::unused_self, 9 | clippy::filter_map_next, 10 | clippy::needless_continue, 11 | clippy::needless_borrow, 12 | clippy::match_wildcard_for_single_variants, 13 | clippy::if_let_mutex, 14 | clippy::await_holding_lock, 15 | clippy::match_on_vec_items, 16 | clippy::imprecise_flops, 17 | clippy::suboptimal_flops, 18 | clippy::lossy_float_literal, 19 | clippy::rest_pat_in_fully_bound_structs, 20 | clippy::fn_params_excessive_bools, 21 | clippy::exit, 22 | clippy::inefficient_to_string, 23 | clippy::linkedlist, 24 | clippy::macro_use_imports, 25 | clippy::option_option, 26 | clippy::verbose_file_reads, 27 | clippy::unnested_or_patterns, 28 | clippy::str_to_string, 29 | rust_2018_idioms, 30 | future_incompatible, 31 | nonstandard_style, 32 | missing_debug_implementations, 33 | // missing_docs 34 | )] 35 | #![deny(unreachable_pub)] 36 | #![allow(elided_lifetimes_in_paths, clippy::type_complexity)] 37 | #![forbid(unsafe_code)] 38 | #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))] 39 | #![cfg_attr(test, allow(clippy::float_cmp))] 40 | 41 | extern crate alloc; 42 | 43 | use proc_macro::TokenStream; 44 | use quote::quote; 45 | use quote::ToTokens; 46 | use syn::parse::Parse; 47 | 48 | mod derive_reflect; 49 | 50 | /// Derive an implementation of `Reflect` and other appropriate traits. 51 | /// 52 | /// # Structs 53 | /// 54 | /// On structs `#[derive(Reflect)]` will also derive `Struct` and `FromReflect`. 55 | /// 56 | /// ``` 57 | /// use mirror_mirror::Reflect; 58 | /// 59 | /// #[derive(Reflect, Clone, Debug, Default)] 60 | /// struct Foo { 61 | /// a: i32, 62 | /// b: bool, 63 | /// c: String, 64 | /// } 65 | /// ``` 66 | /// 67 | /// Unit structs are treated as tuple structs with no fields. 68 | /// 69 | /// # Tuple structs 70 | /// 71 | /// On tuple structs `#[derive(Reflect)]` will also derive `TupleStruct` and `FromReflect`. 72 | /// 73 | /// ``` 74 | /// use mirror_mirror::Reflect; 75 | /// 76 | /// #[derive(Reflect, Clone, Debug, Default)] 77 | /// struct Foo(i32, bool, String); 78 | /// ``` 79 | /// 80 | /// # Enums 81 | /// 82 | /// On enums `#[derive(Reflect)]` will also derive `Enum` and `FromReflect`. 83 | /// 84 | /// ``` 85 | /// use mirror_mirror::Reflect; 86 | /// 87 | /// #[derive(Reflect, Clone, Debug)] 88 | /// #[reflect(opt_out(Default))] 89 | /// enum Foo { 90 | /// A(i32), 91 | /// B { b: bool }, 92 | /// C, 93 | /// } 94 | /// ``` 95 | /// 96 | /// # Options 97 | /// 98 | /// ## `opt_out` 99 | /// 100 | /// By default types are required to implement `Clone`, `Debug`, and `Default`. You can opt-out of these 101 | /// requirements with `#[reflect(opt_out(Clone, Debug, Default))]` 102 | /// 103 | /// ``` 104 | /// use mirror_mirror::Reflect; 105 | /// 106 | /// #[derive(Reflect)] 107 | /// #[reflect(opt_out(Debug, Clone, Default))] 108 | /// struct Foo(i32); 109 | /// ``` 110 | /// 111 | /// This changes the implementation of `Reflect::clone_reflect` and `Reflect::debug` to something 112 | /// that works for any type but is less performant. 113 | /// 114 | /// You can also opt-out of deriving `FromReflect` so you can provide you own implementation: 115 | /// 116 | /// ``` 117 | /// use mirror_mirror::{Reflect, FromReflect}; 118 | /// 119 | /// #[derive(Reflect, Debug, Clone, Default)] 120 | /// #[reflect(opt_out(FromReflect))] 121 | /// struct Foo(i32); 122 | /// 123 | /// impl FromReflect for Foo { 124 | /// fn from_reflect(value: &dyn Reflect) -> Option { 125 | /// Some(Self(*value.downcast_ref::()?)) 126 | /// } 127 | /// } 128 | /// ``` 129 | /// 130 | /// ## `skip` 131 | /// 132 | /// You can exclude fields or variants from being reflected with `#[reflect(skip)]`. The type of the skipped field/variant is 133 | /// required to implement `Default` by the default `FromReflect` implementation. 134 | /// 135 | /// ``` 136 | /// use mirror_mirror::{Reflect, FromReflect}; 137 | /// 138 | /// #[derive(Reflect, Debug, Clone, Default)] 139 | /// struct Foo { 140 | /// #[reflect(skip)] 141 | /// not_reflect: NotReflect, 142 | /// } 143 | /// 144 | /// #[derive(Reflect, Debug, Clone, Default)] 145 | /// struct Bar(#[reflect(skip)] NotReflect); 146 | /// 147 | /// #[derive(Reflect, Debug, Clone)] 148 | /// #[reflect(opt_out(Default))] 149 | /// enum Baz { 150 | /// #[reflect(skip)] 151 | /// OnVariant(NotReflect), 152 | /// 153 | /// OnTupleField(#[reflect(skip)] NotReflect), 154 | /// 155 | /// OnStructField { 156 | /// #[reflect(skip)] 157 | /// not_reflect: NotReflect, 158 | /// } 159 | /// } 160 | /// 161 | /// // A type that isn't compatible with reflection 162 | /// #[derive(Debug, Clone, Default)] 163 | /// struct NotReflect; 164 | /// ``` 165 | /// 166 | /// ## `from_reflect_with` 167 | /// 168 | /// You can override `FromReflect` for a single field by specifying a function to do the 169 | /// conversion: 170 | /// 171 | /// ``` 172 | /// use mirror_mirror::{Reflect, FromReflect}; 173 | /// 174 | /// #[derive(Reflect, Debug, Clone, Default)] 175 | /// struct Foo { 176 | /// #[reflect(from_reflect_with(n_from_reflect))] 177 | /// n: i32, 178 | /// } 179 | /// 180 | /// fn n_from_reflect(field: &dyn Reflect) -> Option { 181 | /// Some(*field.downcast_ref::()?) 182 | /// } 183 | /// ``` 184 | /// 185 | /// ## `meta` 186 | /// 187 | /// Metadata associated with types or enum variants can be added with `#[reflect(meta(...))]` 188 | /// 189 | /// ``` 190 | /// use mirror_mirror::{ 191 | /// Reflect, 192 | /// key_path, 193 | /// key_path::GetTypePath, 194 | /// FromReflect, 195 | /// type_info::{GetMeta, DescribeType}, 196 | /// }; 197 | /// 198 | /// #[derive(Reflect, Debug, Clone, Default)] 199 | /// #[reflect(meta( 200 | /// // a comma separated list of `key = value` pairs. 201 | /// // 202 | /// // `key` must be an identifier and `value` can be anything that 203 | /// // implements `Reflect` 204 | /// item_key = "item value", 205 | /// ))] 206 | /// struct Foo { 207 | /// #[reflect(meta(field_key = 1337))] 208 | /// n: i32, 209 | /// } 210 | /// 211 | /// // Access the metadata through the type information 212 | /// let type_info = ::type_descriptor(); 213 | /// 214 | /// assert_eq!( 215 | /// type_info.get_meta::("item_key").unwrap(), 216 | /// "item value", 217 | /// ); 218 | /// 219 | /// assert_eq!( 220 | /// type_info 221 | /// .as_struct() 222 | /// .unwrap() 223 | /// .field_type("n") 224 | /// .unwrap() 225 | /// .get_meta::("field_key") 226 | /// .unwrap(), 227 | /// 1337, 228 | /// ); 229 | /// ``` 230 | /// 231 | /// ## `crate_name` 232 | /// 233 | /// You can specify a "use path" for `mirror_mirror` with `crate_name`. This is useful if you're 234 | /// using a library that re-exports `mirror_mirror`'s derive macro: 235 | /// 236 | /// ``` 237 | /// # use mirror_mirror as some_library; 238 | /// use some_library::Reflect; 239 | /// 240 | /// #[derive(Reflect, Debug, Clone, Default)] 241 | /// #[reflect(crate_name(some_library))] 242 | /// struct Foo { 243 | /// n: i32, 244 | /// } 245 | /// ``` 246 | /// 247 | /// This causes the macro generate paths like `some_library::FromReflect`. 248 | /// 249 | /// [`Reflect`]: crate::Reflect 250 | #[proc_macro_derive(Reflect, attributes(reflect))] 251 | pub fn derive_reflect(item: TokenStream) -> TokenStream { 252 | expand_with(item, derive_reflect::expand) 253 | } 254 | 255 | /// Private API: Do not use! 256 | #[proc_macro] 257 | #[doc(hidden)] 258 | pub fn __private_derive_reflect_foreign(item: TokenStream) -> TokenStream { 259 | expand_with(item, derive_reflect::expand) 260 | } 261 | 262 | fn expand_with(input: TokenStream, f: F) -> TokenStream 263 | where 264 | F: FnOnce(I) -> syn::Result, 265 | I: Parse, 266 | K: ToTokens, 267 | { 268 | expand(syn::parse(input).and_then(f)) 269 | } 270 | 271 | fn expand(result: syn::Result) -> TokenStream 272 | where 273 | T: ToTokens, 274 | { 275 | match result { 276 | Ok(tokens) => quote! { #tokens }.into(), 277 | Err(err) => err.into_compile_error().into(), 278 | } 279 | } 280 | 281 | fn stringify(token: T) -> Stringify { 282 | Stringify(token) 283 | } 284 | 285 | struct Stringify(T); 286 | 287 | impl ToTokens for Stringify 288 | where 289 | T: ToTokens, 290 | { 291 | fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { 292 | let token = &self.0; 293 | tokens.extend(quote::quote! { 294 | ::core::stringify!(#token) 295 | }) 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /crates/mirror-mirror/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mirror-mirror" 3 | version = "0.2.0-rc.1" # remember to bump the version mirror-mirror-macros depends on 4 | edition = "2021" 5 | authors = ["Embark ", "David Pedersen "] 6 | repository = "https://github.com/EmbarkStudios/mirror-mirror" 7 | homepage = "https://github.com/EmbarkStudios/mirror-mirror" 8 | license = "MIT OR Apache-2.0" 9 | readme = "../../README.md" 10 | rust-version = "1.65" 11 | description = "Reflection library for Rust" 12 | keywords = ["reflection"] 13 | 14 | [features] 15 | default = ["speedy", "serde", "simple_type_name","glam","macaw"] 16 | simple_type_name = ["dep:syn"] 17 | speedy = ["dep:speedy", "kollect/speedy", "glam/speedy"] 18 | serde = ["dep:serde", "kollect/serde"] 19 | glam = ["dep:glam"] 20 | glam-scalar-math = ["glam/scalar-math"] 21 | macaw = ["dep:macaw"] 22 | 23 | [dependencies] 24 | ahash = { version = "0.8.2", default-features = false, features = [ 25 | # required for wasm support 26 | "no-rng", 27 | ] } 28 | kollect = { version = "0.5", default-features = false } 29 | mirror-mirror-macros = { path = "../mirror-mirror-macros", version = "0.2.0-rc.1" } 30 | once_cell = { version = "1.16", features = ["alloc", "race", "critical-section"], default-features = false } 31 | tiny-ordered-float = { version = "0.4", default-features = false } 32 | serde = { version = "1.0.158", default-features = false, features = ["derive", "alloc"], optional = true } 33 | speedy = { version = "0.8", optional = true } 34 | syn = { version = "2.0", features = ["full", "parsing"], optional = true } 35 | glam = { version = ">= 0.28, <= 0.30", optional = true } 36 | macaw = { version = "0.30", optional = true } 37 | 38 | [dev-dependencies] 39 | mirror-mirror-1 = { package = "mirror-mirror", version = "0.1" } 40 | ron = "0.8.1" 41 | 42 | [package.metadata.docs.rs] 43 | all-features = true 44 | rustdoc-args = ["--cfg", "docsrs"] 45 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/array.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | use core::iter::FusedIterator; 3 | 4 | use crate::iter::ValueIterMut; 5 | use crate::Reflect; 6 | 7 | /// A reflected array type. 8 | pub trait Array: Reflect { 9 | fn get(&self, index: usize) -> Option<&dyn Reflect>; 10 | 11 | fn get_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>; 12 | 13 | fn len(&self) -> usize; 14 | 15 | fn is_empty(&self) -> bool; 16 | 17 | fn iter(&self) -> Iter<'_>; 18 | 19 | fn iter_mut(&mut self) -> ValueIterMut<'_>; 20 | 21 | /// Swaps two elements in the array. 22 | /// 23 | /// # Panics 24 | /// 25 | /// Panics if `a` or `b` are out of bounds. 26 | fn swap(&mut self, a: usize, b: usize); 27 | } 28 | 29 | impl fmt::Debug for dyn Array { 30 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 31 | self.as_reflect().debug(f) 32 | } 33 | } 34 | 35 | #[derive(Debug)] 36 | pub struct Iter<'a> { 37 | index: usize, 38 | array: &'a dyn Array, 39 | } 40 | 41 | impl<'a> Iter<'a> { 42 | pub fn new(array: &'a dyn Array) -> Self { 43 | Self { index: 0, array } 44 | } 45 | } 46 | 47 | impl<'a> Iterator for Iter<'a> { 48 | type Item = &'a dyn Reflect; 49 | 50 | fn next(&mut self) -> Option { 51 | let value = self.array.get(self.index)?; 52 | self.index += 1; 53 | Some(value) 54 | } 55 | } 56 | 57 | impl ExactSizeIterator for Iter<'_> { 58 | fn len(&self) -> usize { 59 | self.array.len() 60 | } 61 | } 62 | 63 | impl FusedIterator for Iter<'_> {} 64 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/array.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use alloc::vec::Vec; 3 | use core::any::Any; 4 | use core::fmt; 5 | 6 | use crate::array::Array; 7 | use crate::iter::ValueIterMut; 8 | use crate::type_info::graph::ArrayNode; 9 | use crate::type_info::graph::NodeId; 10 | use crate::type_info::graph::TypeGraph; 11 | use crate::DescribeType; 12 | use crate::FromReflect; 13 | use crate::Reflect; 14 | use crate::ReflectMut; 15 | use crate::ReflectOwned; 16 | use crate::ReflectRef; 17 | use crate::Value; 18 | 19 | impl DescribeType for [T; N] 20 | where 21 | T: DescribeType, 22 | { 23 | fn build(graph: &mut TypeGraph) -> NodeId { 24 | graph.get_or_build_node_with::(|graph| ArrayNode::new::(graph)) 25 | } 26 | } 27 | 28 | impl Reflect for [T; N] 29 | where 30 | T: FromReflect + DescribeType, 31 | { 32 | trivial_reflect_methods!(); 33 | 34 | fn reflect_owned(self: Box) -> ReflectOwned { 35 | ReflectOwned::Array(self) 36 | } 37 | 38 | fn reflect_ref(&self) -> ReflectRef<'_> { 39 | ReflectRef::Array(self) 40 | } 41 | 42 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 43 | ReflectMut::Array(self) 44 | } 45 | 46 | fn patch(&mut self, value: &dyn Reflect) { 47 | if let Some(array) = value.reflect_ref().as_array() { 48 | for (idx, new_value) in array.iter().enumerate() { 49 | if let Some(value) = self.get_mut(idx) { 50 | value.patch(new_value); 51 | } 52 | } 53 | } 54 | } 55 | 56 | fn to_value(&self) -> Value { 57 | let data = self.iter().map(Reflect::to_value).collect(); 58 | Value::List(data) 59 | } 60 | 61 | fn clone_reflect(&self) -> Box { 62 | let value = self.to_value(); 63 | Box::new(Self::from_reflect(&value).unwrap()) 64 | } 65 | 66 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 67 | f.debug_list().entries(self.iter()).finish() 68 | } 69 | } 70 | 71 | impl Array for [T; N] 72 | where 73 | T: FromReflect + DescribeType, 74 | { 75 | fn get(&self, index: usize) -> Option<&dyn Reflect> { 76 | self.as_slice().get(index).map(|value| value.as_reflect()) 77 | } 78 | 79 | fn get_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 80 | self.as_mut_slice() 81 | .get_mut(index) 82 | .map(|value| value.as_reflect_mut()) 83 | } 84 | 85 | fn len(&self) -> usize { 86 | N 87 | } 88 | 89 | fn is_empty(&self) -> bool { 90 | N == 0 91 | } 92 | 93 | fn iter(&self) -> crate::array::Iter<'_> { 94 | crate::array::Iter::new(self) 95 | } 96 | 97 | fn iter_mut(&mut self) -> ValueIterMut<'_> { 98 | let iter = self 99 | .as_mut_slice() 100 | .iter_mut() 101 | .map(|value| value.as_reflect_mut()); 102 | Box::new(iter) 103 | } 104 | 105 | fn swap(&mut self, a: usize, b: usize) { 106 | self.as_mut_slice().swap(a, b); 107 | } 108 | } 109 | 110 | impl FromReflect for [T; N] 111 | where 112 | T: FromReflect + DescribeType, 113 | { 114 | fn from_reflect(reflect: &dyn Reflect) -> Option { 115 | Vec::::from_reflect(reflect)?.try_into().ok() 116 | } 117 | } 118 | 119 | impl From<[T; N]> for Value 120 | where 121 | T: Reflect, 122 | { 123 | fn from(list: [T; N]) -> Self { 124 | let list = list 125 | .iter() 126 | .map(|value| value.to_value()) 127 | .collect::>(); 128 | Value::List(list) 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/boxed.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use core::any::Any; 3 | use core::fmt; 4 | 5 | use crate::reflect_debug; 6 | use crate::type_info::graph::NodeId; 7 | use crate::type_info::graph::TypeGraph; 8 | use crate::DescribeType; 9 | use crate::FromReflect; 10 | use crate::Reflect; 11 | use crate::ReflectMut; 12 | use crate::ReflectOwned; 13 | use crate::ReflectRef; 14 | use crate::Value; 15 | 16 | impl DescribeType for Box 17 | where 18 | T: DescribeType, 19 | { 20 | fn build(graph: &mut TypeGraph) -> NodeId { 21 | T::build(graph) 22 | } 23 | } 24 | 25 | impl Reflect for Box 26 | where 27 | T: Reflect + DescribeType, 28 | { 29 | fn as_any(&self) -> &dyn Any { 30 | ::as_any(self) 31 | } 32 | 33 | fn as_any_mut(&mut self) -> &mut dyn Any { 34 | ::as_any_mut(self) 35 | } 36 | 37 | fn into_any(self: Box) -> Box { 38 | ::into_any(*self) 39 | } 40 | 41 | fn as_reflect(&self) -> &dyn Reflect { 42 | ::as_reflect(self) 43 | } 44 | 45 | fn as_reflect_mut(&mut self) -> &mut dyn Reflect { 46 | ::as_reflect_mut(self) 47 | } 48 | 49 | fn reflect_owned(self: Box) -> ReflectOwned { 50 | ::reflect_owned(*self) 51 | } 52 | 53 | fn reflect_ref(&self) -> ReflectRef<'_> { 54 | ::reflect_ref(self) 55 | } 56 | 57 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 58 | ::reflect_mut(self) 59 | } 60 | 61 | fn patch(&mut self, value: &dyn Reflect) { 62 | ::patch(self, value) 63 | } 64 | 65 | fn to_value(&self) -> Value { 66 | ::to_value(self) 67 | } 68 | 69 | fn clone_reflect(&self) -> Box { 70 | ::clone_reflect(self) 71 | } 72 | 73 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 74 | reflect_debug(self, f) 75 | } 76 | } 77 | 78 | impl FromReflect for Box 79 | where 80 | T: FromReflect + DescribeType, 81 | { 82 | fn from_reflect(reflect: &dyn Reflect) -> Option { 83 | Some(Box::new(T::from_reflect(reflect)?)) 84 | } 85 | } 86 | 87 | impl From> for Value 88 | where 89 | T: Into, 90 | { 91 | fn from(boxed: Box) -> Self { 92 | (*boxed).into() 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/btree_map.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use alloc::collections::BTreeMap; 3 | use core::any::Any; 4 | use core::fmt; 5 | 6 | use crate::iter::PairIterMut; 7 | use crate::map::MapError; 8 | use crate::type_info::graph::MapNode; 9 | use crate::type_info::graph::NodeId; 10 | use crate::type_info::graph::TypeGraph; 11 | use crate::DescribeType; 12 | use crate::FromReflect; 13 | use crate::Map; 14 | use crate::Reflect; 15 | use crate::ReflectMut; 16 | use crate::ReflectOwned; 17 | use crate::ReflectRef; 18 | use crate::Value; 19 | 20 | impl Map for BTreeMap 21 | where 22 | K: FromReflect + DescribeType + Ord, 23 | V: FromReflect + DescribeType, 24 | { 25 | map_methods!(); 26 | } 27 | 28 | impl DescribeType for BTreeMap 29 | where 30 | K: DescribeType, 31 | V: DescribeType, 32 | { 33 | fn build(graph: &mut TypeGraph) -> NodeId { 34 | graph.get_or_build_node_with::(|graph| MapNode::new::(graph)) 35 | } 36 | } 37 | 38 | impl Reflect for BTreeMap 39 | where 40 | K: FromReflect + DescribeType + Ord, 41 | V: FromReflect + DescribeType, 42 | { 43 | trivial_reflect_methods!(); 44 | 45 | fn reflect_owned(self: Box) -> ReflectOwned { 46 | ReflectOwned::Map(self) 47 | } 48 | 49 | fn reflect_ref(&self) -> ReflectRef<'_> { 50 | ReflectRef::Map(self) 51 | } 52 | 53 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 54 | ReflectMut::Map(self) 55 | } 56 | 57 | fn patch(&mut self, value: &dyn Reflect) { 58 | if let Some(map) = value.reflect_ref().as_map() { 59 | for (key, new_value) in map.iter() { 60 | if let Some(value) = Map::get_mut(self, key) { 61 | value.patch(new_value); 62 | } 63 | } 64 | } 65 | } 66 | 67 | fn to_value(&self) -> Value { 68 | let data = self 69 | .iter() 70 | .map(|(key, value)| (key.to_value(), value.to_value())) 71 | .collect(); 72 | Value::Map(data) 73 | } 74 | 75 | fn clone_reflect(&self) -> Box { 76 | let value = self.to_value(); 77 | Box::new(Self::from_reflect(&value).unwrap()) 78 | } 79 | 80 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 81 | f.debug_map().entries(Map::iter(self)).finish() 82 | } 83 | } 84 | 85 | impl FromReflect for BTreeMap 86 | where 87 | K: FromReflect + DescribeType + Ord, 88 | V: FromReflect + DescribeType, 89 | { 90 | fn from_reflect(reflect: &dyn Reflect) -> Option { 91 | let map = reflect.as_map()?; 92 | let mut out = BTreeMap::new(); 93 | for (key, value) in map.iter() { 94 | out.insert(K::from_reflect(key)?, V::from_reflect(value)?); 95 | } 96 | Some(out) 97 | } 98 | } 99 | 100 | impl From> for Value 101 | where 102 | K: Reflect, 103 | V: Reflect, 104 | { 105 | fn from(map: BTreeMap) -> Self { 106 | let map = map 107 | .into_iter() 108 | .map(|(key, value)| (key.to_value(), value.to_value())) 109 | .collect(); 110 | Value::Map(map) 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/glam.rs: -------------------------------------------------------------------------------- 1 | use glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; 2 | use mirror_mirror_macros::__private_derive_reflect_foreign; 3 | 4 | mod mat2; 5 | mod quat; 6 | mod vec4; 7 | 8 | __private_derive_reflect_foreign! { 9 | #[reflect(crate_name(crate))] 10 | pub struct Vec2 { 11 | pub x: f32, 12 | pub y: f32, 13 | } 14 | } 15 | 16 | __private_derive_reflect_foreign! { 17 | #[reflect(crate_name(crate))] 18 | pub struct Vec3 { 19 | pub x: f32, 20 | pub y: f32, 21 | pub z: f32, 22 | } 23 | } 24 | 25 | __private_derive_reflect_foreign! { 26 | #[reflect(crate_name(crate))] 27 | pub struct Mat3 { 28 | pub x_axis: Vec3, 29 | pub y_axis: Vec3, 30 | pub z_axis: Vec3, 31 | } 32 | } 33 | 34 | __private_derive_reflect_foreign! { 35 | #[reflect(crate_name(crate))] 36 | pub struct Mat4 { 37 | pub x_axis: Vec4, 38 | pub y_axis: Vec4, 39 | pub z_axis: Vec4, 40 | pub w_axis: Vec4, 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/glam/mat2.rs: -------------------------------------------------------------------------------- 1 | use glam::{Mat2, Vec2}; 2 | use kollect::LinearMap; 3 | use std::any::Any; 4 | 5 | use crate::{ 6 | struct_::{FieldsIter, FieldsIterMut, StructValue}, 7 | type_info::graph::*, 8 | DefaultValue, DescribeType, FromReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, Struct, 9 | Value, 10 | }; 11 | 12 | impl Reflect for Mat2 { 13 | trivial_reflect_methods!(); 14 | 15 | fn reflect_owned(self: Box) -> ReflectOwned { 16 | ReflectOwned::Struct(self) 17 | } 18 | 19 | fn reflect_ref(&self) -> ReflectRef<'_> { 20 | ReflectRef::Struct(self) 21 | } 22 | 23 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 24 | ReflectMut::Struct(self) 25 | } 26 | 27 | fn patch(&mut self, value: &dyn Reflect) { 28 | if let Some(struct_) = value.as_struct() { 29 | if let Some(x_axis) = struct_.field("x_axis").and_then(<_>::from_reflect) { 30 | self.x_axis = x_axis; 31 | } 32 | if let Some(y_axis) = struct_.field("y_axis").and_then(<_>::from_reflect) { 33 | self.y_axis = y_axis; 34 | } 35 | } 36 | } 37 | 38 | fn to_value(&self) -> Value { 39 | StructValue::with_capacity(2) 40 | .with_field("x_axis", self.x_axis) 41 | .with_field("y_axis", self.y_axis) 42 | .to_value() 43 | } 44 | 45 | fn clone_reflect(&self) -> Box { 46 | Box::new(*self) 47 | } 48 | 49 | fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 50 | if f.alternate() { 51 | write!(f, "{self:#?}") 52 | } else { 53 | write!(f, "{self:?}") 54 | } 55 | } 56 | } 57 | 58 | impl Struct for Mat2 { 59 | fn field(&self, name: &str) -> Option<&dyn Reflect> { 60 | match name { 61 | "x_axis" => Some(&self.x_axis), 62 | "y_axis" => Some(&self.y_axis), 63 | _ => None, 64 | } 65 | } 66 | 67 | fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect> { 68 | match name { 69 | "x_axis" => Some(&mut self.x_axis), 70 | "y_axis" => Some(&mut self.y_axis), 71 | _ => None, 72 | } 73 | } 74 | 75 | fn field_at(&self, index: usize) -> Option<&dyn Reflect> { 76 | match index { 77 | 0 => Some(&self.x_axis), 78 | 1 => Some(&self.y_axis), 79 | _ => None, 80 | } 81 | } 82 | 83 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 84 | match index { 85 | 0 => Some(&mut self.x_axis), 86 | 1 => Some(&mut self.y_axis), 87 | _ => None, 88 | } 89 | } 90 | 91 | fn name_at(&self, index: usize) -> Option<&str> { 92 | match index { 93 | 0 => Some("x_axis"), 94 | 1 => Some("y_axis"), 95 | _ => None, 96 | } 97 | } 98 | 99 | fn fields(&self) -> FieldsIter<'_> { 100 | Box::new( 101 | [ 102 | ("x_axis", self.x_axis.as_reflect()), 103 | ("y_axis", self.y_axis.as_reflect()), 104 | ] 105 | .into_iter(), 106 | ) 107 | } 108 | 109 | fn fields_mut(&mut self) -> FieldsIterMut<'_> { 110 | #[cfg(any( 111 | feature = "glam-scalar-math", 112 | not(any( 113 | target_feature = "sse2", 114 | target_feature = "simd128", 115 | target_arch = "aarch64" 116 | )) 117 | ))] 118 | let repr = self; 119 | 120 | #[cfg(all( 121 | not(feature = "glam-scalar-math"), 122 | any( 123 | target_feature = "sse2", 124 | target_feature = "simd128", 125 | target_arch = "aarch64" 126 | ) 127 | ))] 128 | let repr = &mut **self; 129 | 130 | Box::new( 131 | [ 132 | ("x_axis", repr.x_axis.as_reflect_mut()), 133 | ("y_axis", repr.y_axis.as_reflect_mut()), 134 | ] 135 | .into_iter(), 136 | ) 137 | } 138 | 139 | fn fields_len(&self) -> usize { 140 | 2 141 | } 142 | } 143 | 144 | impl FromReflect for Mat2 { 145 | fn from_reflect(reflect: &dyn Reflect) -> Option { 146 | if let Some(mat) = reflect.downcast_ref() { 147 | Some(*mat) 148 | } else { 149 | let struct_ = reflect.as_struct()?; 150 | let x_axis = <_>::from_reflect(struct_.field("x_axis")?)?; 151 | let y_axis = <_>::from_reflect(struct_.field("y_axis")?)?; 152 | Some(Self::from_cols(x_axis, y_axis)) 153 | } 154 | } 155 | } 156 | 157 | impl DefaultValue for Mat2 { 158 | fn default_value() -> Option { 159 | Some(Self::default().to_value()) 160 | } 161 | } 162 | 163 | impl DescribeType for Mat2 { 164 | fn build(graph: &mut TypeGraph) -> NodeId { 165 | graph.get_or_build_node_with::(|graph| { 166 | let fields = &[ 167 | NamedFieldNode::new::("x_axis", LinearMap::from([]), &[], graph), 168 | NamedFieldNode::new::("y_axis", LinearMap::from([]), &[], graph), 169 | ]; 170 | StructNode::new::(fields, LinearMap::from([]), &[]) 171 | }) 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/glam/quat.rs: -------------------------------------------------------------------------------- 1 | use glam::Quat; 2 | use kollect::LinearMap; 3 | use std::any::Any; 4 | 5 | use crate::{ 6 | struct_::{FieldsIter, FieldsIterMut, StructValue}, 7 | type_info::graph::*, 8 | DefaultValue, DescribeType, FromReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, Struct, 9 | Value, 10 | }; 11 | 12 | impl Reflect for Quat { 13 | trivial_reflect_methods!(); 14 | 15 | fn reflect_owned(self: Box) -> ReflectOwned { 16 | ReflectOwned::Struct(self) 17 | } 18 | 19 | fn reflect_ref(&self) -> ReflectRef<'_> { 20 | ReflectRef::Struct(self) 21 | } 22 | 23 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 24 | ReflectMut::Struct(self) 25 | } 26 | 27 | fn patch(&mut self, value: &dyn Reflect) { 28 | if let Some(struct_) = value.as_struct() { 29 | if let Some(x) = struct_.field("x").and_then(<_>::from_reflect) { 30 | self.x = x; 31 | } 32 | if let Some(y) = struct_.field("y").and_then(<_>::from_reflect) { 33 | self.y = y; 34 | } 35 | if let Some(z) = struct_.field("z").and_then(<_>::from_reflect) { 36 | self.z = z; 37 | } 38 | if let Some(w) = struct_.field("w").and_then(<_>::from_reflect) { 39 | self.w = w; 40 | } 41 | } 42 | } 43 | 44 | fn to_value(&self) -> Value { 45 | StructValue::with_capacity(4) 46 | .with_field("x", self.x) 47 | .with_field("y", self.y) 48 | .with_field("z", self.z) 49 | .with_field("w", self.w) 50 | .to_value() 51 | } 52 | 53 | fn clone_reflect(&self) -> Box { 54 | Box::new(*self) 55 | } 56 | 57 | fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 58 | if f.alternate() { 59 | write!(f, "{self:#?}") 60 | } else { 61 | write!(f, "{self:?}") 62 | } 63 | } 64 | } 65 | 66 | impl Struct for Quat { 67 | fn field(&self, name: &str) -> Option<&dyn Reflect> { 68 | match name { 69 | "x" => Some(&self.x), 70 | "y" => Some(&self.y), 71 | "z" => Some(&self.z), 72 | "w" => Some(&self.w), 73 | _ => None, 74 | } 75 | } 76 | 77 | fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect> { 78 | match name { 79 | "x" => Some(&mut self.x), 80 | "y" => Some(&mut self.y), 81 | "z" => Some(&mut self.z), 82 | "w" => Some(&mut self.w), 83 | _ => None, 84 | } 85 | } 86 | 87 | fn field_at(&self, index: usize) -> Option<&dyn Reflect> { 88 | match index { 89 | 0 => Some(&self.x), 90 | 1 => Some(&self.y), 91 | 2 => Some(&self.z), 92 | 3 => Some(&self.w), 93 | _ => None, 94 | } 95 | } 96 | 97 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 98 | match index { 99 | 0 => Some(&mut self.x), 100 | 1 => Some(&mut self.y), 101 | 2 => Some(&mut self.z), 102 | 3 => Some(&mut self.w), 103 | _ => None, 104 | } 105 | } 106 | 107 | fn name_at(&self, index: usize) -> Option<&str> { 108 | match index { 109 | 0 => Some("x"), 110 | 1 => Some("y"), 111 | 2 => Some("z"), 112 | 3 => Some("w"), 113 | _ => None, 114 | } 115 | } 116 | 117 | fn fields(&self) -> FieldsIter<'_> { 118 | Box::new( 119 | [ 120 | ("x", self.x.as_reflect()), 121 | ("y", self.y.as_reflect()), 122 | ("z", self.z.as_reflect()), 123 | ("w", self.w.as_reflect()), 124 | ] 125 | .into_iter(), 126 | ) 127 | } 128 | 129 | fn fields_mut(&mut self) -> FieldsIterMut<'_> { 130 | #[cfg(any( 131 | feature = "glam-scalar-math", 132 | not(any( 133 | target_feature = "sse2", 134 | target_feature = "simd128", 135 | target_arch = "aarch64" 136 | )) 137 | ))] 138 | let repr = self; 139 | 140 | #[cfg(all( 141 | not(feature = "glam-scalar-math"), 142 | any( 143 | target_feature = "sse2", 144 | target_feature = "simd128", 145 | target_arch = "aarch64" 146 | ) 147 | ))] 148 | let repr = &mut **self; 149 | 150 | Box::new( 151 | [ 152 | ("x", repr.x.as_reflect_mut()), 153 | ("y", repr.y.as_reflect_mut()), 154 | ("z", repr.z.as_reflect_mut()), 155 | ("w", repr.w.as_reflect_mut()), 156 | ] 157 | .into_iter(), 158 | ) 159 | } 160 | 161 | fn fields_len(&self) -> usize { 162 | 4 163 | } 164 | } 165 | 166 | impl FromReflect for Quat { 167 | fn from_reflect(reflect: &dyn Reflect) -> Option { 168 | if let Some(quat) = reflect.downcast_ref() { 169 | Some(*quat) 170 | } else { 171 | let struct_ = reflect.as_struct()?; 172 | let x = <_>::from_reflect(struct_.field("x")?)?; 173 | let y = <_>::from_reflect(struct_.field("y")?)?; 174 | let z = <_>::from_reflect(struct_.field("z")?)?; 175 | let w = <_>::from_reflect(struct_.field("w")?)?; 176 | Some(Self::from_xyzw(x, y, z, w)) 177 | } 178 | } 179 | } 180 | 181 | impl DefaultValue for Quat { 182 | fn default_value() -> Option { 183 | Some(Self::default().to_value()) 184 | } 185 | } 186 | 187 | impl DescribeType for Quat { 188 | fn build(graph: &mut TypeGraph) -> NodeId { 189 | graph.get_or_build_node_with::(|graph| { 190 | let fields = &[ 191 | NamedFieldNode::new::("x", LinearMap::from([]), &[], graph), 192 | NamedFieldNode::new::("y", LinearMap::from([]), &[], graph), 193 | NamedFieldNode::new::("z", LinearMap::from([]), &[], graph), 194 | NamedFieldNode::new::("w", LinearMap::from([]), &[], graph), 195 | ]; 196 | StructNode::new::(fields, LinearMap::from([]), &[]) 197 | }) 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/glam/vec4.rs: -------------------------------------------------------------------------------- 1 | use glam::Vec4; 2 | use kollect::LinearMap; 3 | use std::any::Any; 4 | 5 | use crate::{ 6 | struct_::{FieldsIter, FieldsIterMut, StructValue}, 7 | type_info::graph::*, 8 | DefaultValue, DescribeType, FromReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, Struct, 9 | Value, 10 | }; 11 | 12 | impl Reflect for Vec4 { 13 | trivial_reflect_methods!(); 14 | 15 | fn reflect_owned(self: Box) -> ReflectOwned { 16 | ReflectOwned::Struct(self) 17 | } 18 | 19 | fn reflect_ref(&self) -> ReflectRef<'_> { 20 | ReflectRef::Struct(self) 21 | } 22 | 23 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 24 | ReflectMut::Struct(self) 25 | } 26 | 27 | fn patch(&mut self, value: &dyn Reflect) { 28 | if let Some(struct_) = value.as_struct() { 29 | if let Some(x) = struct_.field("x").and_then(<_>::from_reflect) { 30 | self.x = x; 31 | } 32 | if let Some(y) = struct_.field("y").and_then(<_>::from_reflect) { 33 | self.y = y; 34 | } 35 | if let Some(z) = struct_.field("z").and_then(<_>::from_reflect) { 36 | self.z = z; 37 | } 38 | if let Some(w) = struct_.field("w").and_then(<_>::from_reflect) { 39 | self.w = w; 40 | } 41 | } 42 | } 43 | 44 | fn to_value(&self) -> Value { 45 | StructValue::with_capacity(4) 46 | .with_field("x", self.x) 47 | .with_field("y", self.y) 48 | .with_field("z", self.z) 49 | .with_field("w", self.w) 50 | .to_value() 51 | } 52 | 53 | fn clone_reflect(&self) -> Box { 54 | Box::new(*self) 55 | } 56 | 57 | fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 58 | if f.alternate() { 59 | write!(f, "{self:#?}") 60 | } else { 61 | write!(f, "{self:?}") 62 | } 63 | } 64 | } 65 | 66 | impl Struct for Vec4 { 67 | fn field(&self, name: &str) -> Option<&dyn Reflect> { 68 | match name { 69 | "x" => Some(&self.x), 70 | "y" => Some(&self.y), 71 | "z" => Some(&self.z), 72 | "w" => Some(&self.w), 73 | _ => None, 74 | } 75 | } 76 | 77 | fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect> { 78 | match name { 79 | "x" => Some(&mut self.x), 80 | "y" => Some(&mut self.y), 81 | "z" => Some(&mut self.z), 82 | "w" => Some(&mut self.w), 83 | _ => None, 84 | } 85 | } 86 | 87 | fn field_at(&self, index: usize) -> Option<&dyn Reflect> { 88 | match index { 89 | 0 => Some(&self.x), 90 | 1 => Some(&self.y), 91 | 2 => Some(&self.z), 92 | 3 => Some(&self.w), 93 | _ => None, 94 | } 95 | } 96 | 97 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 98 | match index { 99 | 0 => Some(&mut self.x), 100 | 1 => Some(&mut self.y), 101 | 2 => Some(&mut self.z), 102 | 3 => Some(&mut self.w), 103 | _ => None, 104 | } 105 | } 106 | 107 | fn name_at(&self, index: usize) -> Option<&str> { 108 | match index { 109 | 0 => Some("x"), 110 | 1 => Some("y"), 111 | 2 => Some("z"), 112 | 3 => Some("w"), 113 | _ => None, 114 | } 115 | } 116 | 117 | fn fields(&self) -> FieldsIter<'_> { 118 | Box::new( 119 | [ 120 | ("x", self.x.as_reflect()), 121 | ("y", self.y.as_reflect()), 122 | ("z", self.z.as_reflect()), 123 | ("w", self.w.as_reflect()), 124 | ] 125 | .into_iter(), 126 | ) 127 | } 128 | 129 | fn fields_mut(&mut self) -> FieldsIterMut<'_> { 130 | let [x, y, z, w] = self.as_mut(); 131 | Box::new( 132 | [ 133 | ("x", x.as_reflect_mut()), 134 | ("y", y.as_reflect_mut()), 135 | ("z", z.as_reflect_mut()), 136 | ("w", w.as_reflect_mut()), 137 | ] 138 | .into_iter(), 139 | ) 140 | } 141 | 142 | fn fields_len(&self) -> usize { 143 | 4 144 | } 145 | } 146 | 147 | impl FromReflect for Vec4 { 148 | fn from_reflect(reflect: &dyn Reflect) -> Option { 149 | if let Some(vec) = reflect.downcast_ref() { 150 | Some(*vec) 151 | } else { 152 | let struct_ = reflect.as_struct()?; 153 | let components = ( 154 | <_>::from_reflect(struct_.field("x")?)?, 155 | <_>::from_reflect(struct_.field("y")?)?, 156 | <_>::from_reflect(struct_.field("z")?)?, 157 | <_>::from_reflect(struct_.field("w")?)?, 158 | ); 159 | Some(components.into()) 160 | } 161 | } 162 | } 163 | 164 | impl DefaultValue for Vec4 { 165 | fn default_value() -> Option { 166 | Some(Self::default().to_value()) 167 | } 168 | } 169 | 170 | impl DescribeType for Vec4 { 171 | fn build(graph: &mut TypeGraph) -> NodeId { 172 | graph.get_or_build_node_with::(|graph| { 173 | let fields = &[ 174 | NamedFieldNode::new::("x", LinearMap::from([]), &[], graph), 175 | NamedFieldNode::new::("y", LinearMap::from([]), &[], graph), 176 | NamedFieldNode::new::("z", LinearMap::from([]), &[], graph), 177 | NamedFieldNode::new::("w", LinearMap::from([]), &[], graph), 178 | ]; 179 | StructNode::new::(fields, LinearMap::from([]), &[]) 180 | }) 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/hash_map.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | 3 | use core::any::Any; 4 | use core::fmt; 5 | use core::hash::BuildHasher; 6 | use core::hash::Hash; 7 | 8 | use std::collections::HashMap; 9 | 10 | use crate::iter::PairIterMut; 11 | use crate::map::MapError; 12 | use crate::type_info::graph::MapNode; 13 | use crate::type_info::graph::NodeId; 14 | use crate::type_info::graph::TypeGraph; 15 | use crate::DescribeType; 16 | use crate::FromReflect; 17 | use crate::Map; 18 | use crate::Reflect; 19 | use crate::ReflectMut; 20 | use crate::ReflectOwned; 21 | use crate::ReflectRef; 22 | use crate::Value; 23 | 24 | impl Reflect for HashMap 25 | where 26 | K: FromReflect + DescribeType + Eq + Hash, 27 | V: FromReflect + DescribeType, 28 | S: Default + BuildHasher + Send + 'static, 29 | { 30 | trivial_reflect_methods!(); 31 | 32 | fn reflect_owned(self: Box) -> ReflectOwned { 33 | ReflectOwned::Map(self) 34 | } 35 | 36 | fn reflect_ref(&self) -> ReflectRef<'_> { 37 | ReflectRef::Map(self) 38 | } 39 | 40 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 41 | ReflectMut::Map(self) 42 | } 43 | 44 | fn patch(&mut self, value: &dyn Reflect) { 45 | if let Some(map) = value.reflect_ref().as_map() { 46 | for (key, new_value) in map.iter() { 47 | if let Some(value) = Map::get_mut(self, key) { 48 | value.patch(new_value); 49 | } 50 | } 51 | } 52 | } 53 | 54 | fn to_value(&self) -> Value { 55 | let data = self 56 | .iter() 57 | .map(|(key, value)| (key.to_value(), value.to_value())) 58 | .collect(); 59 | Value::Map(data) 60 | } 61 | 62 | fn clone_reflect(&self) -> Box { 63 | let value = self.to_value(); 64 | Box::new(Self::from_reflect(&value).unwrap()) 65 | } 66 | 67 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 68 | f.debug_map().entries(Map::iter(self)).finish() 69 | } 70 | } 71 | 72 | impl FromReflect for HashMap 73 | where 74 | K: FromReflect + DescribeType + Eq + Hash, 75 | V: FromReflect + DescribeType, 76 | S: Default + BuildHasher + Send + 'static, 77 | { 78 | fn from_reflect(reflect: &dyn Reflect) -> Option { 79 | let map = reflect.as_map()?; 80 | let len = map.len(); 81 | let mut out = HashMap::with_capacity_and_hasher(len, S::default()); 82 | for (key, value) in map.iter() { 83 | out.insert(K::from_reflect(key)?, V::from_reflect(value)?); 84 | } 85 | Some(out) 86 | } 87 | } 88 | 89 | impl From> for Value 90 | where 91 | K: Reflect, 92 | V: Reflect, 93 | { 94 | fn from(map: HashMap) -> Self { 95 | let map = map 96 | .into_iter() 97 | .map(|(key, value)| (key.to_value(), value.to_value())) 98 | .collect(); 99 | Value::Map(map) 100 | } 101 | } 102 | 103 | impl Map for HashMap 104 | where 105 | K: FromReflect + DescribeType + Hash + Eq, 106 | V: FromReflect + DescribeType, 107 | S: Default + BuildHasher + Send + 'static, 108 | { 109 | map_methods!(); 110 | } 111 | 112 | impl DescribeType for HashMap 113 | where 114 | K: DescribeType, 115 | V: DescribeType, 116 | S: 'static, 117 | { 118 | fn build(graph: &mut TypeGraph) -> NodeId { 119 | graph.get_or_build_node_with::(|graph| MapNode::new::(graph)) 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/kollect/linear_map.rs: -------------------------------------------------------------------------------- 1 | use core::any::Any; 2 | use core::fmt; 3 | 4 | use kollect::LinearMap; 5 | 6 | use crate::iter::PairIterMut; 7 | use crate::map::MapError; 8 | use crate::type_info::graph::MapNode; 9 | use crate::type_info::graph::NodeId; 10 | use crate::type_info::graph::TypeGraph; 11 | use crate::DescribeType; 12 | use crate::FromReflect; 13 | use crate::Map; 14 | use crate::Reflect; 15 | use crate::ReflectMut; 16 | use crate::ReflectOwned; 17 | use crate::ReflectRef; 18 | use crate::Value; 19 | 20 | impl Reflect for LinearMap 21 | where 22 | K: FromReflect + DescribeType + Eq, 23 | V: FromReflect + DescribeType, 24 | { 25 | trivial_reflect_methods!(); 26 | 27 | fn reflect_owned(self: Box) -> ReflectOwned { 28 | ReflectOwned::Map(self) 29 | } 30 | 31 | fn reflect_ref(&self) -> ReflectRef<'_> { 32 | ReflectRef::Map(self) 33 | } 34 | 35 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 36 | ReflectMut::Map(self) 37 | } 38 | 39 | fn patch(&mut self, value: &dyn Reflect) { 40 | if let Some(map) = value.reflect_ref().as_map() { 41 | for (key, new_value) in map.iter() { 42 | if let Some(value) = Map::get_mut(self, key) { 43 | value.patch(new_value); 44 | } 45 | } 46 | } 47 | } 48 | 49 | fn to_value(&self) -> Value { 50 | let data = self 51 | .iter() 52 | .map(|(key, value)| (key.to_value(), value.to_value())) 53 | .collect(); 54 | Value::Map(data) 55 | } 56 | 57 | fn clone_reflect(&self) -> Box { 58 | let value = self.to_value(); 59 | Box::new(Self::from_reflect(&value).unwrap()) 60 | } 61 | 62 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 63 | f.debug_map().entries(Map::iter(self)).finish() 64 | } 65 | } 66 | 67 | impl FromReflect for LinearMap 68 | where 69 | K: FromReflect + DescribeType + Eq, 70 | V: FromReflect + DescribeType, 71 | { 72 | fn from_reflect(reflect: &dyn Reflect) -> Option { 73 | let map = reflect.as_map()?; 74 | let len = map.len(); 75 | let mut out = LinearMap::with_capacity(len); 76 | for (key, value) in map.iter() { 77 | out.insert(K::from_reflect(key)?, V::from_reflect(value)?); 78 | } 79 | Some(out) 80 | } 81 | } 82 | 83 | impl From> for Value 84 | where 85 | K: Reflect + Eq, 86 | V: Reflect, 87 | { 88 | fn from(map: LinearMap) -> Self { 89 | let map = map 90 | .into_iter() 91 | .map(|(key, value)| (key.to_value(), value.to_value())) 92 | .collect(); 93 | Value::Map(map) 94 | } 95 | } 96 | 97 | impl Map for LinearMap 98 | where 99 | K: FromReflect + DescribeType + Eq, 100 | V: FromReflect + DescribeType, 101 | { 102 | map_methods!(); 103 | } 104 | 105 | impl DescribeType for LinearMap 106 | where 107 | K: DescribeType, 108 | V: DescribeType, 109 | { 110 | fn build(graph: &mut TypeGraph) -> NodeId { 111 | graph.get_or_build_node_with::(|graph| MapNode::new::(graph)) 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/kollect/linear_set.rs: -------------------------------------------------------------------------------- 1 | use core::any::Any; 2 | use core::fmt; 3 | 4 | use kollect::LinearSet; 5 | 6 | use crate::{ 7 | set::{Iter, SetError}, 8 | type_info::graph::{NodeId, SetNode, TypeGraph}, 9 | DescribeType, FromReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, Set, Value, 10 | }; 11 | 12 | impl Reflect for LinearSet 13 | where 14 | V: FromReflect + DescribeType + Eq, 15 | { 16 | trivial_reflect_methods!(); 17 | 18 | fn reflect_owned(self: Box) -> ReflectOwned { 19 | ReflectOwned::Set(self) 20 | } 21 | 22 | fn reflect_ref(&self) -> ReflectRef<'_> { 23 | ReflectRef::Set(self) 24 | } 25 | 26 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 27 | ReflectMut::Set(self) 28 | } 29 | 30 | /// Performs a union. 31 | fn patch(&mut self, value: &dyn Reflect) { 32 | if let Some(set) = value.as_set() { 33 | for element in set.iter() { 34 | _ = self.try_insert(element); 35 | } 36 | } 37 | } 38 | 39 | fn to_value(&self) -> Value { 40 | let data = self.iter().map(Reflect::to_value).collect(); 41 | Value::Set(data) 42 | } 43 | 44 | fn clone_reflect(&self) -> Box { 45 | let value = self.to_value(); 46 | Box::new(Self::from_reflect(&value).unwrap()) 47 | } 48 | 49 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 50 | f.debug_set().entries(Set::iter(self)).finish() 51 | } 52 | } 53 | 54 | impl FromReflect for LinearSet 55 | where 56 | V: FromReflect + DescribeType + Eq, 57 | { 58 | fn from_reflect(reflect: &dyn Reflect) -> Option { 59 | let set = reflect.as_set()?; 60 | let len = set.len(); 61 | let mut out = LinearSet::with_capacity(len); 62 | for element in set.iter() { 63 | out.insert(V::from_reflect(element)?); 64 | } 65 | Some(out) 66 | } 67 | } 68 | 69 | impl From> for Value 70 | where 71 | V: Reflect + Eq, 72 | { 73 | fn from(set: LinearSet) -> Self { 74 | let set = set.into_iter().map(|element| element.to_value()).collect(); 75 | Value::Set(set) 76 | } 77 | } 78 | 79 | impl Set for LinearSet 80 | where 81 | V: FromReflect + DescribeType + Eq, 82 | { 83 | set_methods!(); 84 | } 85 | 86 | impl DescribeType for LinearSet 87 | where 88 | V: DescribeType, 89 | { 90 | fn build(graph: &mut TypeGraph) -> NodeId { 91 | graph.get_or_build_node_with::(|graph| SetNode::new::(graph)) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/kollect/mod.rs: -------------------------------------------------------------------------------- 1 | mod linear_map; 2 | mod ordered_map; 3 | mod unordered_map; 4 | 5 | mod linear_set; 6 | mod ordered_set; 7 | mod unordered_set; 8 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/kollect/ordered_map.rs: -------------------------------------------------------------------------------- 1 | use core::any::Any; 2 | use core::fmt; 3 | use core::hash::BuildHasher; 4 | use core::hash::Hash; 5 | 6 | use kollect::OrderedMap; 7 | 8 | use crate::iter::PairIterMut; 9 | use crate::map::MapError; 10 | use crate::type_info::graph::MapNode; 11 | use crate::type_info::graph::NodeId; 12 | use crate::type_info::graph::TypeGraph; 13 | use crate::DescribeType; 14 | use crate::FromReflect; 15 | use crate::Map; 16 | use crate::Reflect; 17 | use crate::ReflectMut; 18 | use crate::ReflectOwned; 19 | use crate::ReflectRef; 20 | use crate::Value; 21 | 22 | impl Reflect for OrderedMap 23 | where 24 | K: FromReflect + DescribeType + Eq + Hash, 25 | V: FromReflect + DescribeType, 26 | S: Default + BuildHasher + Send + 'static, 27 | { 28 | trivial_reflect_methods!(); 29 | 30 | fn reflect_owned(self: Box) -> ReflectOwned { 31 | ReflectOwned::Map(self) 32 | } 33 | 34 | fn reflect_ref(&self) -> ReflectRef<'_> { 35 | ReflectRef::Map(self) 36 | } 37 | 38 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 39 | ReflectMut::Map(self) 40 | } 41 | 42 | fn patch(&mut self, value: &dyn Reflect) { 43 | if let Some(map) = value.reflect_ref().as_map() { 44 | for (key, new_value) in map.iter() { 45 | if let Some(value) = Map::get_mut(self, key) { 46 | value.patch(new_value); 47 | } 48 | } 49 | } 50 | } 51 | 52 | fn to_value(&self) -> Value { 53 | let data = self 54 | .iter() 55 | .map(|(key, value)| (key.to_value(), value.to_value())) 56 | .collect(); 57 | Value::Map(data) 58 | } 59 | 60 | fn clone_reflect(&self) -> Box { 61 | let value = self.to_value(); 62 | Box::new(Self::from_reflect(&value).unwrap()) 63 | } 64 | 65 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 66 | f.debug_map().entries(Map::iter(self)).finish() 67 | } 68 | } 69 | 70 | impl FromReflect for OrderedMap 71 | where 72 | K: FromReflect + DescribeType + Eq + Hash, 73 | V: FromReflect + DescribeType, 74 | S: Default + BuildHasher + Send + 'static, 75 | { 76 | fn from_reflect(reflect: &dyn Reflect) -> Option { 77 | let map = reflect.as_map()?; 78 | let len = map.len(); 79 | let mut out = OrderedMap::with_capacity_and_hasher(len, S::default()); 80 | for (key, value) in map.iter() { 81 | out.insert(K::from_reflect(key)?, V::from_reflect(value)?); 82 | } 83 | Some(out) 84 | } 85 | } 86 | 87 | impl From> for Value 88 | where 89 | K: Reflect, 90 | V: Reflect, 91 | { 92 | fn from(map: OrderedMap) -> Self { 93 | let map = map 94 | .into_iter() 95 | .map(|(key, value)| (key.to_value(), value.to_value())) 96 | .collect(); 97 | Value::Map(map) 98 | } 99 | } 100 | 101 | impl Map for OrderedMap 102 | where 103 | K: FromReflect + DescribeType + Hash + Eq, 104 | V: FromReflect + DescribeType, 105 | S: Default + BuildHasher + Send + 'static, 106 | { 107 | map_methods!(); 108 | } 109 | 110 | impl DescribeType for OrderedMap 111 | where 112 | K: DescribeType, 113 | V: DescribeType, 114 | S: 'static, 115 | { 116 | fn build(graph: &mut TypeGraph) -> NodeId { 117 | graph.get_or_build_node_with::(|graph| MapNode::new::(graph)) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/kollect/ordered_set.rs: -------------------------------------------------------------------------------- 1 | use core::any::Any; 2 | use core::fmt; 3 | use core::hash::Hash; 4 | use std::hash::BuildHasher; 5 | 6 | use kollect::OrderedSet; 7 | 8 | use crate::{ 9 | set::{Iter, SetError}, 10 | type_info::graph::{NodeId, SetNode, TypeGraph}, 11 | DescribeType, FromReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, Set, Value, 12 | }; 13 | 14 | impl Reflect for OrderedSet 15 | where 16 | V: FromReflect + DescribeType + Hash + Eq, 17 | S: Default + BuildHasher + Send + 'static, 18 | { 19 | trivial_reflect_methods!(); 20 | 21 | fn reflect_owned(self: Box) -> ReflectOwned { 22 | ReflectOwned::Set(self) 23 | } 24 | 25 | fn reflect_ref(&self) -> ReflectRef<'_> { 26 | ReflectRef::Set(self) 27 | } 28 | 29 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 30 | ReflectMut::Set(self) 31 | } 32 | 33 | /// Performs a union. 34 | fn patch(&mut self, value: &dyn Reflect) { 35 | if let Some(set) = value.as_set() { 36 | for element in set.iter() { 37 | _ = self.try_insert(element); 38 | } 39 | } 40 | } 41 | 42 | fn to_value(&self) -> Value { 43 | let data = self.iter().map(Reflect::to_value).collect(); 44 | Value::Set(data) 45 | } 46 | 47 | fn clone_reflect(&self) -> Box { 48 | let value = self.to_value(); 49 | Box::new(Self::from_reflect(&value).unwrap()) 50 | } 51 | 52 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 53 | f.debug_set().entries(Set::iter(self)).finish() 54 | } 55 | } 56 | 57 | impl FromReflect for OrderedSet 58 | where 59 | V: FromReflect + DescribeType + Eq + Hash, 60 | S: Default + BuildHasher + Send + 'static, 61 | { 62 | fn from_reflect(reflect: &dyn Reflect) -> Option { 63 | let set = reflect.as_set()?; 64 | let len = set.len(); 65 | let mut out = OrderedSet::with_capacity_and_hasher(len, S::default()); 66 | for element in set.iter() { 67 | out.insert(V::from_reflect(element)?); 68 | } 69 | Some(out) 70 | } 71 | } 72 | 73 | impl From> for Value 74 | where 75 | V: Reflect, 76 | { 77 | fn from(set: OrderedSet) -> Self { 78 | let set = set.into_iter().map(|element| element.to_value()).collect(); 79 | Value::Set(set) 80 | } 81 | } 82 | 83 | impl Set for OrderedSet 84 | where 85 | V: FromReflect + DescribeType + Eq + Hash, 86 | S: Default + BuildHasher + Send + 'static, 87 | { 88 | set_methods!(); 89 | } 90 | 91 | impl DescribeType for OrderedSet 92 | where 93 | V: DescribeType, 94 | S: 'static, 95 | { 96 | fn build(graph: &mut TypeGraph) -> NodeId { 97 | graph.get_or_build_node_with::(|graph| SetNode::new::(graph)) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/kollect/unordered_map.rs: -------------------------------------------------------------------------------- 1 | use core::any::Any; 2 | use core::fmt; 3 | use core::hash::BuildHasher; 4 | use core::hash::Hash; 5 | 6 | use kollect::UnorderedMap; 7 | 8 | use crate::iter::PairIterMut; 9 | use crate::map::MapError; 10 | use crate::type_info::graph::MapNode; 11 | use crate::type_info::graph::NodeId; 12 | use crate::type_info::graph::TypeGraph; 13 | use crate::DescribeType; 14 | use crate::FromReflect; 15 | use crate::Map; 16 | use crate::Reflect; 17 | use crate::ReflectMut; 18 | use crate::ReflectOwned; 19 | use crate::ReflectRef; 20 | use crate::Value; 21 | 22 | impl Reflect for UnorderedMap 23 | where 24 | K: FromReflect + DescribeType + Eq + Hash, 25 | V: FromReflect + DescribeType, 26 | S: Default + BuildHasher + Send + 'static, 27 | { 28 | trivial_reflect_methods!(); 29 | 30 | fn reflect_owned(self: Box) -> ReflectOwned { 31 | ReflectOwned::Map(self) 32 | } 33 | 34 | fn reflect_ref(&self) -> ReflectRef<'_> { 35 | ReflectRef::Map(self) 36 | } 37 | 38 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 39 | ReflectMut::Map(self) 40 | } 41 | 42 | fn patch(&mut self, value: &dyn Reflect) { 43 | if let Some(map) = value.reflect_ref().as_map() { 44 | for (key, new_value) in map.iter() { 45 | if let Some(value) = Map::get_mut(self, key) { 46 | value.patch(new_value); 47 | } 48 | } 49 | } 50 | } 51 | 52 | fn to_value(&self) -> Value { 53 | let data = self 54 | .iter() 55 | .map(|(key, value)| (key.to_value(), value.to_value())) 56 | .collect(); 57 | Value::Map(data) 58 | } 59 | 60 | fn clone_reflect(&self) -> Box { 61 | let value = self.to_value(); 62 | Box::new(Self::from_reflect(&value).unwrap()) 63 | } 64 | 65 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 66 | f.debug_map().entries(Map::iter(self)).finish() 67 | } 68 | } 69 | 70 | impl FromReflect for UnorderedMap 71 | where 72 | K: FromReflect + DescribeType + Eq + Hash, 73 | V: FromReflect + DescribeType, 74 | S: Default + BuildHasher + Send + 'static, 75 | { 76 | fn from_reflect(reflect: &dyn Reflect) -> Option { 77 | let map = reflect.as_map()?; 78 | let len = map.len(); 79 | let mut out = UnorderedMap::with_capacity_and_hasher(len, S::default()); 80 | for (key, value) in map.iter() { 81 | out.insert(K::from_reflect(key)?, V::from_reflect(value)?); 82 | } 83 | Some(out) 84 | } 85 | } 86 | 87 | impl From> for Value 88 | where 89 | K: Reflect, 90 | V: Reflect, 91 | { 92 | fn from(map: UnorderedMap) -> Self { 93 | let map = map 94 | .into_iter() 95 | .map(|(key, value)| (key.to_value(), value.to_value())) 96 | .collect(); 97 | Value::Map(map) 98 | } 99 | } 100 | 101 | impl Map for UnorderedMap 102 | where 103 | K: FromReflect + DescribeType + Hash + Eq, 104 | V: FromReflect + DescribeType, 105 | S: Default + BuildHasher + Send + 'static, 106 | { 107 | map_methods!(); 108 | } 109 | 110 | impl DescribeType for UnorderedMap 111 | where 112 | K: DescribeType, 113 | V: DescribeType, 114 | S: 'static, 115 | { 116 | fn build(graph: &mut TypeGraph) -> NodeId { 117 | graph.get_or_build_node_with::(|graph| MapNode::new::(graph)) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/kollect/unordered_set.rs: -------------------------------------------------------------------------------- 1 | use core::any::Any; 2 | use core::fmt; 3 | use core::hash::Hash; 4 | use std::hash::BuildHasher; 5 | 6 | use kollect::UnorderedSet; 7 | 8 | use crate::{ 9 | set::{Iter, SetError}, 10 | type_info::graph::{NodeId, SetNode, TypeGraph}, 11 | DescribeType, FromReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, Set, Value, 12 | }; 13 | 14 | impl Reflect for UnorderedSet 15 | where 16 | V: FromReflect + DescribeType + Hash + Eq, 17 | S: Default + BuildHasher + Send + 'static, 18 | { 19 | trivial_reflect_methods!(); 20 | 21 | fn reflect_owned(self: Box) -> ReflectOwned { 22 | ReflectOwned::Set(self) 23 | } 24 | 25 | fn reflect_ref(&self) -> ReflectRef<'_> { 26 | ReflectRef::Set(self) 27 | } 28 | 29 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 30 | ReflectMut::Set(self) 31 | } 32 | 33 | /// Performs a union. 34 | fn patch(&mut self, value: &dyn Reflect) { 35 | if let Some(set) = value.as_set() { 36 | for element in set.iter() { 37 | _ = self.try_insert(element); 38 | } 39 | } 40 | } 41 | 42 | fn to_value(&self) -> Value { 43 | let data = self.iter().map(Reflect::to_value).collect(); 44 | Value::Set(data) 45 | } 46 | 47 | fn clone_reflect(&self) -> Box { 48 | let value = self.to_value(); 49 | Box::new(Self::from_reflect(&value).unwrap()) 50 | } 51 | 52 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 53 | f.debug_set().entries(Set::iter(self)).finish() 54 | } 55 | } 56 | 57 | impl FromReflect for UnorderedSet 58 | where 59 | V: FromReflect + DescribeType + Eq + Hash, 60 | S: Default + BuildHasher + Send + 'static, 61 | { 62 | fn from_reflect(reflect: &dyn Reflect) -> Option { 63 | let set = reflect.as_set()?; 64 | let len = set.len(); 65 | let mut out = UnorderedSet::with_capacity_and_hasher(len, S::default()); 66 | for element in set.iter() { 67 | out.insert(V::from_reflect(element)?); 68 | } 69 | Some(out) 70 | } 71 | } 72 | 73 | impl From> for Value 74 | where 75 | V: Reflect, 76 | { 77 | fn from(set: UnorderedSet) -> Self { 78 | let set = set.into_iter().map(|element| element.to_value()).collect(); 79 | Value::Set(set) 80 | } 81 | } 82 | 83 | impl Set for UnorderedSet 84 | where 85 | V: FromReflect + DescribeType + Eq + Hash, 86 | S: Default + BuildHasher + Send + 'static, 87 | { 88 | set_methods!(); 89 | } 90 | 91 | impl DescribeType for UnorderedSet 92 | where 93 | V: DescribeType, 94 | S: 'static, 95 | { 96 | fn build(graph: &mut TypeGraph) -> NodeId { 97 | graph.get_or_build_node_with::(|graph| SetNode::new::(graph)) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/macaw.rs: -------------------------------------------------------------------------------- 1 | use macaw::ColorRgba8; 2 | use mirror_mirror_macros::__private_derive_reflect_foreign; 3 | 4 | __private_derive_reflect_foreign! { 5 | #[reflect(crate_name(crate), opt_out(Default))] 6 | pub struct ColorRgba8(pub [u8; 4]); 7 | } 8 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/mod.rs: -------------------------------------------------------------------------------- 1 | use core::convert::Infallible; 2 | use core::ops::Range; 3 | use core::ops::RangeFrom; 4 | use core::ops::RangeFull; 5 | use core::ops::RangeTo; 6 | use core::ops::RangeToInclusive; 7 | 8 | use crate::__private::*; 9 | use mirror_mirror_macros::__private_derive_reflect_foreign; 10 | 11 | mod array; 12 | mod boxed; 13 | mod btree_map; 14 | mod hash_map; 15 | mod kollect; 16 | mod vec; 17 | mod vec_deque; 18 | mod via_scalar; 19 | 20 | #[cfg(feature = "glam")] 21 | mod glam; 22 | #[cfg(feature = "macaw")] 23 | mod macaw; 24 | 25 | __private_derive_reflect_foreign! { 26 | #[reflect(opt_out(Clone, Debug), crate_name(crate))] 27 | enum Option 28 | where 29 | T: FromReflect + DescribeType, 30 | { 31 | None, 32 | Some(T), 33 | } 34 | } 35 | 36 | __private_derive_reflect_foreign! { 37 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 38 | enum Result 39 | where 40 | T: FromReflect + DescribeType, 41 | E: FromReflect + DescribeType, 42 | { 43 | Ok(T), 44 | Err(E), 45 | } 46 | } 47 | 48 | __private_derive_reflect_foreign! { 49 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 50 | struct Range 51 | where 52 | Idx: FromReflect + DescribeType 53 | { 54 | start: Idx, 55 | end: Idx, 56 | } 57 | } 58 | 59 | __private_derive_reflect_foreign! { 60 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 61 | struct RangeFrom 62 | where 63 | Idx: FromReflect + DescribeType, 64 | { 65 | start: Idx, 66 | } 67 | } 68 | 69 | __private_derive_reflect_foreign! { 70 | #[reflect(crate_name(crate))] 71 | struct RangeFull; 72 | } 73 | 74 | __private_derive_reflect_foreign! { 75 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 76 | struct RangeToInclusive 77 | where 78 | Idx: FromReflect + DescribeType, 79 | { 80 | end: Idx, 81 | } 82 | } 83 | 84 | __private_derive_reflect_foreign! { 85 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 86 | struct RangeTo 87 | where 88 | Idx: FromReflect + DescribeType, 89 | { 90 | end: Idx, 91 | } 92 | } 93 | 94 | impl DescribeType for Infallible { 95 | fn build(graph: &mut TypeGraph) -> NodeId { 96 | let variants = &[]; 97 | graph.get_or_build_node_with::(|_graph| { 98 | EnumNode::new::(variants, LinearMap::from([]), &[]) 99 | }) 100 | } 101 | } 102 | 103 | impl DefaultValue for Infallible { 104 | fn default_value() -> Option { 105 | None 106 | } 107 | } 108 | 109 | impl Reflect for Infallible { 110 | fn as_any(&self) -> &dyn Any { 111 | match *self {} 112 | } 113 | 114 | fn as_any_mut(&mut self) -> &mut dyn Any { 115 | match *self {} 116 | } 117 | 118 | fn as_reflect(&self) -> &dyn Reflect { 119 | match *self {} 120 | } 121 | 122 | fn as_reflect_mut(&mut self) -> &mut dyn Reflect { 123 | match *self {} 124 | } 125 | 126 | fn into_any(self: Box) -> Box { 127 | match *self {} 128 | } 129 | 130 | fn patch(&mut self, _value: &dyn Reflect) { 131 | match *self {} 132 | } 133 | 134 | fn to_value(&self) -> Value { 135 | match *self {} 136 | } 137 | 138 | fn clone_reflect(&self) -> Box { 139 | match *self {} 140 | } 141 | 142 | fn debug(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { 143 | match *self {} 144 | } 145 | 146 | fn reflect_owned(self: Box) -> ReflectOwned { 147 | match *self {} 148 | } 149 | 150 | fn reflect_ref(&self) -> ReflectRef<'_> { 151 | match *self {} 152 | } 153 | 154 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 155 | match *self {} 156 | } 157 | } 158 | 159 | impl FromReflect for Infallible { 160 | fn from_reflect(_reflect: &dyn Reflect) -> Option { 161 | None 162 | } 163 | } 164 | 165 | impl Enum for Infallible { 166 | fn variant_name(&self) -> &str { 167 | match *self {} 168 | } 169 | 170 | fn variant_kind(&self) -> VariantKind { 171 | match *self {} 172 | } 173 | 174 | fn field(&self, _name: &str) -> Option<&dyn Reflect> { 175 | match *self {} 176 | } 177 | 178 | fn field_mut(&mut self, _name: &str) -> Option<&mut dyn Reflect> { 179 | match *self {} 180 | } 181 | 182 | fn field_at(&self, _index: usize) -> Option<&dyn Reflect> { 183 | match *self {} 184 | } 185 | 186 | fn field_at_mut(&mut self, _index: usize) -> Option<&mut dyn Reflect> { 187 | match *self {} 188 | } 189 | 190 | fn fields(&self) -> crate::enum_::VariantFieldIter<'_> { 191 | match *self {} 192 | } 193 | 194 | fn fields_mut(&mut self) -> VariantFieldIterMut<'_> { 195 | match *self {} 196 | } 197 | 198 | fn variants_len(&self) -> usize { 199 | match *self {} 200 | } 201 | 202 | fn fields_len(&self) -> usize { 203 | match *self {} 204 | } 205 | 206 | fn name_at(&self, _index: usize) -> Option<&str> { 207 | match *self {} 208 | } 209 | } 210 | 211 | impl From for Value { 212 | fn from(value: Infallible) -> Value { 213 | match value {} 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/vec.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use alloc::vec::Vec; 3 | use core::any::Any; 4 | 5 | use crate::array::Array; 6 | use crate::iter::ValueIterMut; 7 | use crate::list::ListError; 8 | use crate::type_info::graph::ListNode; 9 | use crate::type_info::graph::NodeId; 10 | use crate::type_info::graph::TypeGraph; 11 | use crate::DescribeType; 12 | use crate::FromReflect; 13 | use crate::List; 14 | use crate::Reflect; 15 | use crate::ReflectMut; 16 | use crate::ReflectOwned; 17 | use crate::ReflectRef; 18 | use crate::Value; 19 | 20 | impl List for Vec 21 | where 22 | T: FromReflect + DescribeType, 23 | { 24 | fn try_push(&mut self, element: &dyn Reflect) -> Result<(), ListError> { 25 | if let Some(value) = T::from_reflect(element) { 26 | Vec::push(self, value); 27 | Ok(()) 28 | } else { 29 | Err(ListError) 30 | } 31 | } 32 | 33 | fn pop(&mut self) -> Option> { 34 | let value = Vec::pop(self)?; 35 | Some(Box::new(value)) 36 | } 37 | 38 | fn try_remove(&mut self, index: usize) -> Option> { 39 | if index < self.len() { 40 | let value = Vec::remove(self, index); 41 | Some(Box::new(value)) 42 | } else { 43 | None 44 | } 45 | } 46 | 47 | fn try_insert(&mut self, index: usize, element: &dyn Reflect) -> Result<(), ListError> { 48 | if let Some(element) = T::from_reflect(element) { 49 | Vec::insert(self, index, element); 50 | Ok(()) 51 | } else { 52 | Err(ListError) 53 | } 54 | } 55 | } 56 | 57 | impl Array for Vec 58 | where 59 | T: FromReflect + DescribeType, 60 | { 61 | fn get(&self, index: usize) -> Option<&dyn Reflect> { 62 | self.as_slice().get(index).map(|value| value.as_reflect()) 63 | } 64 | 65 | fn get_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 66 | self.as_mut_slice() 67 | .get_mut(index) 68 | .map(|value| value.as_reflect_mut()) 69 | } 70 | 71 | fn len(&self) -> usize { 72 | Vec::len(self) 73 | } 74 | 75 | fn is_empty(&self) -> bool { 76 | Vec::is_empty(self) 77 | } 78 | 79 | fn iter(&self) -> crate::array::Iter<'_> { 80 | crate::array::Iter::new(self) 81 | } 82 | 83 | fn iter_mut(&mut self) -> ValueIterMut<'_> { 84 | let iter = self 85 | .as_mut_slice() 86 | .iter_mut() 87 | .map(|value| value.as_reflect_mut()); 88 | Box::new(iter) 89 | } 90 | 91 | fn swap(&mut self, a: usize, b: usize) { 92 | self.as_mut_slice().swap(a, b); 93 | } 94 | } 95 | 96 | impl DescribeType for Vec 97 | where 98 | T: DescribeType, 99 | { 100 | fn build(graph: &mut TypeGraph) -> NodeId { 101 | graph.get_or_build_node_with::(|graph| ListNode::new::(graph)) 102 | } 103 | } 104 | 105 | impl Reflect for Vec 106 | where 107 | T: FromReflect + DescribeType, 108 | { 109 | trivial_reflect_methods!(); 110 | 111 | fn patch(&mut self, value: &dyn Reflect) { 112 | if let Some(list) = value.reflect_ref().as_list() { 113 | for (idx, new_value) in list.iter().enumerate() { 114 | if let Some(value) = self.get_mut(idx) { 115 | value.patch(new_value); 116 | } 117 | } 118 | } 119 | } 120 | 121 | fn to_value(&self) -> Value { 122 | let data = self.iter().map(Reflect::to_value).collect(); 123 | Value::List(data) 124 | } 125 | 126 | fn clone_reflect(&self) -> Box { 127 | let value = self.to_value(); 128 | Box::new(Self::from_reflect(&value).unwrap()) 129 | } 130 | 131 | fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 132 | f.debug_list().entries(self.iter()).finish() 133 | } 134 | 135 | fn reflect_owned(self: Box) -> ReflectOwned { 136 | ReflectOwned::List(self) 137 | } 138 | 139 | fn reflect_ref(&self) -> ReflectRef<'_> { 140 | ReflectRef::List(self) 141 | } 142 | 143 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 144 | ReflectMut::List(self) 145 | } 146 | 147 | fn as_array(&self) -> Option<&dyn Array> { 148 | Some(self) 149 | } 150 | 151 | fn as_array_mut(&mut self) -> Option<&mut dyn Array> { 152 | Some(self) 153 | } 154 | 155 | fn into_array(self: Box) -> Option> { 156 | Some(self) 157 | } 158 | } 159 | 160 | impl FromReflect for Vec 161 | where 162 | T: FromReflect + DescribeType, 163 | { 164 | fn from_reflect(reflect: &dyn Reflect) -> Option { 165 | let iter = match reflect.reflect_ref() { 166 | ReflectRef::Array(array) => array.iter(), 167 | ReflectRef::List(list) => list.iter(), 168 | _ => return None, 169 | }; 170 | let mut out = Vec::with_capacity(iter.len()); 171 | for value in iter { 172 | out.push(T::from_reflect(value)?); 173 | } 174 | Some(out) 175 | } 176 | } 177 | 178 | impl From> for Value 179 | where 180 | T: Reflect, 181 | { 182 | fn from(list: Vec) -> Self { 183 | let list = list 184 | .into_iter() 185 | .map(|value| value.to_value()) 186 | .collect::>(); 187 | Value::List(list) 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/vec_deque.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use alloc::collections::VecDeque; 3 | use alloc::vec::Vec; 4 | use core::any::Any; 5 | 6 | use crate::array::Array; 7 | use crate::list::ListError; 8 | use crate::type_info::graph::ListNode; 9 | use crate::type_info::graph::NodeId; 10 | use crate::type_info::graph::TypeGraph; 11 | use crate::DescribeType; 12 | use crate::FromReflect; 13 | use crate::List; 14 | use crate::Reflect; 15 | use crate::ReflectMut; 16 | use crate::ReflectOwned; 17 | use crate::ReflectRef; 18 | use crate::Value; 19 | 20 | impl List for VecDeque 21 | where 22 | T: FromReflect + DescribeType, 23 | { 24 | fn try_push(&mut self, element: &dyn Reflect) -> Result<(), ListError> { 25 | if let Some(value) = T::from_reflect(element) { 26 | VecDeque::push_back(self, value); 27 | Ok(()) 28 | } else { 29 | Err(ListError) 30 | } 31 | } 32 | 33 | fn pop(&mut self) -> Option> { 34 | let value = VecDeque::pop_back(self)?; 35 | Some(Box::new(value)) 36 | } 37 | 38 | fn try_remove(&mut self, index: usize) -> Option> { 39 | if index < self.len() { 40 | let value = VecDeque::remove(self, index); 41 | Some(Box::new(value)) 42 | } else { 43 | None 44 | } 45 | } 46 | 47 | fn try_insert(&mut self, index: usize, element: &dyn Reflect) -> Result<(), ListError> { 48 | if let Some(element) = T::from_reflect(element) { 49 | VecDeque::insert(self, index, element); 50 | Ok(()) 51 | } else { 52 | Err(ListError) 53 | } 54 | } 55 | } 56 | 57 | impl Array for VecDeque 58 | where 59 | T: FromReflect + DescribeType, 60 | { 61 | fn get(&self, index: usize) -> Option<&dyn Reflect> { 62 | VecDeque::get(self, index).map(|value| value.as_reflect()) 63 | } 64 | 65 | fn get_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 66 | VecDeque::get_mut(self, index).map(|value| value.as_reflect_mut()) 67 | } 68 | 69 | fn len(&self) -> usize { 70 | VecDeque::len(self) 71 | } 72 | 73 | fn is_empty(&self) -> bool { 74 | VecDeque::is_empty(self) 75 | } 76 | 77 | fn iter(&self) -> crate::array::Iter<'_> { 78 | crate::array::Iter::new(self) 79 | } 80 | 81 | fn iter_mut(&mut self) -> crate::iter::ValueIterMut<'_> { 82 | let iter = VecDeque::iter_mut(self).map(|value| value.as_reflect_mut()); 83 | Box::new(iter) 84 | } 85 | 86 | fn swap(&mut self, a: usize, b: usize) { 87 | VecDeque::swap(self, a, b); 88 | } 89 | } 90 | 91 | impl Reflect for VecDeque 92 | where 93 | T: FromReflect + DescribeType, 94 | { 95 | trivial_reflect_methods!(); 96 | 97 | fn patch(&mut self, value: &dyn Reflect) { 98 | if let Some(list) = value.reflect_ref().as_list() { 99 | for (idx, new_value) in list.iter().enumerate() { 100 | if let Some(value) = self.get_mut(idx) { 101 | value.patch(new_value); 102 | } 103 | } 104 | } 105 | } 106 | 107 | fn to_value(&self) -> Value { 108 | let data = self.iter().map(Reflect::to_value).collect(); 109 | Value::List(data) 110 | } 111 | 112 | fn clone_reflect(&self) -> Box { 113 | let value = self.to_value(); 114 | Box::new(Self::from_reflect(&value).unwrap()) 115 | } 116 | 117 | fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 118 | f.debug_list().entries(Array::iter(self)).finish() 119 | } 120 | 121 | fn reflect_owned(self: Box) -> ReflectOwned { 122 | ReflectOwned::List(self) 123 | } 124 | 125 | fn reflect_ref(&self) -> ReflectRef<'_> { 126 | ReflectRef::List(self) 127 | } 128 | 129 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 130 | ReflectMut::List(self) 131 | } 132 | 133 | fn as_array(&self) -> Option<&dyn Array> { 134 | Some(self) 135 | } 136 | 137 | fn as_array_mut(&mut self) -> Option<&mut dyn Array> { 138 | Some(self) 139 | } 140 | 141 | fn into_array(self: Box) -> Option> { 142 | Some(self) 143 | } 144 | } 145 | 146 | impl FromReflect for VecDeque 147 | where 148 | T: FromReflect + DescribeType, 149 | { 150 | fn from_reflect(reflect: &dyn Reflect) -> Option { 151 | let iter = match reflect.reflect_ref() { 152 | ReflectRef::Array(array) => array.iter(), 153 | ReflectRef::List(list) => list.iter(), 154 | _ => return None, 155 | }; 156 | let mut out = VecDeque::with_capacity(iter.len()); 157 | for value in iter { 158 | out.push_back(T::from_reflect(value)?); 159 | } 160 | Some(out) 161 | } 162 | } 163 | 164 | impl From> for Value 165 | where 166 | T: Reflect, 167 | { 168 | fn from(list: VecDeque) -> Self { 169 | let list = list 170 | .into_iter() 171 | .map(|value| value.to_value()) 172 | .collect::>(); 173 | Value::List(list) 174 | } 175 | } 176 | 177 | impl DescribeType for VecDeque 178 | where 179 | T: DescribeType, 180 | { 181 | fn build(graph: &mut TypeGraph) -> NodeId { 182 | graph.get_or_build_node_with::(|graph| ListNode::new::(graph)) 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/foreign_impls/via_scalar.rs: -------------------------------------------------------------------------------- 1 | use core::num::NonZeroI128; 2 | use core::num::NonZeroI16; 3 | use core::num::NonZeroI32; 4 | use core::num::NonZeroI64; 5 | use core::num::NonZeroI8; 6 | use core::num::NonZeroU128; 7 | use core::num::NonZeroU16; 8 | use core::num::NonZeroU32; 9 | use core::num::NonZeroU64; 10 | use core::num::NonZeroU8; 11 | use core::num::NonZeroUsize; 12 | use core::time::Duration; 13 | 14 | macro_rules! impl_reflect_via_scalar { 15 | ($ty:ty, $via_ty:ty, $get_fn:expr, $new_fn:expr $(,)?) => { 16 | const _: () = { 17 | use $crate::__private::*; 18 | 19 | impl DescribeType for $ty { 20 | fn build(graph: &mut TypeGraph) -> NodeId { 21 | graph.get_or_build_node_with::(|graph| { 22 | OpaqueNode::new::(Default::default(), graph) 23 | }) 24 | } 25 | } 26 | 27 | impl Reflect for $ty { 28 | trivial_reflect_methods!(); 29 | 30 | #[allow(clippy::redundant_closure_call)] 31 | fn reflect_owned(self: Box) -> ReflectOwned { 32 | ReflectOwned::Scalar(ScalarOwned::from($get_fn(&*self))) 33 | } 34 | 35 | #[allow(clippy::redundant_closure_call)] 36 | fn reflect_ref(&self) -> ReflectRef<'_> { 37 | ReflectRef::Scalar(ScalarRef::from($get_fn(self))) 38 | } 39 | 40 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 41 | ReflectMut::Opaque(self) 42 | } 43 | 44 | fn patch(&mut self, value: &dyn Reflect) { 45 | if let Some(n) = Self::from_reflect(value) { 46 | *self = n; 47 | } 48 | } 49 | 50 | #[allow(clippy::redundant_closure_call)] 51 | fn to_value(&self) -> Value { 52 | $get_fn(self).to_value() 53 | } 54 | 55 | fn clone_reflect(&self) -> Box { 56 | Box::new(*self) 57 | } 58 | 59 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 60 | if f.alternate() { 61 | write!(f, "{:#?}", self) 62 | } else { 63 | write!(f, "{:?}", self) 64 | } 65 | } 66 | } 67 | 68 | impl FromReflect for $ty { 69 | fn from_reflect(reflect: &dyn Reflect) -> Option { 70 | if let Some(n) = reflect.downcast_ref::() { 71 | Some(*n) 72 | } else { 73 | <$via_ty>::from_reflect(reflect) 74 | .and_then(|value| $new_fn(value).into_option()) 75 | } 76 | } 77 | } 78 | 79 | impl From<$ty> for Value { 80 | fn from(n: $ty) -> Self { 81 | n.to_value() 82 | } 83 | } 84 | }; 85 | }; 86 | } 87 | 88 | impl_reflect_via_scalar! { NonZeroUsize, usize, |n: &NonZeroUsize| n.get(), Self::new } 89 | impl_reflect_via_scalar! { NonZeroU8, u8, |n: &NonZeroU8| n.get(), Self::new } 90 | impl_reflect_via_scalar! { NonZeroU16, u16, |n: &NonZeroU16| n.get(), Self::new } 91 | impl_reflect_via_scalar! { NonZeroU32, u32, |n: &NonZeroU32| n.get(), Self::new } 92 | impl_reflect_via_scalar! { NonZeroU64, u64, |n: &NonZeroU64| n.get(), Self::new } 93 | impl_reflect_via_scalar! { NonZeroU128, u128, |n: &NonZeroU128| n.get(), Self::new } 94 | impl_reflect_via_scalar! { NonZeroI8, i8, |n: &NonZeroI8| n.get(), Self::new } 95 | impl_reflect_via_scalar! { NonZeroI16, i16, |n: &NonZeroI16| n.get(), Self::new } 96 | impl_reflect_via_scalar! { NonZeroI32, i32, |n: &NonZeroI32| n.get(), Self::new } 97 | impl_reflect_via_scalar! { NonZeroI64, i64, |n: &NonZeroI64| n.get(), Self::new } 98 | impl_reflect_via_scalar! { NonZeroI128, i128, |n: &NonZeroI128| n.get(), Self::new } 99 | 100 | impl_reflect_via_scalar! { Duration, f32, |d: &Duration| d.as_secs_f32(), Self::from_secs_f32 } 101 | 102 | trait IntoOption { 103 | fn into_option(self) -> Option; 104 | } 105 | 106 | impl IntoOption for Option { 107 | fn into_option(self) -> Option { 108 | self 109 | } 110 | } 111 | 112 | impl IntoOption for T { 113 | fn into_option(self) -> Option { 114 | Some(self) 115 | } 116 | } 117 | 118 | #[cfg(test)] 119 | mod tests { 120 | use super::*; 121 | use crate::DescribeType; 122 | 123 | #[test] 124 | fn keeps_type_name() { 125 | assert_eq!( 126 | ::type_descriptor() 127 | .get_type() 128 | .type_name(), 129 | "core::num::nonzero::NonZero" 130 | ); 131 | 132 | assert_eq!( 133 | ::type_descriptor() 134 | .get_type() 135 | .type_name(), 136 | "core::time::Duration" 137 | ); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/iter.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | 3 | use crate::Reflect; 4 | 5 | // Its not possible to implement this without boxing, because rust cannot prove that the borrows 6 | // from `next` don't overlap. That requires `LendingIterator` 7 | // 8 | // Its a type alias to make it clear that it allocates 9 | pub type ValueIterMut<'a> = Box + 'a>; 10 | 11 | // Its not possible to implement this without boxing, because rust cannot prove that the borrows 12 | // from `next` don't overlap. That requires `LendingIterator` 13 | // 14 | // Its a type alias to make it clear that it allocates 15 | pub type PairIterMut<'a, T = str> = Box + 'a>; 16 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/list.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use core::fmt; 3 | 4 | use crate::array::Array; 5 | use crate::Reflect; 6 | 7 | /// A reflected list type. 8 | pub trait List: Array { 9 | /// Appends an element to the back of a collection. 10 | /// 11 | /// Returns `Err(_)` if `element` couldn't be parsed to the element type, using 12 | /// `FromReflect::from_reflect`. 13 | fn try_push(&mut self, element: &dyn Reflect) -> Result<(), ListError>; 14 | 15 | /// Removes the last element from a vector and returns it, or `None` if it is empty. 16 | fn pop(&mut self) -> Option>; 17 | 18 | /// Removes and returns the element at position `index` within the vector, shifting all elements 19 | /// after it to the left. 20 | /// 21 | /// Returns `None` if `inde` is out of bounds. 22 | fn try_remove(&mut self, index: usize) -> Option>; 23 | 24 | /// Inserts an element at position `index` within the vector, shifting all elements after it to 25 | /// the right. 26 | /// 27 | /// Returns `Err(_)` if `element` couldn't be parsed to the element type, using 28 | /// `FromReflect::from_reflect`. 29 | fn try_insert(&mut self, index: usize, element: &dyn Reflect) -> Result<(), ListError>; 30 | } 31 | 32 | impl fmt::Debug for dyn List { 33 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 34 | self.as_reflect().debug(f) 35 | } 36 | } 37 | 38 | /// A method on a reflected list failed. 39 | #[non_exhaustive] 40 | #[derive(Debug)] 41 | pub struct ListError; 42 | 43 | impl core::fmt::Display for ListError { 44 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 45 | write!(f, "failed to parse element") 46 | } 47 | } 48 | 49 | impl std::error::Error for ListError {} 50 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/map.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | use alloc::boxed::Box; 4 | 5 | use crate::iter::PairIterMut; 6 | use crate::{FromReflect, Reflect}; 7 | 8 | /// A reflected key-to-value map type. 9 | /// 10 | /// Maps are guaranteed to not have duplicate entries for the same key, but there is 11 | /// *not* a guaranteed of a stable ordering of the `(key, value)` elements in the map. 12 | /// However, for underlying map types that have an ordering, that ordering can be assumed 13 | /// to be respected. 14 | /// 15 | /// This is implemented for the std [`BTreeMap`], [`HashMap`], as well as for our own 16 | /// [`UnorderedMap`], [`OrderedMap`] and [`Value`]s which are maps. 17 | /// 18 | /// [`BTreeMap`]: alloc::collections::BTreeMap 19 | /// [`HashMap`]: std::collections::HashMap 20 | /// [`Value`]: crate::Value 21 | /// [`OrderedMap`]: kollect::OrderedMap 22 | /// [`UnorderedMap`]: kollect::UnorderedMap 23 | pub trait Map: Reflect { 24 | fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect>; 25 | 26 | fn get_mut(&mut self, key: &dyn Reflect) -> Option<&mut dyn Reflect>; 27 | 28 | /// Inserts a key-value pair into the map. 29 | /// 30 | /// If the map did not have this key present, `Ok(None)` is returned. 31 | /// 32 | /// If the key, or value, failed to be parsed with `FromReflect::from_reflect` the `Err(_)` is 33 | /// returned. 34 | fn try_insert<'a>( 35 | &mut self, 36 | key: &'a dyn Reflect, 37 | value: &'a dyn Reflect, 38 | ) -> Result>, MapError>; 39 | 40 | /// Removes a key from the map, returning the value at the key if the key was previously in the 41 | /// map. 42 | /// 43 | /// If the key failed to be parsed with `FromReflect::from_reflect` the `Err(_)` is returned. 44 | fn try_remove(&mut self, key: &dyn Reflect) -> Result>, MapError>; 45 | 46 | fn len(&self) -> usize; 47 | 48 | fn is_empty(&self) -> bool; 49 | 50 | /// Get an iterator over the `(k, v)` element pairs in the map. Note that the iteration order 51 | /// is *not* guaranteed to be stable, though if the underlying implementor type does have a 52 | /// defined order then that can be assumed to be respected. 53 | fn iter(&self) -> Iter<'_>; 54 | 55 | /// Get an iterator over the `(k, v)` element pairs in the map with mutable values. Note that 56 | /// the iteration order is *not* guaranteed to be stable, though if the underlying implementor 57 | /// type does have a defined order then that can be assumed to be respected. 58 | fn iter_mut(&mut self) -> PairIterMut<'_, dyn Reflect>; 59 | } 60 | 61 | impl fmt::Debug for dyn Map { 62 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 63 | self.as_reflect().debug(f) 64 | } 65 | } 66 | 67 | pub type Iter<'a> = Box + 'a>; 68 | 69 | /// A method on a reflected map failed. 70 | #[derive(Debug)] 71 | pub enum MapError { 72 | /// Parsing the key with `FromReflect::from_reflect` failed. 73 | KeyFromReflectFailed, 74 | /// Parsing the value with `FromReflect::from_reflect` failed. 75 | ValueFromReflectFailed, 76 | } 77 | 78 | impl core::fmt::Display for MapError { 79 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 80 | match self { 81 | MapError::KeyFromReflectFailed => write!(f, "failed to parse key"), 82 | MapError::ValueFromReflectFailed => write!(f, "failed to parse value"), 83 | } 84 | } 85 | } 86 | 87 | impl std::error::Error for MapError {} 88 | 89 | pub(crate) fn key_value_from_reflect( 90 | key: &dyn Reflect, 91 | value: &dyn Reflect, 92 | ) -> Result<(K, V), MapError> 93 | where 94 | K: FromReflect, 95 | V: FromReflect, 96 | { 97 | let k = K::from_reflect(key).ok_or(MapError::KeyFromReflectFailed)?; 98 | let v = V::from_reflect(value).ok_or(MapError::KeyFromReflectFailed)?; 99 | Ok((k, v)) 100 | } 101 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/set.rs: -------------------------------------------------------------------------------- 1 | use crate::Reflect; 2 | 3 | use core::fmt; 4 | 5 | pub trait Set: Reflect { 6 | fn len(&self) -> usize; 7 | 8 | fn is_empty(&self) -> bool; 9 | 10 | fn try_insert(&mut self, element: &dyn Reflect) -> Result; 11 | 12 | fn try_remove(&mut self, element: &dyn Reflect) -> Result; 13 | 14 | fn try_contains(&mut self, element: &dyn Reflect) -> Result; 15 | 16 | fn iter(&self) -> Iter<'_>; 17 | } 18 | 19 | impl fmt::Debug for dyn Set { 20 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 21 | self.as_reflect().debug(f) 22 | } 23 | } 24 | 25 | pub type Iter<'a> = Box + 'a>; 26 | 27 | /// A method on a reflected set failed. 28 | #[non_exhaustive] 29 | #[derive(Debug)] 30 | pub struct SetError; 31 | 32 | impl core::fmt::Display for SetError { 33 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 34 | write!(f, "failed to parse element") 35 | } 36 | } 37 | 38 | impl std::error::Error for SetError {} 39 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/struct_.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use alloc::string::String; 3 | use core::any::Any; 4 | use core::fmt; 5 | 6 | use kollect::LinearMap; 7 | 8 | use crate::iter::PairIterMut; 9 | use crate::type_info::graph::NodeId; 10 | use crate::type_info::graph::OpaqueNode; 11 | use crate::type_info::graph::TypeGraph; 12 | use crate::DescribeType; 13 | use crate::FromReflect; 14 | use crate::Reflect; 15 | use crate::ReflectMut; 16 | use crate::ReflectOwned; 17 | use crate::ReflectRef; 18 | use crate::Value; 19 | 20 | pub type FieldsIter<'a> = Box + 'a>; 21 | pub type FieldsIterMut<'a> = Box + 'a>; 22 | 23 | /// A reflected struct type. 24 | /// 25 | /// Will be implemented by `#[derive(Reflect)]` on structs. 26 | pub trait Struct: Reflect { 27 | fn field(&self, name: &str) -> Option<&dyn Reflect>; 28 | 29 | fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect>; 30 | 31 | fn field_at(&self, index: usize) -> Option<&dyn Reflect>; 32 | 33 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>; 34 | 35 | fn name_at(&self, index: usize) -> Option<&str>; 36 | 37 | fn fields(&self) -> FieldsIter<'_>; 38 | 39 | fn fields_mut(&mut self) -> FieldsIterMut<'_>; 40 | 41 | fn fields_len(&self) -> usize; 42 | } 43 | 44 | impl fmt::Debug for dyn Struct { 45 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 46 | self.as_reflect().debug(f) 47 | } 48 | } 49 | 50 | #[derive(Default, Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] 51 | #[cfg_attr(feature = "speedy", derive(speedy::Readable, speedy::Writable))] 52 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 53 | pub struct StructValue { 54 | #[cfg_attr(feature = "serde", serde(with = "kollect::linear_map::serde_as_map"))] 55 | fields: LinearMap, 56 | } 57 | 58 | impl StructValue { 59 | pub fn new() -> Self { 60 | Self::default() 61 | } 62 | 63 | pub fn with_capacity(capacity: usize) -> Self { 64 | Self { 65 | fields: LinearMap::with_capacity(capacity), 66 | } 67 | } 68 | 69 | pub fn with_field(mut self, name: impl Into, value: impl Into) -> Self { 70 | self.set_field(name, value); 71 | self 72 | } 73 | 74 | pub fn set_field(&mut self, name: impl Into, value: impl Into) { 75 | let name = name.into(); 76 | self.fields.insert(name, value.into()); 77 | } 78 | } 79 | 80 | impl DescribeType for StructValue { 81 | fn build(graph: &mut TypeGraph) -> NodeId { 82 | graph.get_or_build_node_with::(|graph| { 83 | OpaqueNode::new::(Default::default(), graph) 84 | }) 85 | } 86 | } 87 | 88 | impl Reflect for StructValue { 89 | trivial_reflect_methods!(); 90 | 91 | fn patch(&mut self, value: &dyn Reflect) { 92 | if let Some(struct_) = value.reflect_ref().as_struct() { 93 | for (name, value) in self.fields_mut() { 94 | if let Some(new_value) = struct_.field(name) { 95 | value.patch(new_value); 96 | } 97 | } 98 | } 99 | } 100 | 101 | fn to_value(&self) -> Value { 102 | self.clone().into() 103 | } 104 | 105 | fn clone_reflect(&self) -> Box { 106 | Box::new(self.clone()) 107 | } 108 | 109 | fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 110 | if f.alternate() { 111 | write!(f, "{self:#?}") 112 | } else { 113 | write!(f, "{self:?}") 114 | } 115 | } 116 | 117 | fn reflect_owned(self: Box) -> ReflectOwned { 118 | ReflectOwned::Struct(self) 119 | } 120 | 121 | fn reflect_ref(&self) -> ReflectRef<'_> { 122 | ReflectRef::Struct(self) 123 | } 124 | 125 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 126 | ReflectMut::Struct(self) 127 | } 128 | } 129 | 130 | impl Struct for StructValue { 131 | fn field(&self, name: &str) -> Option<&dyn Reflect> { 132 | Some(self.fields.get(name)?) 133 | } 134 | 135 | fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect> { 136 | Some(self.fields.get_mut(name)?) 137 | } 138 | 139 | fn fields(&self) -> FieldsIter<'_> { 140 | let iter = self 141 | .fields 142 | .iter() 143 | .map(|(key, value)| (&**key, value.as_reflect())); 144 | Box::new(iter) 145 | } 146 | 147 | fn fields_mut(&mut self) -> PairIterMut<'_> { 148 | let iter = self 149 | .fields 150 | .iter_mut() 151 | .map(|(key, value)| (&**key, value.as_reflect_mut())); 152 | Box::new(iter) 153 | } 154 | 155 | fn fields_len(&self) -> usize { 156 | self.fields.len() 157 | } 158 | 159 | fn field_at(&self, index: usize) -> Option<&dyn Reflect> { 160 | let (_name, value) = self.fields.get_index(index)?; 161 | Some(value) 162 | } 163 | 164 | fn name_at(&self, index: usize) -> Option<&str> { 165 | let (name, _value) = self.fields.get_index(index)?; 166 | Some(name.as_str()) 167 | } 168 | 169 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 170 | let (_name, value) = self.fields.get_index_mut(index)?; 171 | Some(value) 172 | } 173 | } 174 | 175 | impl FromReflect for StructValue { 176 | fn from_reflect(reflect: &dyn Reflect) -> Option { 177 | let struct_ = reflect.reflect_ref().as_struct()?; 178 | let this = struct_ 179 | .fields() 180 | .fold(StructValue::default(), |builder, (name, value)| { 181 | builder.with_field(name, value.to_value()) 182 | }); 183 | Some(this) 184 | } 185 | } 186 | 187 | impl FromIterator<(S, V)> for StructValue 188 | where 189 | S: Into, 190 | V: Reflect, 191 | { 192 | fn from_iter(iter: T) -> Self 193 | where 194 | T: IntoIterator, 195 | { 196 | let fields = LinearMap::from_iter(iter.into_iter().map(|(k, v)| (k.into(), v.to_value()))); 197 | Self { fields } 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/array.rs: -------------------------------------------------------------------------------- 1 | use crate::DescribeType; 2 | use crate::FromReflect; 3 | use crate::Reflect; 4 | use crate::ReflectMut; 5 | use crate::ReflectOwned; 6 | use crate::ReflectRef; 7 | 8 | #[test] 9 | fn from_default_tuple() { 10 | #[derive(Debug, Clone, Default, Reflect, PartialEq)] 11 | #[reflect(crate_name(crate))] 12 | struct Foo([i32; 5]); 13 | 14 | let foo_default_value = ::type_descriptor() 15 | .default_value() 16 | .unwrap(); 17 | 18 | let foo = Foo::from_reflect(&foo_default_value).unwrap(); 19 | 20 | assert_eq!(foo, Foo([0, 0, 0, 0, 0])) 21 | } 22 | 23 | #[test] 24 | fn from_default_named() { 25 | #[derive(Debug, Clone, Default, Reflect, PartialEq)] 26 | #[reflect(crate_name(crate))] 27 | struct Foo { 28 | array: [i32; 5], 29 | } 30 | 31 | let foo_default_value = ::type_descriptor() 32 | .default_value() 33 | .unwrap(); 34 | 35 | assert_eq!( 36 | Foo::from_reflect(&foo_default_value).unwrap(), 37 | Foo { 38 | array: [0, 0, 0, 0, 0], 39 | } 40 | ); 41 | } 42 | 43 | #[test] 44 | fn casting_array_to_list() { 45 | let mut array: [i32; 5] = [0, 0, 0, 0, 0]; 46 | assert!(array.as_list().is_none()); 47 | assert!(array.as_list_mut().is_none()); 48 | assert!(Box::new(array).into_list().is_none()); 49 | 50 | // there is no `Value::Array`. Arrays converted to `Value` will become `Value::Array`, which 51 | // does support `as_array` 52 | } 53 | 54 | #[test] 55 | fn casting_array_to_array() { 56 | let mut array: [i32; 5] = [0, 0, 0, 0, 0]; 57 | assert!(array.as_array().is_some()); 58 | assert!(array.as_array_mut().is_some()); 59 | assert!(Box::new(array).into_array().is_some()); 60 | 61 | let mut array: [i32; 5] = [0, 0, 0, 0, 0]; 62 | assert!(matches!(array.reflect_ref(), ReflectRef::Array(_))); 63 | assert!(matches!(array.reflect_mut(), ReflectMut::Array(_))); 64 | assert!(matches!( 65 | Box::new(array).reflect_owned(), 66 | ReflectOwned::Array(_), 67 | )); 68 | } 69 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/key_path.rs: -------------------------------------------------------------------------------- 1 | use alloc::collections::BTreeMap; 2 | 3 | use crate::key_path; 4 | use crate::key_path::*; 5 | use crate::type_info::ScalarType; 6 | use crate::type_info::TypeAtPath; 7 | use crate::DescribeType; 8 | use crate::Reflect; 9 | 10 | #[test] 11 | #[allow(clippy::bool_assert_comparison)] 12 | fn works() { 13 | #[derive(Reflect, Clone, Debug)] 14 | #[reflect(crate_name(crate), opt_out(Default))] 15 | struct A { 16 | a: i32, 17 | b: B, 18 | c: C, 19 | d: BTreeMap, 20 | e: Vec, 21 | } 22 | 23 | #[derive(Reflect, Clone, Debug)] 24 | #[reflect(crate_name(crate), opt_out(Default))] 25 | struct B { 26 | c: bool, 27 | } 28 | 29 | #[derive(Reflect, Clone, Debug)] 30 | #[reflect(crate_name(crate), opt_out(Default))] 31 | enum C { 32 | C { d: String }, 33 | } 34 | 35 | let mut a = A { 36 | a: 42, 37 | b: B { c: true }, 38 | c: C::C { 39 | d: "foo".to_owned(), 40 | }, 41 | d: BTreeMap::from([("fourtytwo".to_owned(), 42)]), 42 | e: Vec::from([1.0, 2.0, 3.0]), 43 | }; 44 | 45 | assert!(a.get_at::(&key_path!()).is_some()); 46 | assert_eq!(a.get_at::(&key_path!(.a)).unwrap(), &42); 47 | assert_eq!(a.get_at::(&key_path!(.b.c)).unwrap(), &true); 48 | assert_eq!(a.get_at::(&key_path!(.c::C.d)).unwrap(), &"foo"); 49 | assert!(a.at(&key_path!(.c::DoesntExist)).is_none()); 50 | assert_eq!(a.get_at::(&key_path!(.d["fourtytwo"])).unwrap(), &42); 51 | 52 | assert_eq!(a.get_at::(&key_path!(.e[0])).unwrap(), &1.0); 53 | assert_eq!(a.get_at::(&key_path!(.e[1])).unwrap(), &2.0); 54 | assert_eq!(a.get_at::(&key_path!(.e[2])).unwrap(), &3.0); 55 | assert!(a.at(&key_path!(.e[3])).is_none()); 56 | 57 | assert_eq!(a.b.c, true); 58 | *a.get_at_mut(&key_path!(.b.c)).unwrap() = false; 59 | assert_eq!(a.b.c, false); 60 | } 61 | 62 | #[test] 63 | fn display() { 64 | assert_eq!( 65 | key_path!(.a.0.b.c[1]["foo"]::D.e[3]).to_string(), 66 | ".a.0.b.c[1][\"foo\"]::D.e[3]" 67 | ); 68 | } 69 | 70 | #[test] 71 | fn query_type_info_struct() { 72 | #[derive(Reflect, Clone, Debug, Default)] 73 | #[reflect(crate_name(crate))] 74 | struct User { 75 | employer: Company, 76 | } 77 | 78 | #[derive(Reflect, Clone, Debug, Default)] 79 | #[reflect(crate_name(crate))] 80 | struct Company { 81 | countries: Vec, 82 | } 83 | 84 | #[derive(Reflect, Clone, Debug, Default)] 85 | #[reflect(crate_name(crate))] 86 | struct Country { 87 | name: String, 88 | } 89 | 90 | let user = User { 91 | employer: Company { 92 | countries: Vec::from([Country { 93 | name: "Denmark".to_owned(), 94 | }]), 95 | }, 96 | }; 97 | 98 | let key_path = key_path!(.employer.countries[0].name); 99 | 100 | assert_eq!(user.get_at::(&key_path).unwrap(), "Denmark"); 101 | 102 | let type_info = ::type_descriptor(); 103 | 104 | assert!(matches!( 105 | dbg!(type_info.type_at(&key_path).unwrap()), 106 | TypeAtPath::Scalar(ScalarType::String) 107 | )); 108 | } 109 | 110 | #[test] 111 | fn query_type_info_enum() { 112 | #[derive(Reflect, Clone, Debug)] 113 | #[reflect(crate_name(crate), opt_out(Default))] 114 | enum Foo { 115 | A { a: String }, 116 | B(i32), 117 | C, 118 | } 119 | 120 | assert!(matches!( 121 | dbg!(::type_descriptor() 122 | .type_at(&key_path!(::A.a)) 123 | .unwrap()), 124 | TypeAtPath::Scalar(ScalarType::String) 125 | )); 126 | 127 | assert!(matches!( 128 | dbg!(::type_descriptor() 129 | .type_at(&key_path!(::B.0)) 130 | .unwrap()), 131 | TypeAtPath::Scalar(ScalarType::i32) 132 | )); 133 | 134 | assert!(::type_descriptor() 135 | .type_at(&key_path!(::B[0])) 136 | .is_none()); 137 | 138 | let info = ::type_descriptor(); 139 | let variant = info.type_at(&key_path!(::C)).unwrap().as_variant().unwrap(); 140 | 141 | assert_eq!(variant.name(), "C"); 142 | } 143 | 144 | #[test] 145 | fn select_tuple_field() { 146 | #[derive(Reflect, Clone, Debug, Default)] 147 | #[reflect(crate_name(crate))] 148 | struct Foo(i32, bool); 149 | 150 | let foo = Foo(42, true); 151 | 152 | assert_eq!(foo.get_at::(&key_path!(.0)).unwrap(), &42); 153 | assert_eq!(foo.get_at::(&key_path!(.1)).unwrap(), &true); 154 | } 155 | 156 | #[test] 157 | fn breadcrumbs() { 158 | let path = key_path!(.a.b.c.d); 159 | 160 | let actual = path 161 | .breadcrumbs() 162 | .map(|key| key.iter().cloned().collect::()); 163 | 164 | let expected = Vec::from([ 165 | key_path!(.a), 166 | key_path!(.a.b), 167 | key_path!(.a.b.c), 168 | key_path!(.a.b.c.d), 169 | ]); 170 | 171 | for (a, b) in actual.into_iter().zip(expected) { 172 | assert_eq!(a, b); 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/list.rs: -------------------------------------------------------------------------------- 1 | use crate::DescribeType; 2 | use crate::FromReflect; 3 | use crate::Reflect; 4 | use crate::ReflectMut; 5 | use crate::ReflectOwned; 6 | use crate::ReflectRef; 7 | use crate::Value; 8 | 9 | #[test] 10 | fn indexing() { 11 | let list = Vec::from([1, 2, 3]); 12 | let list = list.reflect_ref().as_list().unwrap(); 13 | 14 | assert_eq!(list.get(0).unwrap().downcast_ref::().unwrap(), &1); 15 | assert_eq!(list.get(1).unwrap().downcast_ref::().unwrap(), &2); 16 | assert_eq!(list.get(2).unwrap().downcast_ref::().unwrap(), &3); 17 | assert!(list.get(3).is_none()); 18 | 19 | let value = list.to_value(); 20 | let value = value.reflect_ref().as_list().unwrap(); 21 | assert_eq!(value.get(0).unwrap().downcast_ref::().unwrap(), &1); 22 | assert_eq!(value.get(1).unwrap().downcast_ref::().unwrap(), &2); 23 | assert_eq!(value.get(2).unwrap().downcast_ref::().unwrap(), &3); 24 | assert!(value.get(3).is_none()); 25 | 26 | let mut list = Vec::::from_reflect(list.as_reflect()).unwrap(); 27 | assert_eq!(list, Vec::from([1, 2, 3])); 28 | 29 | list.patch(&Vec::from([42])); 30 | assert_eq!(list, Vec::from([42, 2, 3])); 31 | } 32 | 33 | #[test] 34 | fn debug() { 35 | let list = Vec::from([1, 2, 3]); 36 | assert_eq!(format!("{:?}", list.as_reflect()), format!("{list:?}")); 37 | assert_eq!(format!("{:#?}", list.as_reflect()), format!("{list:#?}")); 38 | } 39 | 40 | #[test] 41 | fn remove() { 42 | let mut list = Vec::from([1, 2, 3]); 43 | let list = list.as_list_mut().unwrap(); 44 | assert_eq!( 45 | list.try_remove(2).unwrap().downcast_ref::().unwrap(), 46 | &3 47 | ); 48 | assert!(list.try_remove(2).is_none()); 49 | assert!(list.try_remove(1337).is_none()); 50 | } 51 | 52 | #[test] 53 | fn list_default_value_yields_list() { 54 | let ty = as DescribeType>::type_descriptor(); 55 | let default = ty.default_value().unwrap(); 56 | assert!(default.as_list().is_some()); 57 | 58 | // it is also valid as an array 59 | assert!(default.as_array().is_some()); 60 | } 61 | 62 | #[test] 63 | fn casting_list_to_list() { 64 | let mut list = Vec::::new(); 65 | assert!(list.as_list().is_some()); 66 | assert!(list.as_list_mut().is_some()); 67 | assert!(Box::new(list).into_list().is_some()); 68 | 69 | let mut list = Value::List(Vec::new()); 70 | assert!(list.as_list().is_some()); 71 | assert!(list.as_list_mut().is_some()); 72 | assert!(matches!(list.reflect_ref(), ReflectRef::List(_))); 73 | assert!(Box::new(list).into_list().is_some()); 74 | 75 | let mut list = Vec::::new(); 76 | assert!(matches!(list.reflect_ref(), ReflectRef::List(_))); 77 | assert!(matches!(list.reflect_mut(), ReflectMut::List(_))); 78 | assert!(matches!( 79 | Box::new(list).reflect_owned(), 80 | ReflectOwned::List(_) 81 | )); 82 | } 83 | 84 | #[test] 85 | fn casting_list_to_array() { 86 | let mut list = Vec::::new(); 87 | assert!(list.as_array().is_some()); 88 | assert!(list.as_array_mut().is_some()); 89 | assert!(matches!(list.reflect_ref(), ReflectRef::List(_))); 90 | assert!(Box::new(list).into_array().is_some()); 91 | 92 | let mut list = Value::List(Vec::new()); 93 | assert!(list.as_array().is_some()); 94 | assert!(list.as_array_mut().is_some()); 95 | assert!(matches!(list.reflect_ref(), ReflectRef::List(_))); 96 | assert!(Box::new(list).into_array().is_some()); 97 | 98 | let mut list = Value::List(Vec::new()); 99 | assert!(matches!(list.reflect_ref(), ReflectRef::List(_))); 100 | assert!(matches!(list.reflect_mut(), ReflectMut::List(_))); 101 | assert!(matches!( 102 | Box::new(list).reflect_owned(), 103 | ReflectOwned::List(_) 104 | )); 105 | } 106 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/map.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use alloc::collections::BTreeMap; 4 | 5 | use kollect::UnorderedMap; 6 | 7 | use crate::key_path; 8 | use crate::key_path::GetPath; 9 | use crate::DescribeType; 10 | use crate::GetField; 11 | use crate::GetFieldMut; 12 | use crate::Map; 13 | use crate::Reflect; 14 | 15 | #[test] 16 | fn works_btreemap() { 17 | let mut map = BTreeMap::from([(1, 1)]); 18 | let map = map.as_reflect_mut().as_map_mut().unwrap(); 19 | 20 | assert_eq!(map.get(&1).unwrap().downcast_ref::().unwrap(), &1); 21 | assert_eq!(map.get_field::(1_i32).unwrap(), &1); 22 | assert_eq!(map.get_field_mut::(1_i32).unwrap(), &mut 1); 23 | 24 | let map = BTreeMap::from([("foo".to_owned(), 1)]); 25 | let map = map.as_reflect().as_map().unwrap(); 26 | assert_eq!( 27 | map.get(&"foo".to_owned()) 28 | .unwrap() 29 | .downcast_ref::() 30 | .unwrap(), 31 | &1 32 | ); 33 | assert_eq!(map.get_field::("foo").unwrap(), &1); 34 | } 35 | 36 | #[test] 37 | fn works_unordered_map() { 38 | let mut map = UnorderedMap::from([(1, 1)]); 39 | 40 | { 41 | let map = map.as_reflect().as_map().unwrap(); 42 | 43 | assert_eq!(map.get(&1).unwrap().downcast_ref::().unwrap(), &1); 44 | assert_eq!(map.get_field::(1_i32).unwrap(), &1); 45 | assert_eq!(map.get_at::(&key_path!([1_i32])).unwrap(), &1); 46 | } 47 | 48 | { 49 | let map = map.as_reflect_mut().as_map_mut().unwrap(); 50 | 51 | assert_eq!( 52 | map.get_mut(&1).unwrap().downcast_mut::().unwrap(), 53 | &mut 1 54 | ); 55 | assert_eq!(map.get_field_mut::(1_i32).unwrap(), &mut 1); 56 | *map.get_at_mut::(&key_path!([1_i32])).unwrap() = 2; 57 | assert_eq!(map.get_at_mut::(&key_path!([1_i32])).unwrap(), &mut 2); 58 | } 59 | 60 | let mut map = UnorderedMap::from([("foo".to_owned(), 1)]); 61 | 62 | { 63 | let map = map.as_reflect().as_map().unwrap(); 64 | assert_eq!( 65 | map.get(&"foo".to_owned()) 66 | .unwrap() 67 | .downcast_ref::() 68 | .unwrap(), 69 | &1 70 | ); 71 | assert_eq!(map.get_field::("foo").unwrap(), &1); 72 | assert_eq!(map.get_at::(&key_path!(["foo"])).unwrap(), &1); 73 | } 74 | 75 | { 76 | let map = map.as_reflect_mut().as_map_mut().unwrap(); 77 | assert_eq!( 78 | map.get_mut(&"foo".to_owned()) 79 | .unwrap() 80 | .downcast_mut::() 81 | .unwrap(), 82 | &mut 1 83 | ); 84 | assert_eq!(map.get_field_mut::("foo").unwrap(), &mut 1); 85 | *map.get_at_mut::(&key_path!(["foo"])).unwrap() = 2; 86 | assert_eq!(map.get_at_mut::(&key_path!(["foo"])).unwrap(), &mut 2); 87 | } 88 | } 89 | 90 | #[test] 91 | fn works_hash_map() { 92 | let mut map = HashMap::from([(1, 1)]); 93 | 94 | { 95 | let map = map.as_reflect().as_map().unwrap(); 96 | 97 | assert_eq!(map.get(&1).unwrap().downcast_ref::().unwrap(), &1); 98 | assert_eq!(map.get_field::(1_i32).unwrap(), &1); 99 | assert_eq!(map.get_at::(&key_path!([1_i32])).unwrap(), &1); 100 | } 101 | 102 | { 103 | let map = map.as_reflect_mut().as_map_mut().unwrap(); 104 | 105 | assert_eq!( 106 | map.get_mut(&1).unwrap().downcast_mut::().unwrap(), 107 | &mut 1 108 | ); 109 | assert_eq!(map.get_field_mut::(1_i32).unwrap(), &mut 1); 110 | *map.get_at_mut::(&key_path!([1_i32])).unwrap() = 2; 111 | assert_eq!(map.get_at_mut::(&key_path!([1_i32])).unwrap(), &mut 2); 112 | } 113 | 114 | let mut map = HashMap::from([("foo".to_owned(), 1)]); 115 | 116 | { 117 | let map = map.as_reflect().as_map().unwrap(); 118 | assert_eq!( 119 | map.get(&"foo".to_owned()) 120 | .unwrap() 121 | .downcast_ref::() 122 | .unwrap(), 123 | &1 124 | ); 125 | assert_eq!(map.get_field::("foo").unwrap(), &1); 126 | assert_eq!(map.get_at::(&key_path!(["foo"])).unwrap(), &1); 127 | } 128 | 129 | { 130 | let map = map.as_reflect_mut().as_map_mut().unwrap(); 131 | assert_eq!( 132 | map.get_mut(&"foo".to_owned()) 133 | .unwrap() 134 | .downcast_mut::() 135 | .unwrap(), 136 | &mut 1 137 | ); 138 | assert_eq!(map.get_field_mut::("foo").unwrap(), &mut 1); 139 | *map.get_at_mut::(&key_path!(["foo"])).unwrap() = 2; 140 | assert_eq!(map.get_at_mut::(&key_path!(["foo"])).unwrap(), &mut 2); 141 | } 142 | } 143 | 144 | #[test] 145 | fn exotic_key_type() { 146 | #[derive(Clone, Debug, Default, Ord, PartialOrd, Eq, PartialEq, Reflect, Hash)] 147 | #[reflect(crate_name(crate))] 148 | struct Foo(i32); 149 | 150 | let mut map = UnorderedMap::from([(Foo(1), 1), (Foo(2), 2)]); 151 | 152 | { 153 | let map: &dyn Map = map.as_map().unwrap(); 154 | 155 | assert_eq!(map.get(&Foo(1)).unwrap().downcast_ref::().unwrap(), &1); 156 | assert_eq!(map.get(&Foo(2)).unwrap().downcast_ref::().unwrap(), &2); 157 | assert!(map.get(&Foo(3)).is_none()); 158 | 159 | assert_eq!(map.get_at::(&key_path!([Foo(1)])).unwrap(), &1); 160 | assert_eq!(map.get_at::(&key_path!([Foo(2)])).unwrap(), &2); 161 | assert!(map.get_at::(&key_path!([Foo(3)])).is_none()); 162 | } 163 | 164 | { 165 | let map = map.as_map_mut().unwrap(); 166 | 167 | assert_eq!( 168 | map.get_mut(&Foo(1)).unwrap().downcast_mut::().unwrap(), 169 | &mut 1 170 | ); 171 | assert_eq!( 172 | map.get_mut(&Foo(2)).unwrap().downcast_mut::().unwrap(), 173 | &mut 2 174 | ); 175 | assert!(map.get_mut(&Foo(3)).is_none()); 176 | 177 | assert_eq!(map.get_at_mut::(&key_path!([Foo(1)])).unwrap(), &mut 1); 178 | assert_eq!(map.get_at_mut::(&key_path!([Foo(2)])).unwrap(), &mut 2); 179 | assert!(map.get_at_mut::(&key_path!([Foo(3)])).is_none()); 180 | } 181 | } 182 | 183 | #[test] 184 | fn exoctic_value_type() { 185 | #[derive(Debug, Clone, Default, Reflect)] 186 | #[reflect(crate_name(crate))] 187 | struct Foo { 188 | array: [i32; 5], 189 | tuple: (Vec, bool), 190 | } 191 | 192 | let mut map = UnorderedMap::::new(); 193 | let foo_default_value = ::type_descriptor() 194 | .default_value() 195 | .unwrap(); 196 | map.as_map_mut() 197 | .unwrap() 198 | .try_insert(&1, &foo_default_value) 199 | .unwrap(); 200 | assert_eq!(map.len(), 1); 201 | } 202 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/meta.rs: -------------------------------------------------------------------------------- 1 | use crate::type_info::GetMeta; 2 | use crate::DescribeType; 3 | use crate::Reflect; 4 | 5 | #[test] 6 | fn works() { 7 | #[derive(Reflect, Debug, Clone, Default)] 8 | #[reflect(crate_name(crate), meta(foo = "bar", baz = 42))] 9 | struct Foo; 10 | 11 | let type_info = ::type_descriptor(); 12 | let type_info = type_info.get_type().as_struct().unwrap(); 13 | 14 | assert_eq!( 15 | type_info 16 | .meta("foo") 17 | .unwrap() 18 | .downcast_ref::() 19 | .unwrap(), 20 | "bar" 21 | ); 22 | 23 | assert_eq!( 24 | type_info 25 | .meta("baz") 26 | .unwrap() 27 | .downcast_ref::() 28 | .unwrap(), 29 | &42, 30 | ); 31 | } 32 | 33 | #[derive(Reflect, Debug, Default, Clone)] 34 | #[reflect(crate_name(crate), meta(n = 1))] 35 | struct A { 36 | #[reflect(meta(n = 1))] 37 | a: String, 38 | } 39 | 40 | #[derive(Reflect, Debug, Default, Clone)] 41 | #[reflect(crate_name(crate), meta(n = 1))] 42 | struct B(#[reflect(meta(n = 1))] String); 43 | 44 | #[derive(Reflect, Debug, Clone)] 45 | #[reflect(crate_name(crate), meta(n = 1), opt_out(Default))] 46 | enum C { 47 | #[reflect(meta(n = 1))] 48 | A { 49 | #[reflect(meta(n = 1))] 50 | a: String, 51 | }, 52 | 53 | #[reflect(meta(n = 1))] 54 | B(#[reflect(meta(n = 1))] String), 55 | 56 | #[reflect(meta(n = 1))] 57 | #[allow(clippy::enum_variant_names)] 58 | C, 59 | } 60 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::dbg_macro)] 2 | 3 | use crate::Reflect; 4 | 5 | mod array; 6 | mod enum_; 7 | mod key_path; 8 | mod list; 9 | mod map; 10 | mod meta; 11 | mod simple_type_name; 12 | mod struct_; 13 | mod tuple; 14 | mod tuple_struct; 15 | mod type_info; 16 | mod value; 17 | 18 | #[derive(Reflect)] 19 | #[reflect(crate_name(crate), opt_out(Debug, Clone, Default))] 20 | #[allow(dead_code)] 21 | struct DebugOptOut; 22 | 23 | #[derive(Reflect)] 24 | #[reflect(crate_name(crate), opt_out(Debug, Clone, Default))] 25 | #[allow(dead_code)] 26 | struct ContainsBoxed(Box); 27 | 28 | mod complex_types { 29 | #![allow(dead_code)] 30 | 31 | use alloc::collections::BTreeMap; 32 | 33 | use crate::Reflect; 34 | 35 | #[derive(Reflect, Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq)] 36 | #[reflect(crate_name(crate))] 37 | struct A { 38 | a: String, 39 | b: Vec, 40 | d: BTreeMap>, 41 | } 42 | 43 | #[derive(Reflect, Debug, Clone, Ord, PartialOrd, Eq, PartialEq)] 44 | #[reflect(crate_name(crate), opt_out(Default))] 45 | enum B { 46 | C(C), 47 | D { d: D }, 48 | } 49 | 50 | #[derive(Reflect, Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq)] 51 | #[reflect(crate_name(crate))] 52 | struct C(String, i32, Vec); 53 | 54 | #[derive(Reflect, Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq)] 55 | #[reflect(crate_name(crate))] 56 | struct D; 57 | } 58 | 59 | mod skip { 60 | #![allow(dead_code)] 61 | 62 | use super::*; 63 | 64 | #[derive(Reflect, Debug, Clone, Default)] 65 | #[reflect(crate_name(crate))] 66 | struct TestStruct { 67 | #[reflect(skip)] 68 | not_reflect: NotReflect, 69 | } 70 | 71 | #[derive(Reflect, Debug, Clone, Default)] 72 | #[reflect(crate_name(crate))] 73 | struct TestTupleStruct(#[reflect(skip)] NotReflect); 74 | 75 | #[derive(Reflect, Debug, Clone)] 76 | #[reflect(crate_name(crate), opt_out(Default))] 77 | #[allow(clippy::enum_variant_names)] 78 | enum TestEnum { 79 | #[reflect(skip)] 80 | SkipStructVariant { 81 | not_reflect: NotReflect, 82 | }, 83 | SkipStructField { 84 | #[reflect(skip)] 85 | not_reflect: NotReflect, 86 | }, 87 | #[reflect(skip)] 88 | SkipTupleVariant(NotReflect), 89 | SkipTupleField(#[reflect(skip)] NotReflect), 90 | #[reflect(skip)] 91 | SkipUnitVariant, 92 | } 93 | 94 | #[derive(Debug, Clone, Default)] 95 | struct NotReflect; 96 | } 97 | 98 | mod option_f32 { 99 | #![allow(dead_code)] 100 | 101 | use super::*; 102 | 103 | #[derive(Debug, Clone, Reflect, Default)] 104 | #[reflect(crate_name(crate))] 105 | struct Foo { 106 | maybe_float: Option, 107 | maybe_string: Option, 108 | } 109 | } 110 | 111 | mod derive_foreign { 112 | #![allow(dead_code)] 113 | 114 | use mirror_mirror_macros::*; 115 | 116 | use crate::DescribeType; 117 | use crate::FromReflect; 118 | 119 | enum Foo 120 | where 121 | A: FromReflect + DescribeType, 122 | B: FromReflect + DescribeType, 123 | { 124 | Struct { a: A }, 125 | Tuple(B), 126 | Unit, 127 | } 128 | 129 | __private_derive_reflect_foreign! { 130 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 131 | enum Foo 132 | where 133 | A: FromReflect + DescribeType, 134 | B: FromReflect + DescribeType, 135 | { 136 | Struct { a: A }, 137 | Tuple(B), 138 | Unit, 139 | } 140 | } 141 | 142 | struct Bar 143 | where 144 | A: FromReflect + DescribeType, 145 | B: FromReflect + DescribeType, 146 | { 147 | a: A, 148 | b: B, 149 | } 150 | 151 | __private_derive_reflect_foreign! { 152 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 153 | struct Bar 154 | where 155 | A: FromReflect + DescribeType, 156 | B: FromReflect + DescribeType, 157 | { 158 | a: A, 159 | b: B, 160 | } 161 | } 162 | 163 | struct Baz(A, B) 164 | where 165 | A: FromReflect + DescribeType, 166 | B: FromReflect + DescribeType; 167 | 168 | __private_derive_reflect_foreign! { 169 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 170 | struct Baz(A, B) 171 | where 172 | A: FromReflect + DescribeType, 173 | B: FromReflect + DescribeType; 174 | } 175 | 176 | struct Qux; 177 | 178 | __private_derive_reflect_foreign! { 179 | #[reflect(opt_out(Clone, Debug, Default), crate_name(crate))] 180 | struct Qux; 181 | } 182 | } 183 | 184 | mod from_reflect_opt_out { 185 | #![allow(warnings)] 186 | 187 | use super::*; 188 | use crate::FromReflect; 189 | 190 | #[derive(Reflect, Debug, Clone, Copy, Default, PartialEq)] 191 | #[reflect(crate_name(crate), opt_out(FromReflect))] 192 | struct Percentage(f32); 193 | 194 | impl FromReflect for Percentage { 195 | fn from_reflect(reflect: &dyn Reflect) -> Option { 196 | if let Some(this) = reflect.downcast_ref::() { 197 | Some(*this) 198 | } else if let Some(value) = f32::from_reflect(reflect) { 199 | Some(Self(value.clamp(0.0, 100.0))) 200 | } else if let Some(value) = f64::from_reflect(reflect) { 201 | Some(Self((value as f32).clamp(0.0, 100.0))) 202 | } else { 203 | None 204 | } 205 | } 206 | } 207 | 208 | #[test] 209 | fn works() { 210 | assert_eq!( 211 | Percentage::from_reflect(&Percentage(10.0)).unwrap(), 212 | Percentage(10.0) 213 | ); 214 | 215 | assert_eq!(Percentage::from_reflect(&10.0).unwrap(), Percentage(10.0)); 216 | 217 | assert_eq!( 218 | Percentage::from_reflect(&1337.0).unwrap(), 219 | Percentage(100.0) 220 | ); 221 | } 222 | 223 | #[derive(Reflect, Debug, Clone, Default)] 224 | #[reflect(crate_name(crate), opt_out(FromReflect))] 225 | struct B { 226 | n: f32, 227 | } 228 | 229 | impl FromReflect for B { 230 | fn from_reflect(reflect: &dyn Reflect) -> Option { 231 | None 232 | } 233 | } 234 | 235 | #[derive(Reflect, Debug, Clone)] 236 | #[reflect(crate_name(crate), opt_out(FromReflect, Default))] 237 | enum C { 238 | A(f32), 239 | } 240 | 241 | impl FromReflect for C { 242 | fn from_reflect(reflect: &dyn Reflect) -> Option { 243 | None 244 | } 245 | } 246 | } 247 | 248 | mod from_reflect_with { 249 | #![allow(warnings)] 250 | 251 | use super::*; 252 | use crate::FromReflect; 253 | 254 | #[derive(Reflect, Debug, Clone, Copy, PartialEq)] 255 | #[reflect(crate_name(crate), opt_out(Default))] 256 | struct A { 257 | #[reflect(from_reflect_with(clamp_ratio))] 258 | a: f32, 259 | } 260 | 261 | #[derive(Reflect, Debug, Clone, Copy, PartialEq)] 262 | #[reflect(crate_name(crate), opt_out(Default))] 263 | struct B(#[reflect(from_reflect_with(clamp_ratio))] f32); 264 | 265 | #[derive(Reflect, Debug, Clone, Copy, PartialEq)] 266 | #[reflect(crate_name(crate), opt_out(Default))] 267 | enum C { 268 | C(#[reflect(from_reflect_with(clamp_ratio))] f32), 269 | D { 270 | #[reflect(from_reflect_with(clamp_ratio))] 271 | d: f32, 272 | }, 273 | } 274 | 275 | fn clamp_ratio(ratio: &dyn Reflect) -> Option { 276 | Some(ratio.downcast_ref::()?.clamp(0.0, 1.0)) 277 | } 278 | 279 | #[test] 280 | fn works() { 281 | assert_eq!(A::from_reflect(&A { a: 100.0 }).unwrap(), A { a: 1.0 }); 282 | assert_eq!(A::from_reflect(&A { a: -100.0 }).unwrap(), A { a: 0.0 }); 283 | 284 | assert_eq!(B::from_reflect(&B(100.0)).unwrap(), B(1.0)); 285 | assert_eq!(B::from_reflect(&B(-100.0)).unwrap(), B(0.0)); 286 | 287 | assert_eq!(C::from_reflect(&C::C(100.0)).unwrap(), C::C(1.0)); 288 | assert_eq!(C::from_reflect(&C::C(-100.0)).unwrap(), C::C(0.0)); 289 | 290 | assert_eq!( 291 | C::from_reflect(&C::D { d: 100.0 }).unwrap(), 292 | C::D { d: 1.0 } 293 | ); 294 | assert_eq!( 295 | C::from_reflect(&C::D { d: -100.0 }).unwrap(), 296 | C::D { d: 0.0 } 297 | ); 298 | } 299 | } 300 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/simple_type_name.rs: -------------------------------------------------------------------------------- 1 | use alloc::collections::BTreeMap; 2 | 3 | use crate::type_info::SimpleTypeName; 4 | 5 | fn simple_type_name() -> String { 6 | SimpleTypeName::new_from_type::().to_string() 7 | } 8 | 9 | #[test] 10 | fn works() { 11 | #[allow(dead_code)] 12 | struct Foo<'a, const N: usize>(&'a ()); 13 | 14 | assert_eq!(simple_type_name::(), "String"); 15 | assert_eq!(simple_type_name::(), "i32"); 16 | assert_eq!(simple_type_name::(), "bool"); 17 | assert_eq!(simple_type_name::<()>(), "()"); 18 | assert_eq!(simple_type_name::<(i32,)>(), "(i32,)"); 19 | assert_eq!(simple_type_name::<(i32, String)>(), "(i32, String)"); 20 | assert_eq!(simple_type_name::>(), "Vec"); 21 | assert_eq!(simple_type_name::>(), "Vec<&()>"); 22 | assert_eq!(simple_type_name::>(), "Vec<&mut ()>"); 23 | assert_eq!(simple_type_name::>(), "Vec<&()>"); 24 | assert_eq!(simple_type_name::>(), "Vec<&mut ()>"); 25 | assert_eq!(simple_type_name::>(), "Option"); 26 | assert_eq!( 27 | simple_type_name::>(), 28 | "BTreeMap" 29 | ); 30 | assert_eq!( 31 | simple_type_name::)>, String>>(), 32 | "BTreeMap)>, String>" 33 | ); 34 | assert_eq!(simple_type_name::<[i32; 10]>(), "[i32; 10]"); 35 | assert_eq!( 36 | simple_type_name::<[BTreeMap; 10]>(), 37 | "[BTreeMap; 10]" 38 | ); 39 | // type names don't include lifetimes 40 | assert_eq!(simple_type_name::>(), "Foo<10>"); 41 | assert_eq!(simple_type_name::>(), "Box"); 42 | } 43 | 44 | #[test] 45 | fn type_inside_unnamed_const() { 46 | trait A { 47 | type T; 48 | } 49 | 50 | struct Foo; 51 | 52 | const _: () = { 53 | struct Bar(T); 54 | 55 | impl A for Foo { 56 | type T = Bar; 57 | } 58 | }; 59 | 60 | assert_eq!(simple_type_name::<::T>(), "Bar"); 61 | } 62 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/tuple.rs: -------------------------------------------------------------------------------- 1 | use crate::tuple::TupleValue; 2 | use crate::DescribeType; 3 | use crate::FromReflect; 4 | use crate::GetField; 5 | use crate::Reflect; 6 | 7 | #[test] 8 | fn tuple_value() { 9 | let mut tuple = TupleValue::new().with_field(1_i32).with_field(false); 10 | 11 | assert_eq!(tuple.get_field::(0).unwrap(), &1); 12 | assert_eq!(tuple.get_field::(1).unwrap(), &false); 13 | 14 | tuple.patch(&TupleValue::new().with_field(42_i32)); 15 | assert_eq!(tuple.get_field::(0).unwrap(), &42); 16 | assert_eq!(tuple.get_field::(1).unwrap(), &false); 17 | } 18 | 19 | #[test] 20 | fn static_tuple() { 21 | let mut tuple = (1_i32, false); 22 | 23 | assert_eq!(tuple.get_field::(0).unwrap(), &1); 24 | assert_eq!(tuple.get_field::(1).unwrap(), &false); 25 | 26 | tuple.patch(&TupleValue::new().with_field(42_i32)); 27 | assert_eq!(tuple.get_field::(0).unwrap(), &42); 28 | assert_eq!(tuple.get_field::(1).unwrap(), &false); 29 | } 30 | 31 | #[test] 32 | fn from_default() { 33 | type Pair = (i32, bool); 34 | 35 | let default_value = ::type_descriptor() 36 | .default_value() 37 | .unwrap(); 38 | 39 | let foo = Pair::from_reflect(&default_value).unwrap(); 40 | 41 | assert_eq!(foo, (0, false)); 42 | } 43 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/tuple_struct.rs: -------------------------------------------------------------------------------- 1 | use alloc::vec::Vec; 2 | 3 | use crate::tuple_struct::TupleStructValue; 4 | use crate::DescribeType; 5 | use crate::FromReflect; 6 | use crate::GetField; 7 | use crate::Reflect; 8 | use crate::TupleStruct; 9 | 10 | #[test] 11 | fn tuple_value() { 12 | let mut tuple = TupleStructValue::new().with_field(1_i32).with_field(false); 13 | 14 | assert_eq!(tuple.get_field::(0).unwrap(), &1); 15 | assert_eq!(tuple.get_field::(1).unwrap(), &false); 16 | 17 | tuple.patch(&TupleStructValue::new().with_field(42_i32)); 18 | assert_eq!(tuple.get_field::(0).unwrap(), &42); 19 | assert_eq!(tuple.get_field::(1).unwrap(), &false); 20 | } 21 | 22 | #[test] 23 | fn static_tuple() { 24 | #[derive(Reflect, Default, Clone, Eq, PartialEq, Debug)] 25 | #[reflect(crate_name(crate))] 26 | struct A(i32, bool); 27 | 28 | let mut tuple = A(1_i32, false); 29 | 30 | assert_eq!(tuple.get_field::(0).unwrap(), &1); 31 | assert_eq!(tuple.get_field::(1).unwrap(), &false); 32 | 33 | tuple.patch(&TupleStructValue::new().with_field(42_i32)); 34 | assert_eq!(tuple.get_field::(0).unwrap(), &42); 35 | assert_eq!(tuple.get_field::(1).unwrap(), &false); 36 | 37 | let mut tuple = A::from_reflect(&tuple.to_value()).unwrap(); 38 | assert!(matches!(tuple, A(42, false))); 39 | 40 | let fields = tuple.fields().collect::>(); 41 | assert_eq!(fields.len(), 2); 42 | assert_eq!(fields[0].downcast_ref::().unwrap(), &42); 43 | assert_eq!(fields[1].downcast_ref::().unwrap(), &false); 44 | 45 | tuple.field_at_mut(1).unwrap().patch(&true); 46 | assert!(tuple.1); 47 | } 48 | 49 | #[test] 50 | fn from_reflect_with_value() { 51 | #[derive(Debug, Clone, Reflect, Default)] 52 | #[reflect(crate_name(crate))] 53 | pub struct Foo(Number); 54 | 55 | #[derive(Debug, Clone, Reflect, Default)] 56 | #[reflect(crate_name(crate))] 57 | pub enum Number { 58 | #[default] 59 | One, 60 | Two, 61 | Three, 62 | } 63 | 64 | let value = TupleStructValue::new().with_field(Number::One); 65 | 66 | assert!(Foo::from_reflect(&value).is_some()); 67 | } 68 | #[test] 69 | fn default_value() { 70 | #[derive(Reflect, Debug, Clone, Copy)] 71 | #[reflect(crate_name(crate))] 72 | struct Foo(u32, u32); 73 | 74 | impl Default for Foo { 75 | fn default() -> Self { 76 | Foo(1, 2) 77 | } 78 | } 79 | 80 | #[derive(Reflect, Debug, Clone, Copy)] 81 | #[reflect(crate_name(crate), opt_out(Default))] 82 | struct Bar(u32, u32); 83 | 84 | let foo_descriptor = ::type_descriptor(); 85 | let bar_descriptor = ::type_descriptor(); 86 | 87 | assert!(foo_descriptor.has_default_value()); 88 | assert!(!bar_descriptor.has_default_value()); 89 | 90 | let foo_default = Foo::default().to_value(); 91 | 92 | assert_eq!(foo_descriptor.default_value(), Some(foo_default)); 93 | assert_eq!(bar_descriptor.default_value(), None); 94 | } 95 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/type_info.rs: -------------------------------------------------------------------------------- 1 | use core::any::type_name; 2 | use core::hash::Hash; 3 | 4 | use alloc::collections::BTreeMap; 5 | 6 | use crate::key_path; 7 | use crate::key_path::GetPath; 8 | use crate::tuple_struct::TupleStructValue; 9 | use crate::type_info::graph::OpaqueNode; 10 | use crate::type_info::*; 11 | use crate::FromReflect; 12 | use crate::Reflect; 13 | use crate::Value; 14 | 15 | #[test] 16 | fn struct_() { 17 | #[derive(Reflect, Clone, Debug, Default)] 18 | #[reflect(crate_name(crate))] 19 | struct Foo { 20 | n: i32, 21 | foos: Vec, 22 | } 23 | 24 | let type_info = ::type_descriptor(); 25 | 26 | assert_eq!( 27 | type_info.get_type().type_name(), 28 | "mirror_mirror::tests::type_info::struct_::Foo" 29 | ); 30 | 31 | let struct_ = type_info.get_type().as_struct().unwrap(); 32 | 33 | assert_eq!( 34 | struct_.type_name(), 35 | "mirror_mirror::tests::type_info::struct_::Foo" 36 | ); 37 | 38 | for field in struct_.field_types() { 39 | match field.name() { 40 | "foos" => { 41 | assert_eq!( 42 | field.get_type().type_name(), 43 | "alloc::vec::Vec" 44 | ); 45 | 46 | let list = field.get_type().as_list().unwrap(); 47 | 48 | assert_eq!( 49 | list.type_name(), 50 | "alloc::vec::Vec" 51 | ); 52 | 53 | assert_eq!( 54 | list.element_type().type_name(), 55 | "mirror_mirror::tests::type_info::struct_::Foo" 56 | ); 57 | } 58 | "n" => { 59 | assert_eq!(field.get_type().type_name(), "i32"); 60 | let scalar = field.get_type().as_scalar().unwrap(); 61 | assert_eq!(scalar.type_name(), "i32"); 62 | } 63 | _ => panic!("wat"), 64 | } 65 | } 66 | } 67 | 68 | #[test] 69 | fn enum_() { 70 | #[derive(Reflect, Clone, Debug)] 71 | #[reflect(crate_name(crate), opt_out(Default))] 72 | enum Foo { 73 | A { a: String }, 74 | B(Vec), 75 | C, 76 | } 77 | } 78 | 79 | #[test] 80 | fn complex_meta_type() { 81 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 82 | #[reflect(crate_name(crate), meta(a = Foo(1337)))] 83 | struct Foo(i32); 84 | 85 | let type_info = ::type_descriptor(); 86 | 87 | let foo = type_info.get_type().get_meta::("a").unwrap(); 88 | assert_eq!(foo, Foo(1337)); 89 | } 90 | 91 | #[test] 92 | fn type_to_root() { 93 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 94 | #[reflect(crate_name(crate), meta(a = Foo(1337)))] 95 | struct Foo(i32); 96 | 97 | let type_info = ::type_descriptor(); 98 | 99 | assert_eq!( 100 | type_info.get_type().as_tuple_struct().unwrap().type_name(), 101 | type_name::() 102 | ); 103 | 104 | let type_info = type_info 105 | .get_type() 106 | .as_tuple_struct() 107 | .unwrap() 108 | .into_type_descriptor(); 109 | assert_eq!(type_info.get_type().type_name(), type_name::()); 110 | } 111 | 112 | #[test] 113 | fn two_types() { 114 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 115 | #[reflect(crate_name(crate))] 116 | struct Foo(i32); 117 | 118 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 119 | #[reflect(crate_name(crate))] 120 | struct Bar(bool); 121 | 122 | assert_eq!( 123 | ::type_descriptor() 124 | .as_tuple_struct() 125 | .unwrap() 126 | .field_type_at(0) 127 | .unwrap() 128 | .get_type() 129 | .as_scalar() 130 | .unwrap(), 131 | ScalarType::i32, 132 | ); 133 | 134 | assert_eq!( 135 | ::type_descriptor() 136 | .as_tuple_struct() 137 | .unwrap() 138 | .field_type_at(0) 139 | .unwrap() 140 | .get_type() 141 | .as_scalar() 142 | .unwrap(), 143 | ScalarType::bool, 144 | ) 145 | } 146 | 147 | #[test] 148 | fn how_to_handle_generics() { 149 | #[derive(Reflect, Clone, Debug, PartialEq, Eq)] 150 | #[reflect(crate_name(crate), opt_out(Debug, Clone, Default))] 151 | struct Foo(T) 152 | where 153 | T: Reflect + FromReflect + DescribeType; 154 | 155 | assert_eq!( 156 | as DescribeType>::type_descriptor() 157 | .as_tuple_struct() 158 | .unwrap() 159 | .field_type_at(0) 160 | .unwrap() 161 | .get_type() 162 | .as_scalar() 163 | .unwrap(), 164 | ScalarType::i32, 165 | ); 166 | 167 | assert_eq!( 168 | as DescribeType>::type_descriptor() 169 | .as_tuple_struct() 170 | .unwrap() 171 | .field_type_at(0) 172 | .unwrap() 173 | .get_type() 174 | .as_scalar() 175 | .unwrap(), 176 | ScalarType::bool, 177 | ); 178 | } 179 | 180 | #[test] 181 | fn opaque_default() { 182 | struct Opaque(i32); 183 | 184 | impl DescribeType for Opaque { 185 | fn build(graph: &mut graph::TypeGraph) -> graph::NodeId { 186 | graph.get_or_build_node_with::(|graph| { 187 | OpaqueNode::new::(Default::default(), graph).default_value(Opaque(1337)) 188 | }) 189 | } 190 | } 191 | 192 | impl From for Value { 193 | fn from(opaque: Opaque) -> Self { 194 | let Opaque(n) = opaque; 195 | TupleStructValue::new().with_field(n).to_value() 196 | } 197 | } 198 | 199 | let type_descriptor = Opaque::type_descriptor(); 200 | 201 | let default_value = type_descriptor.default_value().unwrap(); 202 | 203 | assert_eq!(default_value.get_at::(&key_path!(.0)).unwrap(), &1337); 204 | } 205 | 206 | #[test] 207 | fn basic_eq() { 208 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 209 | #[reflect(crate_name(crate))] 210 | struct Foo(i32); 211 | 212 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 213 | #[reflect(crate_name(crate))] 214 | struct Bar { 215 | b: bool, 216 | } 217 | 218 | assert_eq!( 219 | ::type_descriptor(), 220 | ::type_descriptor(), 221 | ); 222 | 223 | assert_eq!( 224 | ::type_descriptor(), 225 | ::type_descriptor(), 226 | ); 227 | 228 | assert_ne!( 229 | ::type_descriptor(), 230 | ::type_descriptor(), 231 | ); 232 | } 233 | 234 | #[test] 235 | fn basic_hash() { 236 | use std::collections::hash_map::RandomState; 237 | use std::hash::{BuildHasher, Hasher}; 238 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 239 | #[reflect(crate_name(crate))] 240 | struct Foo { 241 | a: i32, 242 | } 243 | 244 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 245 | #[reflect(crate_name(crate))] 246 | struct Bar { 247 | b: bool, 248 | foo: Foo, 249 | c: Vec, 250 | } 251 | 252 | let s = RandomState::new(); 253 | 254 | let mut hasher = s.build_hasher(); 255 | ::type_descriptor().hash(&mut hasher); 256 | let foo_hash = hasher.finish(); 257 | 258 | let mut hasher = s.build_hasher(); 259 | ::type_descriptor().hash(&mut hasher); 260 | let bar_hash = hasher.finish(); 261 | 262 | assert_ne!(foo_hash, bar_hash); 263 | 264 | let mut hasher = s.build_hasher(); 265 | ::type_descriptor().hash(&mut hasher); 266 | let foo_hash_2 = hasher.finish(); 267 | 268 | let mut hasher = s.build_hasher(); 269 | ::type_descriptor().hash(&mut hasher); 270 | let bar_hash_2 = hasher.finish(); 271 | 272 | assert_eq!(foo_hash, foo_hash_2); 273 | assert_eq!(bar_hash, bar_hash_2); 274 | } 275 | 276 | // TODO: 277 | // we should guarantee deterministic hash of `TypeDescriptor` stays static across compatible versions. 278 | // if we need to update this test, then we also likely need to release a new semver breaking version. 279 | // Sadly we cannot right now because `NodeId` uses `std::any::TypeId` to determine its hash, which 280 | // is not stable... should investigate other ways, hashing the fully qualified type name? 281 | /* 282 | #[test] 283 | fn basic_static_hash() { 284 | use crate::STATIC_RANDOM_STATE; 285 | #[derive(Default, Reflect, Clone, Debug)] 286 | #[reflect(crate_name(crate))] 287 | struct Foo { 288 | a: i32, 289 | } 290 | 291 | #[derive(Default, Reflect, Clone, Debug)] 292 | #[reflect(crate_name(crate))] 293 | struct Bar { 294 | b: bool, 295 | foo: Foo, 296 | c: Vec, 297 | } 298 | 299 | let foo_desc = ::type_descriptor().into_owned(); 300 | let foo_hash = STATIC_RANDOM_STATE.hash_one(&foo_desc); 301 | 302 | eprintln!("{:#?}", foo_desc); 303 | assert_eq!(foo_hash, 4657325414717586457); // precomputed hash of Foo descriptor 304 | 305 | let bar_desc = ::type_descriptor().into_owned(); 306 | let bar_hash = STATIC_RANDOM_STATE.hash_one(&bar_desc); 307 | 308 | eprintln!("{:#?}", bar_desc); 309 | assert_eq!(bar_hash, 11082174673177877468); // precomputed hash of Bar descriptor 310 | } 311 | */ 312 | 313 | #[test] 314 | fn has_default_value() { 315 | #[derive(Reflect, Clone, Debug, Default)] 316 | #[reflect(crate_name(crate))] 317 | struct A { 318 | a: String, 319 | } 320 | 321 | #[derive(Reflect, Clone, Debug, Default)] 322 | #[reflect(crate_name(crate))] 323 | struct B(String); 324 | 325 | #[derive(Reflect, Clone, Debug)] 326 | #[reflect(crate_name(crate))] 327 | enum C { 328 | C(i32), 329 | } 330 | 331 | impl Default for C { 332 | fn default() -> Self { 333 | Self::C(0) 334 | } 335 | } 336 | 337 | assert!(::type_descriptor().has_default_value()); 338 | assert!(::type_descriptor().has_default_value()); 339 | assert!(::type_descriptor().has_default_value()); 340 | assert!(<(i32, String) as DescribeType>::type_descriptor().has_default_value()); 341 | assert!(<[i32; 3] as DescribeType>::type_descriptor().has_default_value()); 342 | assert!( as DescribeType>::type_descriptor().has_default_value()); 343 | assert!(::type_descriptor().has_default_value()); 344 | 345 | // value doesn't have a default 346 | assert!(!<[Value; 3] as DescribeType>::type_descriptor().has_default_value()); 347 | assert!(!::type_descriptor().has_default_value()); 348 | } 349 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tests/value.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use crate::{DescribeType, FromReflect, Reflect}; 4 | 5 | #[test] 6 | fn option_uses_none_as_default() { 7 | #[derive(Reflect, Clone, Debug, Default, PartialEq, Eq)] 8 | #[reflect(crate_name(crate))] 9 | struct Foo { 10 | x: Option, 11 | } 12 | 13 | let default = ::type_descriptor() 14 | .default_value() 15 | .unwrap(); 16 | 17 | let foo = Foo::from_reflect(&default).expect("`from_reflect` failed"); 18 | assert_eq!(foo, Foo { x: None }); 19 | } 20 | 21 | #[test] 22 | fn hash() { 23 | let map = HashMap::from([ 24 | (1_i32.to_value(), "one"), 25 | ("foo".to_owned().to_value(), "two"), 26 | ]); 27 | 28 | assert_eq!(map.get(&1_i32.to_value()).unwrap(), &"one"); 29 | assert_eq!(map.get(&"foo".to_owned().to_value()).unwrap(), &"two"); 30 | assert!(!map.contains_key(&true.to_value())); 31 | } 32 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/try_visit.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | type_info::{OpaqueType, Type, VariantField}, 3 | Reflect, ScalarRef, 4 | }; 5 | use alloc::string::String; 6 | 7 | macro_rules! visit_scalar_fn { 8 | ($name:ident, $ty:ty) => { 9 | #[allow(clippy::ptr_arg)] 10 | #[inline] 11 | fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { 12 | Ok(()) 13 | } 14 | }; 15 | } 16 | 17 | #[allow(unused_variables)] 18 | pub trait TryVisit { 19 | type Error; 20 | 21 | visit_scalar_fn!(try_visit_usize, usize); 22 | visit_scalar_fn!(try_visit_u8, u8); 23 | visit_scalar_fn!(try_visit_u16, u16); 24 | visit_scalar_fn!(try_visit_u32, u32); 25 | visit_scalar_fn!(try_visit_u64, u64); 26 | visit_scalar_fn!(try_visit_u128, u128); 27 | visit_scalar_fn!(try_visit_i8, i8); 28 | visit_scalar_fn!(try_visit_i16, i16); 29 | visit_scalar_fn!(try_visit_i32, i32); 30 | visit_scalar_fn!(try_visit_i64, i64); 31 | visit_scalar_fn!(try_visit_i128, i128); 32 | visit_scalar_fn!(try_visit_bool, bool); 33 | visit_scalar_fn!(try_visit_char, char); 34 | visit_scalar_fn!(try_visit_f32, f32); 35 | visit_scalar_fn!(try_visit_f64, f64); 36 | visit_scalar_fn!(try_visit_string, &String); 37 | 38 | #[inline] 39 | fn try_visit_opaque( 40 | &mut self, 41 | value: &dyn Reflect, 42 | ty: OpaqueType<'_>, 43 | ) -> Result<(), Self::Error> { 44 | Ok(()) 45 | } 46 | } 47 | 48 | pub fn try_visit(visitor: &mut V, value: &dyn Reflect, ty: Type<'_>) -> Result<(), V::Error> 49 | where 50 | V: TryVisit, 51 | { 52 | match ty { 53 | Type::Scalar(_) => { 54 | let scalar = value.as_scalar().unwrap(); 55 | match scalar { 56 | ScalarRef::usize(inner) => visitor.try_visit_usize(inner)?, 57 | ScalarRef::f32(inner) => visitor.try_visit_f32(inner)?, 58 | ScalarRef::bool(inner) => visitor.try_visit_bool(inner)?, 59 | ScalarRef::u8(inner) => visitor.try_visit_u8(inner)?, 60 | ScalarRef::u16(inner) => visitor.try_visit_u16(inner)?, 61 | ScalarRef::u32(inner) => visitor.try_visit_u32(inner)?, 62 | ScalarRef::u64(inner) => visitor.try_visit_u64(inner)?, 63 | ScalarRef::u128(inner) => visitor.try_visit_u128(inner)?, 64 | ScalarRef::i8(inner) => visitor.try_visit_i8(inner)?, 65 | ScalarRef::i16(inner) => visitor.try_visit_i16(inner)?, 66 | ScalarRef::i32(inner) => visitor.try_visit_i32(inner)?, 67 | ScalarRef::i64(inner) => visitor.try_visit_i64(inner)?, 68 | ScalarRef::i128(inner) => visitor.try_visit_i128(inner)?, 69 | ScalarRef::char(inner) => visitor.try_visit_char(inner)?, 70 | ScalarRef::f64(inner) => visitor.try_visit_f64(inner)?, 71 | ScalarRef::String(inner) => visitor.try_visit_string(inner)?, 72 | } 73 | } 74 | Type::Struct(struct_ty) => { 75 | let struct_ = value.as_struct().unwrap(); 76 | 77 | for field_ty in struct_ty.field_types() { 78 | let field = struct_.field(field_ty.name()).unwrap(); 79 | try_visit(visitor, field, field_ty.get_type())?; 80 | } 81 | } 82 | Type::TupleStruct(tuple_struct_ty) => { 83 | let tuple_struct = value.as_tuple_struct().unwrap(); 84 | 85 | for (idx, field_ty) in tuple_struct_ty.field_types().enumerate() { 86 | let field = tuple_struct.field_at(idx).unwrap(); 87 | try_visit(visitor, field, field_ty.get_type())?; 88 | } 89 | } 90 | Type::Tuple(tuple_ty) => { 91 | let tuple = value.as_tuple().unwrap(); 92 | 93 | for (idx, field_ty) in tuple_ty.field_types().enumerate() { 94 | let field = tuple.field_at(idx).unwrap(); 95 | try_visit(visitor, field, field_ty.get_type())?; 96 | } 97 | } 98 | Type::Enum(enum_ty) => { 99 | let enum_ = value.as_enum().unwrap(); 100 | let variant_ty = enum_ty.variant(enum_.variant_name()).unwrap(); 101 | 102 | for (idx, field_ty) in variant_ty.field_types().enumerate() { 103 | let field = match field_ty { 104 | VariantField::Named(named_field_ty) => { 105 | enum_.field(named_field_ty.name()).unwrap() 106 | } 107 | VariantField::Unnamed(_) => enum_.field_at(idx).unwrap(), 108 | }; 109 | try_visit(visitor, field, field_ty.get_type())?; 110 | } 111 | } 112 | Type::List(list_ty) => { 113 | let list = value.as_list().unwrap(); 114 | let element_ty = list_ty.element_type(); 115 | 116 | for element in list.iter() { 117 | try_visit(visitor, element, element_ty)?; 118 | } 119 | } 120 | Type::Array(array_ty) => { 121 | let array = value.as_array().unwrap(); 122 | let element_ty = array_ty.element_type(); 123 | 124 | for element in array.iter() { 125 | try_visit(visitor, element, element_ty)?; 126 | } 127 | } 128 | Type::Map(map_ty) => { 129 | let map = value.as_map().unwrap(); 130 | let key_ty = map_ty.key_type(); 131 | let value_ty = map_ty.value_type(); 132 | 133 | for (key, value) in map.iter() { 134 | try_visit(visitor, key, key_ty)?; 135 | try_visit(visitor, value, value_ty)?; 136 | } 137 | } 138 | Type::Set(set_ty) => { 139 | let set = value.as_set().unwrap(); 140 | let element_ty = set_ty.element_type(); 141 | 142 | for element in set.iter() { 143 | try_visit(visitor, element, element_ty)?; 144 | } 145 | } 146 | Type::Opaque(opaque_ty) => { 147 | visitor.try_visit_opaque(value, opaque_ty)?; 148 | } 149 | } 150 | 151 | Ok(()) 152 | } 153 | 154 | #[cfg(test)] 155 | mod tests { 156 | use super::*; 157 | use crate::DescribeType; 158 | use alloc::collections::BTreeMap; 159 | use core::convert::Infallible; 160 | 161 | #[derive(Debug, Clone, Default, Reflect)] 162 | #[reflect(crate_name(crate))] 163 | struct Foo { 164 | a: String, 165 | b: i32, 166 | c: Vec, 167 | } 168 | 169 | #[derive(Debug, Clone, Reflect)] 170 | #[reflect(crate_name(crate), opt_out(Default))] 171 | enum Bar { 172 | A(BTreeMap), 173 | } 174 | 175 | #[derive(Default, Debug)] 176 | struct CountsI32sAndStrings { 177 | string_count: usize, 178 | i32_count: usize, 179 | } 180 | 181 | impl TryVisit for CountsI32sAndStrings { 182 | type Error = Infallible; 183 | 184 | fn try_visit_string(&mut self, _value: &String) -> Result<(), Self::Error> { 185 | self.string_count += 1; 186 | Ok(()) 187 | } 188 | 189 | fn try_visit_i32(&mut self, _value: i32) -> Result<(), Self::Error> { 190 | self.i32_count += 1; 191 | Ok(()) 192 | } 193 | } 194 | 195 | #[test] 196 | fn works() { 197 | let foo = Foo { 198 | a: "a".to_owned(), 199 | b: 1337, 200 | c: Vec::from([Bar::A(BTreeMap::from_iter([(1, 1), (2, 2)]))]), 201 | }; 202 | 203 | let mut visitor = CountsI32sAndStrings::default(); 204 | try_visit( 205 | &mut visitor, 206 | &foo, 207 | ::type_descriptor().get_type(), 208 | ) 209 | .unwrap(); 210 | 211 | assert_eq!(visitor.string_count, 1); 212 | assert_eq!(visitor.i32_count, 5); 213 | } 214 | 215 | #[test] 216 | fn recursive() { 217 | #[derive(Debug, Clone, Default, Reflect)] 218 | #[reflect(crate_name(crate))] 219 | struct Recursive(i32, Vec); 220 | 221 | let value = Recursive( 222 | 1, 223 | Vec::from([Recursive(2, Vec::from([Recursive(3, Vec::new())]))]), 224 | ); 225 | 226 | let mut visitor = CountsI32sAndStrings::default(); 227 | try_visit( 228 | &mut visitor, 229 | &value, 230 | ::type_descriptor().get_type(), 231 | ) 232 | .unwrap(); 233 | 234 | assert_eq!(visitor.string_count, 0); 235 | assert_eq!(visitor.i32_count, 3); 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tuple.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use alloc::vec::Vec; 3 | use core::any::Any; 4 | use core::fmt; 5 | use core::fmt::Debug; 6 | use core::iter::FusedIterator; 7 | 8 | use crate::iter::ValueIterMut; 9 | use crate::type_info::graph::NodeId; 10 | use crate::type_info::graph::OpaqueNode; 11 | use crate::type_info::graph::TupleNode; 12 | use crate::type_info::graph::TypeGraph; 13 | use crate::type_info::graph::UnnamedFieldNode; 14 | use crate::DescribeType; 15 | use crate::FromReflect; 16 | use crate::Reflect; 17 | use crate::ReflectMut; 18 | use crate::ReflectOwned; 19 | use crate::ReflectRef; 20 | use crate::Value; 21 | 22 | /// A reflected tuple type. 23 | pub trait Tuple: Reflect { 24 | fn field_at(&self, index: usize) -> Option<&dyn Reflect>; 25 | 26 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>; 27 | 28 | fn fields(&self) -> Iter<'_>; 29 | 30 | fn fields_mut(&mut self) -> ValueIterMut<'_>; 31 | 32 | fn fields_len(&self) -> usize; 33 | } 34 | 35 | impl fmt::Debug for dyn Tuple { 36 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 37 | self.as_reflect().debug(f) 38 | } 39 | } 40 | 41 | #[derive(Default, Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] 42 | #[cfg_attr(feature = "speedy", derive(speedy::Readable, speedy::Writable))] 43 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 44 | pub struct TupleValue { 45 | fields: Vec, 46 | } 47 | 48 | impl TupleValue { 49 | pub fn new() -> Self { 50 | Self::default() 51 | } 52 | 53 | pub fn with_capacity(capacity: usize) -> Self { 54 | Self { 55 | fields: Vec::with_capacity(capacity), 56 | } 57 | } 58 | 59 | pub fn with_field(mut self, value: impl Into) -> Self { 60 | self.push_field(value); 61 | self 62 | } 63 | 64 | pub fn push_field(&mut self, value: impl Into) { 65 | self.fields.push(value.into()); 66 | } 67 | } 68 | 69 | impl Tuple for TupleValue { 70 | fn field_at(&self, index: usize) -> Option<&dyn Reflect> { 71 | Some(self.fields.get(index)?.as_reflect()) 72 | } 73 | 74 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 75 | Some(self.fields.get_mut(index)?.as_reflect_mut()) 76 | } 77 | 78 | fn fields(&self) -> Iter<'_> { 79 | Iter::new(self) 80 | } 81 | 82 | fn fields_mut(&mut self) -> ValueIterMut<'_> { 83 | let iter = self.fields.iter_mut().map(|value| value.as_reflect_mut()); 84 | Box::new(iter) 85 | } 86 | 87 | fn fields_len(&self) -> usize { 88 | self.fields.len() 89 | } 90 | } 91 | 92 | impl DescribeType for TupleValue { 93 | fn build(graph: &mut TypeGraph) -> NodeId { 94 | graph.get_or_build_node_with::(|graph| { 95 | OpaqueNode::new::(Default::default(), graph) 96 | }) 97 | } 98 | } 99 | 100 | impl Reflect for TupleValue { 101 | trivial_reflect_methods!(); 102 | 103 | fn patch(&mut self, value: &dyn Reflect) { 104 | if let Some(tuple) = value.reflect_ref().as_tuple() { 105 | for (index, value) in self.fields_mut().enumerate() { 106 | if let Some(new_value) = tuple.field_at(index) { 107 | value.patch(new_value); 108 | } 109 | } 110 | } 111 | } 112 | 113 | fn to_value(&self) -> Value { 114 | self.clone().into() 115 | } 116 | 117 | fn clone_reflect(&self) -> Box { 118 | Box::new(self.clone()) 119 | } 120 | 121 | fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 122 | if f.alternate() { 123 | write!(f, "{self:#?}") 124 | } else { 125 | write!(f, "{self:?}") 126 | } 127 | } 128 | 129 | fn reflect_owned(self: Box) -> ReflectOwned { 130 | ReflectOwned::Tuple(self) 131 | } 132 | 133 | fn reflect_ref(&self) -> ReflectRef<'_> { 134 | ReflectRef::Tuple(self) 135 | } 136 | 137 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 138 | ReflectMut::Tuple(self) 139 | } 140 | } 141 | 142 | impl FromReflect for TupleValue { 143 | fn from_reflect(reflect: &dyn Reflect) -> Option { 144 | let tuple = reflect.reflect_ref().as_tuple()?; 145 | let this = tuple 146 | .fields() 147 | .fold(TupleValue::default(), |builder, value| { 148 | builder.with_field(value.to_value()) 149 | }); 150 | Some(this) 151 | } 152 | } 153 | 154 | macro_rules! impl_tuple { 155 | ($($ident:ident),* $(,)?) => { 156 | #[allow(non_snake_case, unused_mut, unused_variables)] 157 | impl<$($ident,)*> DescribeType for ($($ident,)*) 158 | where 159 | $($ident: Reflect + DescribeType + Clone,)* 160 | { 161 | fn build(graph: &mut TypeGraph) -> NodeId { 162 | graph.get_or_build_node_with::(|graph| { 163 | let fields = &[ 164 | $( 165 | UnnamedFieldNode::new::<$ident>(Default::default(), Default::default(), graph), 166 | )* 167 | ]; 168 | TupleNode::new::(fields, Default::default(), Default::default()) 169 | }) 170 | } 171 | } 172 | 173 | #[allow(non_snake_case, unused_mut, unused_variables)] 174 | impl<$($ident,)*> Reflect for ($($ident,)*) 175 | where 176 | $($ident: Reflect + DescribeType + Clone,)* 177 | { 178 | trivial_reflect_methods!(); 179 | 180 | #[allow(unused_assignments)] 181 | fn patch(&mut self, value: &dyn Reflect) { 182 | if let Some(tuple) = value.reflect_ref().as_tuple() { 183 | let ($($ident,)*) = self; 184 | let mut i = 0; 185 | $( 186 | if let Some(field) = tuple.field_at(i) { 187 | $ident.patch(field); 188 | } 189 | i += 1; 190 | )* 191 | } 192 | } 193 | 194 | fn to_value(&self) -> Value { 195 | let ($($ident,)*) = self; 196 | let mut value = TupleValue::new(); 197 | $( 198 | value = value.with_field($ident.to_value()); 199 | )* 200 | value.into() 201 | } 202 | 203 | fn clone_reflect(&self) -> Box { 204 | Box::new(self.clone()) 205 | } 206 | 207 | fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 208 | write!(f, "{}", core::any::type_name::()) 209 | } 210 | 211 | fn reflect_owned(self: Box) -> ReflectOwned { 212 | ReflectOwned::Tuple(self) 213 | } 214 | 215 | fn reflect_ref(&self) -> ReflectRef<'_> { 216 | ReflectRef::Tuple(self) 217 | } 218 | 219 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 220 | ReflectMut::Tuple(self) 221 | } 222 | } 223 | 224 | #[allow(non_snake_case, unused_mut, unused_assignments, unused_variables)] 225 | impl<$($ident,)*> Tuple for ($($ident,)*) 226 | where 227 | $($ident: Reflect + DescribeType + Clone,)* 228 | { 229 | fn field_at(&self, index: usize) -> Option<&dyn Reflect> { 230 | let mut i = 0; 231 | let ($($ident,)*) = self; 232 | $( 233 | if index == i { 234 | return Some($ident); 235 | } 236 | i += 1; 237 | )* 238 | None 239 | } 240 | 241 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 242 | let mut i = 0; 243 | let ($($ident,)*) = self; 244 | $( 245 | if index == i { 246 | return Some($ident); 247 | } 248 | i += 1; 249 | )* 250 | None 251 | } 252 | 253 | fn fields(&self) -> Iter<'_> { 254 | Iter::new(self) 255 | } 256 | 257 | fn fields_mut(&mut self) -> ValueIterMut<'_> { 258 | let ($($ident,)*) = self; 259 | Box::new([$($ident.as_reflect_mut(),)*].into_iter()) 260 | } 261 | 262 | fn fields_len(&self) -> usize { 263 | let mut n = 0; 264 | $( 265 | let _ = stringify!($ident); 266 | n += 1; 267 | )* 268 | n 269 | } 270 | } 271 | 272 | #[allow(non_snake_case, unused_mut, unused_assignments, unused_variables)] 273 | impl<$($ident,)*> FromReflect for ($($ident,)*) 274 | where 275 | $($ident: FromReflect + DescribeType + Clone,)* 276 | { 277 | fn from_reflect(reflect: &dyn Reflect) -> Option { 278 | let tuple = reflect.as_tuple()?; 279 | let mut fields = tuple.fields(); 280 | Some(( 281 | $($ident::from_reflect(fields.next()?)?,)* 282 | )) 283 | } 284 | } 285 | }; 286 | } 287 | 288 | impl_tuple!(); 289 | impl_tuple!(T1); 290 | impl_tuple!(T1, T2); 291 | impl_tuple!(T1, T2, T3); 292 | impl_tuple!(T1, T2, T3, T4); 293 | impl_tuple!(T1, T2, T3, T4, T5); 294 | impl_tuple!(T1, T2, T3, T4, T5, T6); 295 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7); 296 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8); 297 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9); 298 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); 299 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); 300 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); 301 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13); 302 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14); 303 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15); 304 | impl_tuple!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16); 305 | 306 | impl FromIterator for TupleValue 307 | where 308 | V: Reflect, 309 | { 310 | fn from_iter(iter: T) -> Self 311 | where 312 | T: IntoIterator, 313 | { 314 | let mut out = Self::default(); 315 | for value in iter { 316 | out.push_field(value.to_value()); 317 | } 318 | out 319 | } 320 | } 321 | 322 | #[derive(Debug)] 323 | pub struct Iter<'a> { 324 | tuple: &'a dyn Tuple, 325 | index: usize, 326 | } 327 | 328 | impl<'a> Iter<'a> { 329 | pub fn new(tuple: &'a dyn Tuple) -> Self { 330 | Self { tuple, index: 0 } 331 | } 332 | } 333 | 334 | impl<'a> Iterator for Iter<'a> { 335 | type Item = &'a dyn Reflect; 336 | 337 | fn next(&mut self) -> Option { 338 | let value = self.tuple.field_at(self.index)?; 339 | self.index += 1; 340 | Some(value) 341 | } 342 | } 343 | 344 | impl ExactSizeIterator for Iter<'_> { 345 | fn len(&self) -> usize { 346 | self.tuple.fields_len() 347 | } 348 | } 349 | 350 | impl FusedIterator for Iter<'_> {} 351 | -------------------------------------------------------------------------------- /crates/mirror-mirror/src/tuple_struct.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use core::any::Any; 3 | use core::fmt; 4 | use core::iter::FusedIterator; 5 | 6 | use crate::iter::ValueIterMut; 7 | use crate::tuple::TupleValue; 8 | use crate::type_info::graph::NodeId; 9 | use crate::type_info::graph::OpaqueNode; 10 | use crate::type_info::graph::TypeGraph; 11 | use crate::DescribeType; 12 | use crate::FromReflect; 13 | use crate::Reflect; 14 | use crate::ReflectMut; 15 | use crate::ReflectOwned; 16 | use crate::ReflectRef; 17 | use crate::Tuple; 18 | use crate::Value; 19 | 20 | /// A reflected tuple struct type. 21 | /// 22 | /// Will be implemented by `#[derive(Reflect)]` on tuple structs. 23 | pub trait TupleStruct: Reflect { 24 | fn field_at(&self, index: usize) -> Option<&dyn Reflect>; 25 | 26 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>; 27 | 28 | fn fields(&self) -> Iter<'_>; 29 | 30 | fn fields_mut(&mut self) -> ValueIterMut<'_>; 31 | 32 | fn fields_len(&self) -> usize; 33 | } 34 | 35 | impl fmt::Debug for dyn TupleStruct { 36 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 37 | self.as_reflect().debug(f) 38 | } 39 | } 40 | 41 | #[derive(Default, Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] 42 | #[cfg_attr(feature = "speedy", derive(speedy::Readable, speedy::Writable))] 43 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 44 | pub struct TupleStructValue { 45 | tuple: TupleValue, 46 | } 47 | 48 | impl TupleStructValue { 49 | pub fn new() -> Self { 50 | Self::default() 51 | } 52 | 53 | pub fn with_capacity(capacity: usize) -> Self { 54 | Self { 55 | tuple: TupleValue::with_capacity(capacity), 56 | } 57 | } 58 | 59 | pub fn with_field(self, value: impl Into) -> Self { 60 | Self { 61 | tuple: self.tuple.with_field(value), 62 | } 63 | } 64 | 65 | pub fn push_field(&mut self, value: impl Into) { 66 | self.tuple.push_field(value); 67 | } 68 | } 69 | 70 | impl DescribeType for TupleStructValue { 71 | fn build(graph: &mut TypeGraph) -> NodeId { 72 | graph.get_or_build_node_with::(|graph| { 73 | OpaqueNode::new::(Default::default(), graph) 74 | }) 75 | } 76 | } 77 | 78 | impl Reflect for TupleStructValue { 79 | trivial_reflect_methods!(); 80 | 81 | fn patch(&mut self, value: &dyn Reflect) { 82 | if let Some(tuple) = value.reflect_ref().as_tuple_struct() { 83 | for (index, value) in self.fields_mut().enumerate() { 84 | if let Some(new_value) = tuple.field_at(index) { 85 | value.patch(new_value); 86 | } 87 | } 88 | } 89 | } 90 | 91 | fn to_value(&self) -> Value { 92 | self.clone().into() 93 | } 94 | 95 | fn clone_reflect(&self) -> Box { 96 | Box::new(self.clone()) 97 | } 98 | 99 | fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 100 | if f.alternate() { 101 | write!(f, "{self:#?}") 102 | } else { 103 | write!(f, "{self:?}") 104 | } 105 | } 106 | 107 | fn reflect_owned(self: Box) -> ReflectOwned { 108 | ReflectOwned::TupleStruct(self) 109 | } 110 | 111 | fn reflect_ref(&self) -> ReflectRef<'_> { 112 | ReflectRef::TupleStruct(self) 113 | } 114 | 115 | fn reflect_mut(&mut self) -> ReflectMut<'_> { 116 | ReflectMut::TupleStruct(self) 117 | } 118 | } 119 | 120 | impl TupleStruct for TupleStructValue { 121 | fn field_at(&self, index: usize) -> Option<&dyn Reflect> { 122 | self.tuple.field_at(index) 123 | } 124 | 125 | fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { 126 | self.tuple.field_at_mut(index) 127 | } 128 | 129 | fn fields(&self) -> Iter<'_> { 130 | Iter::new(self) 131 | } 132 | 133 | fn fields_mut(&mut self) -> ValueIterMut<'_> { 134 | self.tuple.fields_mut() 135 | } 136 | 137 | fn fields_len(&self) -> usize { 138 | self.tuple.fields_len() 139 | } 140 | } 141 | 142 | impl FromReflect for TupleStructValue { 143 | fn from_reflect(reflect: &dyn Reflect) -> Option { 144 | let tuple_struct = reflect.reflect_ref().as_tuple_struct()?; 145 | let this = tuple_struct 146 | .fields() 147 | .fold(TupleStructValue::default(), |builder, value| { 148 | builder.with_field(value.to_value()) 149 | }); 150 | Some(this) 151 | } 152 | } 153 | 154 | impl FromIterator for TupleStructValue 155 | where 156 | V: Reflect, 157 | { 158 | fn from_iter(iter: T) -> Self 159 | where 160 | T: IntoIterator, 161 | { 162 | let mut out = Self::default(); 163 | for value in iter { 164 | out.push_field(value.to_value()); 165 | } 166 | out 167 | } 168 | } 169 | 170 | #[derive(Debug)] 171 | pub struct Iter<'a> { 172 | tuple_struct: &'a dyn TupleStruct, 173 | index: usize, 174 | } 175 | 176 | impl<'a> Iter<'a> { 177 | pub fn new(tuple_struct: &'a dyn TupleStruct) -> Self { 178 | Self { 179 | tuple_struct, 180 | index: 0, 181 | } 182 | } 183 | } 184 | 185 | impl<'a> Iterator for Iter<'a> { 186 | type Item = &'a dyn Reflect; 187 | 188 | fn next(&mut self) -> Option { 189 | let value = self.tuple_struct.field_at(self.index)?; 190 | self.index += 1; 191 | Some(value) 192 | } 193 | } 194 | 195 | impl ExactSizeIterator for Iter<'_> { 196 | fn len(&self) -> usize { 197 | self.tuple_struct.fields_len() 198 | } 199 | } 200 | 201 | impl FusedIterator for Iter<'_> {} 202 | -------------------------------------------------------------------------------- /deny.toml: -------------------------------------------------------------------------------- 1 | [advisories] 2 | 3 | [bans] 4 | deny = [ 5 | ] 6 | 7 | skip = [ 8 | # two versions of glam for now since macaw is 9 | # unreleased for a little while, should fix soon 10 | { name = "glam" } 11 | ] 12 | 13 | [sources] 14 | allow-registry = [ 15 | "https://github.com/rust-lang/crates.io-index", 16 | ] 17 | 18 | [licenses] 19 | # We want really high confidence when inferring licenses from text 20 | confidence-threshold = 0.92 21 | allow = [ 22 | "Apache-2.0", 23 | "MIT", 24 | "Unicode-DFS-2016", 25 | "Zlib", 26 | ] 27 | exceptions = [ 28 | ] 29 | --------------------------------------------------------------------------------