diff options
Diffstat (limited to 'third_party/rust/presser')
-rw-r--r-- | third_party/rust/presser/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/presser/CHANGELOG.md | 40 | ||||
-rw-r--r-- | third_party/rust/presser/CODE_OF_CONDUCT.md | 76 | ||||
-rw-r--r-- | third_party/rust/presser/CONTRIBUTING.md | 75 | ||||
-rw-r--r-- | third_party/rust/presser/Cargo.toml | 58 | ||||
-rw-r--r-- | third_party/rust/presser/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | third_party/rust/presser/LICENSE-MIT | 25 | ||||
-rw-r--r-- | third_party/rust/presser/README.md | 130 | ||||
-rw-r--r-- | third_party/rust/presser/release.toml | 11 | ||||
-rw-r--r-- | third_party/rust/presser/src/lib.rs | 786 |
10 files changed, 1403 insertions, 0 deletions
diff --git a/third_party/rust/presser/.cargo-checksum.json b/third_party/rust/presser/.cargo-checksum.json new file mode 100644 index 0000000000..c1f5e1ae48 --- /dev/null +++ b/third_party/rust/presser/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"d30e238ea99cf0b7eef9bde74738d59ef9247febe226931c681e54e3e78555ea","CODE_OF_CONDUCT.md":"bdd62923c8e1c5b1d86ff459b7d71a9f1d6279d262c524bae767d7bb4fa65f50","CONTRIBUTING.md":"8580dcd2e6ef627d8666c2e624e00581e3cdf42f10d7d6ab48c65f42ed755ce7","Cargo.toml":"ef362b2fb1b874d6450911fa11fb6f7fa28c033d292cb636e2f9e8d6773ca85f","LICENSE-APACHE":"8173d5c29b4f956d532781d2b86e4e30f83e6b7878dce18c919451d6ba707c90","LICENSE-MIT":"090a294a492ab2f41388252312a65cf2f0e423330b721a68c6665ac64766753b","README.md":"c517d356445491dfc27bd31101753f7c715bfc98b34f2c67f3fde1639f4513b2","release.toml":"35ef9c6d98a56fa088266b04dfc2b4f054e60ce86fc23201227b20d06117b84e","src/lib.rs":"f7942cfcefdd7670785b46eef8265f6d55bec016fdff3762ab9bc66f51553f86"},"package":"e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"}
\ No newline at end of file diff --git a/third_party/rust/presser/CHANGELOG.md b/third_party/rust/presser/CHANGELOG.md new file mode 100644 index 0000000000..2bfebdbde7 --- /dev/null +++ b/third_party/rust/presser/CHANGELOG.md @@ -0,0 +1,40 @@ +<!-- markdownlint-disable blanks-around-headings blanks-around-lists no-duplicate-heading --> + +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +<!-- next-header --> +## [Unreleased] - ReleaseDate +## [0.3.1] - 2022-10-16 + +- Small documentation fixes +- Add example to docs + +## 0.3.0 - 2022-10-16 + +- Open source repository +- Support `#[no_std]` via optional `std` feature +- Improve/revamp some documentation + +## 0.2.1 + +- Re-word crate-level safety documentation + +## 0.2.0 + +- Require Rust 1.64 +- Added `copy_into_maybe_uninit_slice` +- Added `clone_into_maybe_uninit_slice` +- Remove optional `gpu-allocator` feature and support + +## 0.1.1 + +- Added `maybe_uninit_slice_from_vec` helper function + +<!-- next-url --> +[Unreleased]: https://github.com/EmbarkStudios/presser/compare/0.3.1...HEAD +[0.3.1]: https://github.com/EmbarkStudios/presser/compare/0.3.0...0.3.1 diff --git a/third_party/rust/presser/CODE_OF_CONDUCT.md b/third_party/rust/presser/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..7d03b67555 --- /dev/null +++ b/third_party/rust/presser/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at opensource@embark-studios.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/third_party/rust/presser/CONTRIBUTING.md b/third_party/rust/presser/CONTRIBUTING.md new file mode 100644 index 0000000000..65c2b968c6 --- /dev/null +++ b/third_party/rust/presser/CONTRIBUTING.md @@ -0,0 +1,75 @@ +# Embark Contributor Guidelines + +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. + +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. + +If you have ideas for collaboration, email us at opensource@embark-studios.com. + +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). + +## Issues + +### Feature Requests + +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. + +Feature requests will be tagged as `enhancement` and their status will be updated in the comments of the issue. + +### Bugs + +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. + +Reproducible bugs will be tagged as `bug` and their status will be updated in the comments of the issue. + +### Wontfix + +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. + +## Contribution Workflow + +### Open Issues + +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"). + +You can comment on the issue to let others know you're interested in working on it or to ask questions. + +### Making Changes + +1. Fork the repository. + +2. Create a new feature branch. + +3. Make your changes. Ensure that there are no build errors by running the project with your changes locally. + +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). + +5. A maintainer will review your pull request and may ask you to make changes. + +## Code Guidelines + +### Rust + +You can read about our standards and recommendations for working with Rust [here](https://github.com/EmbarkStudios/rust-ecosystem/blob/main/guidelines.md). + +### Python + +We recommend following [PEP8 conventions](https://www.python.org/dev/peps/pep-0008/) when working with Python modules. + +### JavaScript & TypeScript + +We use [Prettier](https://prettier.io/) with the default settings to auto-format our JavaScript and TypeScript code. + +## Licensing + +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. + +## Contributor Terms + +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. + +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). + +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.) + +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. diff --git a/third_party/rust/presser/Cargo.toml b/third_party/rust/presser/Cargo.toml new file mode 100644 index 0000000000..49d96e476f --- /dev/null +++ b/third_party/rust/presser/Cargo.toml @@ -0,0 +1,58 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.64" +name = "presser" +version = "0.3.1" +authors = [ + "Embark <opensource@embark-studios.com>", + "Gray Olson <gray@grayolson.com", +] +publish = true +description = "A crate to help you copy things into raw buffers without invoking spooky action at a distance (undefined behavior)." +homepage = "https://github.com/EmbarkStudios/presser" +documentation = "https://docs.rs/presser" +readme = "README.md" +keywords = [ + "copy", + "graphics", + "raw", + "buffer", + "memory", +] +categories = [ + "games", + "memory-management", + "graphics", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/EmbarkStudios/presser" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = [ + "--cfg", + "docs_build", +] + +[lib] +test = true +doctest = true + +[dependencies] + +[dev-dependencies] + +[features] +default = ["std"] +std = [] diff --git a/third_party/rust/presser/LICENSE-APACHE b/third_party/rust/presser/LICENSE-APACHE new file mode 100644 index 0000000000..11069edd79 --- /dev/null +++ b/third_party/rust/presser/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third_party/rust/presser/LICENSE-MIT b/third_party/rust/presser/LICENSE-MIT new file mode 100644 index 0000000000..0bdad8fb34 --- /dev/null +++ b/third_party/rust/presser/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2019 Embark Studios + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/presser/README.md b/third_party/rust/presser/README.md new file mode 100644 index 0000000000..e8b25f583d --- /dev/null +++ b/third_party/rust/presser/README.md @@ -0,0 +1,130 @@ +<!-- Allow this file to not have a first line heading --> +<!-- markdownlint-disable-file MD041 no-emphasis-as-heading --> + +<!-- inline html --> +<!-- markdownlint-disable-file MD033 --> + +<div align="center"> + +# `π presser` + +**Utilities to help make copying data around into raw, possibly-uninitialized buffers easier and safer.** + +[![Embark](https://img.shields.io/badge/embark-open%20source-blueviolet.svg)](https://embark.dev) +[![Embark](https://img.shields.io/badge/discord-ark-%237289da.svg?logo=discord)](https://discord.gg/dAuKfZS) +[![Crates.io](https://img.shields.io/crates/v/presser.svg)](https://crates.io/crates/presser) +[![Published Docs](https://docs.rs/presser/badge.svg)](https://docs.rs/presser) +[![Git Docs](https://img.shields.io/badge/git%20main%20docs-published-blue?style=plastic)](https://embarkstudios.github.io/presser/presser/index.html) +[![dependency status](https://deps.rs/repo/github/EmbarkStudios/presser/status.svg)](https://deps.rs/repo/github/EmbarkStudios/presser) +</div> + +`presser` can help you when copying data into raw buffers. One primary use-case is copying data into +graphics-api-allocated buffers which will then be accessed by the GPU. Common methods for doing this +right now in Rust can often invoke UB in subtle and hard-to-see ways. For example, viewing an allocated +but uninitialized buffer as an `&mut [u8]` **is instantly undefined behavior**\*, and `transmute`ing even a +`T: Copy` type which has *any padding bytes in its layout* as a `&[u8]` to be the source of a copy is +**also instantly undefined behavior**, in both cases because it is *invalid* to create a reference to an invalid +value (and uninitialized memory is an invalid `u8`), *even if* your code never actually accesses that memory. +This immediately makes what seems like the most straightforward way to copy data into buffers unsound π¬ + +\* *If you're currently thinking to yourself "bah! what's the issue? surely an uninit u8 is just any random bit pattern +and that's fine we don't care," [check out this blog post](https://www.ralfj.de/blog/2019/07/14/uninit.html) by +@RalfJung, one of the people leading the effort to better define Rust's memory and execution model. As is explored +in that blog post, an*uninit*piece of memory is not simply*an arbitrary bit pattern*, it is a wholly separate +state about a piece of memory, outside of its value, which lets the compiler perform optimizations that reorder, +delete, and otherwise change the actual execution flow of your program in ways that cannot be described simply +by "the value could have*some*possible bit pattern". LLVM and Clang are changing themselves to require special +`noundef` attribute to perform many important optimizations that are otherwise unsound. For a concrete example +of the sorts of problems this can cause, [see this issue @scottmcm hit](https://github.com/rust-lang/rust/pull/98919#issuecomment-1186106387).* + +## A bad example + +```rust +#[derive(Clone, Copy)] +#[repr(C)] +struct MyDataStruct { + a: u8, + b: u32, +} + +let my_data = MyDataStruct { a: 0, b: 42 }; + +// π¨ MyDataStruct contains 3 padding bytes after `a`, which are +// uninit, therefore getting a slice that includes them is UB! +let my_data_bytes: &[u8] = transmute(&my_data); + +// allocate an uninit buffer of some size +let my_buffer: MyBufferType = some_api.alloc_buffer_size(2048); + +// π¨ this is UB for the same reason, these bytes are uninit! +let buffer_as_bytes: &mut [u8] = + slice::from_raw_parts(my_buffer.ptr(), my_buffer.size()); + +// π¨ this is UB because not only are both slices invalid, +// this is not ensuring proper alignment! +buffer_as_bytes.copy_from_slice(my_data_bytes); +``` + +`presser` helps with this by allowing you to view raw allocated memory of some size as a "`Slab`" of memory and then +provides *safe, valid* ways to copy data into that memory: + +### A good example + +```rust +#[derive(Clone, Copy)] +#[repr(C)] +struct MyDataStruct { + a: u8, + b: u32, +} + +let my_data = MyDataStruct { a: 0, b: 42 }; + +// allocate an uninit buffer of some size +let my_buffer: MyBufferType = some_api.alloc_buffer_size(2048); + +// use `RawAllocation` helper to allow access to a presser `Slab`. +// alternatively, you could implement the `Slab` on your buffer type directly if that +// type is owned by your code! +let raw_allocation = presser::RawAllocation::from_raw_parts(my_buffer.ptr(), my_buffer.size()); + +// here we assert that we have exclusive access to the data in the buffer, and get the actual +// `Slab` to use to copy into. +let slab = unsafe { raw_allocation.borrow_as_slab(); } + +// now we may safely copy `my_data` into `my_buffer`, starting at a minimum offset of 0 into the buffer +let copy_record = presser::copy_to_offset(&my_data, &mut slab, 0)?; + +// note that due to alignment requirements of `my_data`, the *actual* start of the bytes of +// `my_data` may be placed at a different offset than requested. so, we check the returned +// `CopyRecord` to check the actual start offset of the copied data. +let actual_start_offset = copy_record.copy_start_offset; +``` + +Note that actually accessing the copied data is a completely separate issue which `presser` does not +(as of now) concern itself with. BE CAREFUL! + +See more in [the git `main` docs](https://embarkstudios.github.io/presser/presser/index.html) +or [the released version docs](https://docs.rs/presser). + +## Contribution + +[![Contributor Covenant](https://img.shields.io/badge/contributor%20covenant-v1.4-ff69b4.svg)](CODE_OF_CONDUCT.md) + +We welcome community contributions to this project. + +Please read our [Contributor Guide](CONTRIBUTING.md) for more information on how to get started. +Please also read our [Contributor Terms](CONTRIBUTING.md#contributor-terms) before you make any contributions. + +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: + +### License + +This contribution is dual licensed under EITHER OF + +* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) +* MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) + +at your option. + +For clarity, "your" refers to Embark or any other licensee/user of the contribution. diff --git a/third_party/rust/presser/release.toml b/third_party/rust/presser/release.toml new file mode 100644 index 0000000000..904e2fe68e --- /dev/null +++ b/third_party/rust/presser/release.toml @@ -0,0 +1,11 @@ +pre-release-commit-message = "Release {{version}}" +dev-version = false +tag-message = "Release {{version}}" +tag-name = "{{version}}" +pre-release-replacements = [ + { file = "CHANGELOG.md", search = "Unreleased", replace = "{{version}}" }, + { file = "CHANGELOG.md", search = "\\.\\.\\.HEAD", replace = "...{{tag_name}}" }, + { file = "CHANGELOG.md", search = "ReleaseDate", replace = "{{date}}" }, + { file = "CHANGELOG.md", search = "<!-- next-header -->", replace = "<!-- next-header -->\n## [Unreleased] - ReleaseDate" }, + { file = "CHANGELOG.md", search = "<!-- next-url -->", replace = "<!-- next-url -->\n[Unreleased]: https://github.com/EmbarkStudios/presser/compare/{{tag_name}}...HEAD" }, +] diff --git a/third_party/rust/presser/src/lib.rs b/third_party/rust/presser/src/lib.rs new file mode 100644 index 0000000000..4d15558247 --- /dev/null +++ b/third_party/rust/presser/src/lib.rs @@ -0,0 +1,786 @@ +//! # `π presser` +//! +//! **Utilities to help make copying data around into raw, possibly-uninitialized buffers +//! easier and safer.** +//! +//! ## Motivation +//! +//! `presser` can help you when copying data into raw buffers. One primary use-case is copying data into +//! graphics-api-allocated buffers which will then be accessed by the GPU. Common methods for doing this +//! right now in Rust can often invoke UB in subtle and hard-to-see ways. For example, viewing an allocated +//! but uninitialized buffer as an `&mut [u8]` **is instantly undefined behavior**\*, and `transmute`ing even a +//! `T: Copy` type which has *any padding bytes in its layout* as a `&[u8]` to be the source of a copy is +//! **also instantly undefined behavior**, in both cases because it is *invalid* to create a reference to an invalid +//! value (and uninitialized memory is an invalid `u8`), *even if* your code never actually accesses that memory. +//! This immediately makes what seems like the most straightforward way to copy data into buffers unsound π¬. +//! +//! `presser` helps with this by allowing you to view raw allocated memory of some size as a "[`Slab`]" of memory and then +//! provides *safe, valid* ways to copy data into that memory. For example, you could implement [`Slab`] for your +//! GPU-allocated buffer type, or use the built-in [`RawAllocation`] workflow described below, then use +//! [`copy_to_offset_with_align`] to copy any `T: Copy` data into that buffer safely for use on the GPU. +//! Of course, if your `T` doesn't have the correct layout the GPU expects, accessing it on the GPU side may still be +//! unsound or at least give an error. +//! +//! \* *If you're currently thinking to yourself "bah! what's the issue? surely an uninit u8 is just any random bit pattern +//! and that's fine we don't care," [check out this blog post](https://www.ralfj.de/blog/2019/07/14/uninit.html) by +//! @RalfJung, one of the people leading the effort to better define Rust's memory and execution model. As is explored +//! in that blog post, an *uninit* piece of memory is not simply *an arbitrary bit pattern*, it is a wholly separate +//! state about a piece of memory, outside of its value, which lets the compiler perform optimizations that reorder, +//! delete, and otherwise change the actual execution flow of your program in ways that cannot be described simply +//! by "the value could have *some* possible bit pattern". LLVM and Clang are changing themselves to require special +//! `noundef` attribute to perform many important optimizations that are otherwise unsound. For a concrete example +//! of the sorts of problems this can cause, +//! [see this issue @scottmcm hit](https://github.com/rust-lang/rust/pull/98919#issuecomment-1186106387).* +//! +//! ## Introduction +//! +//! The main idea is to implement [`Slab`] on raw-buffer-esque-types (see [the `Slab` safety docs][Slab#Safety]), +//! which then enables the use of the other functions within the crate. +//! +//! Depending on your use case, you may be able to implement [`Slab`] directly for your buffer type, or it may +//! be more convenient or necessary to create a wrapping struct that borrows your raw buffer type and in turn +//! implements [`Slab`]. For an example of this, see [`RawAllocation`] and [`BorrowedRawAllocation`], which you +//! may also use directly. The idea is to create a [`RawAllocation`] to your buffer, which you then borrow into +//! a [`BorrowedRawAllocation`] (which implements [`Slab`]) by calling the unsafe function +//! [`RawAllocation::borrow_as_slab`] +//! +//! Once you have a slab, you can use the copy helper functions provided at the crate root, for example, +//! [`copy_to_offset`] and [`copy_to_offset_with_align`]. +//! +//! ### Example +//! +//! ```rust,ignore +//! #[derive(Clone, Copy)] +//! #[repr(C)] +//! struct MyDataStruct { +//! a: u8, +//! b: u32, +//! } +//! +//! let my_data = MyDataStruct { a: 0, b: 42 }; +//! +//! // allocate an uninit buffer of some size +//! let my_buffer: MyBufferType = some_api.alloc_buffer_size(2048); +//! +//! // use `RawAllocation` helper to allow access to a presser `Slab`. +//! // alternatively, you could implement the `Slab` on `MyByfferType` directly if that +//! // type is owned by your code! +//! let raw_allocation = presser::RawAllocation::from_raw_parts(my_buffer.ptr(), my_buffer.size()); +//! +//! // here we assert that we have exclusive access to the data in the buffer, and get the actual +//! // `Slab` to use to copy into. +//! let slab = unsafe { raw_allocation.borrow_as_slab(); } +//! +//! // now we may safely copy `my_data` into `my_buffer`, starting at a minimum offset of 0 into the buffer +//! let copy_record = presser::copy_to_offset(&my_data, &mut slab, 0)?; +//! +//! // note that due to alignment requirements of `my_data`, the *actual* start of the bytes of +//! // `my_data` may be placed at a different offset than requested. so, we check the returned +//! // `CopyRecord` to check the actual start offset of the copied data. +//! let actual_start_offset = copy_record.copy_start_offset; +//! ``` +//! +//! ### `#[no_std]` +//! +//! This crate supports `no_std` environments by building without the '`std`' feature. This will limit some +//! of the fuctions the crate can perform. +//! +//! # Safety +//! +//! An important note is that obeying the safety rules specified in the [`Slab`] safety documentation +//! *only* guarantees safety for the *direct results* of the copy operations performed by the +//! helper functions exported at the crate root (and the safe functions on [`Slab`]). **However**, +//! it is ***not*** guaranteed that operations which would previously have been safe to perform +//! using same backing memory that the [`Slab`] you copied into used are still safe. +//! +//! For example, say you have a fully-initialized +//! chunk of bytes (like a `Vec<u8>`), which you view as a [`Slab`], and then (safely) perform a copy +//! operation into using [`copy_to_offset`]. If the `T` you copied into it has any padding bytes in +//! its memory layout, then the memory locations where those padding bytes now exist in the underlying `Vec`'s +//! memory must now be treated as uninitialized. As such, taking any view into that byte vector which +//! relies on those newly-uninit bytes being initialized to be valid (for example, taking a `&[u8]` slice of the `Vec` +//! which includes those bytes, ***even if your code never actually reads from that slice***) +//! is now instant **undefined behavior**. +#![cfg_attr(not(feature = "std"), no_std)] +#![deny(unsafe_op_in_unsafe_fn)] +#![deny(missing_docs)] +// only enables the `doc_auto_cfg` feature when +// the `docs_build` configuration attribute is defined +// this cfg is defined when building on docs.rs (defined thru the project +// Cargo.toml) and when building the docs for publishing on github pages (thru the +// .github/workflows/rustdoc-pages.yml workflow) +#![cfg_attr(docs_build, feature(doc_auto_cfg))] + +use core::alloc::Layout; +use core::alloc::LayoutError; +use core::marker::PhantomData; +use core::mem::MaybeUninit; +use core::ptr::NonNull; + +/// Represents a contiguous piece of a single allocation with some layout that is used as a +/// data copying destination. May be wholly or partially uninitialized. +/// +/// This trait is *basically* equivalent to implementing `Deref`/`DerefMut` with +/// `Target = [MaybeUninit<u8>]` in terms of safety requirements. It is a separate +/// trait for the extra flexibility having a trait we own provides: namely, the ability +/// to implement it on foreign types. +/// +/// # Safety +/// +/// Implementors of this trait must ensure these guarantees: +/// +/// - The memory range represented by `base_ptr` and `size` **may** be wholly or partially uninitialized +/// - `base_ptr` **must** point to a valid, single allocation of at least `size` bytes. +/// - `size` **must not** be greater than `isize::MAX` +/// +/// Assume the lifetime of a shared borrow of self is named `'a`: +/// +/// - `base_ptr` **must** be [valid][`core::ptr#safety`] for `'a` +/// - `base_ptr` **must *not*** be mutably aliased for `'a` +/// - It is necessary but not sufficient for this requirement that +/// **no outside *mutable* references** may exist to its data, even if they are unused by user code. +/// +/// Assume the lifetime of a mutable borrow of self is named `'a`: +/// +/// - `base_ptr_mut` **must** be [valid][`core::ptr#safety`] for `'a` +/// - `base_ptr_mut` **must *not*** be aliased at all for `'a` +/// - It is necessary but not sufficient for this requirement that +/// **no outside references** may exist to its data, even if they are unused by user code. +/// +/// Also see the [crate-level safety documentation][`crate#safety`]. +pub unsafe trait Slab { + /// Get a pointer to the beginning of the allocation represented by `self`. + fn base_ptr(&self) -> *const u8; + + /// Get a pointer to the beginning of the allocation represented by `self`. + fn base_ptr_mut(&mut self) -> *mut u8; + + /// Get the size of the allocation represented by `self`. + fn size(&self) -> usize; + + /// Interpret a portion of `self` as a slice of [`MaybeUninit<u8>`]. This is likely not + /// incredibly useful, you probably want to use [`Slab::as_maybe_uninit_bytes_mut`] + fn as_maybe_uninit_bytes(&self) -> &[MaybeUninit<u8>] { + // SAFETY: Safe so long as top level safety guarantees are held, since + // `MaybeUninit` has same layout as bare type. + unsafe { core::slice::from_raw_parts(self.base_ptr().cast(), self.size()) } + } + + /// Interpret a portion of `self` as a mutable slice of [`MaybeUninit<u8>`]. + fn as_maybe_uninit_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] { + // SAFETY: Safe so long as top level safety guarantees are held, since + // `MaybeUninit` has same layout as bare type. + unsafe { core::slice::from_raw_parts_mut(self.base_ptr_mut().cast(), self.size()) } + } + + /// Interpret `self` as a byte slice. This assumes that **all bytes** + /// in `self` are initialized. + /// + /// # Safety + /// + /// Assuming that the safety guarantees for creating `self` were followed, + /// the only extra requirement for this to be safe is that **all memory** + /// within the range of `self` must be **initialized**. If *any bytes* within + /// this range are not initialized, using this function is *instantly **undefined + /// behavior***, even if you *do noting* with the result. + /// + /// Also see the [crate-level Safety documentation][`crate#safety`] for more. + unsafe fn assume_initialized_as_bytes(&self) -> &[u8] { + // SAFETY: same requirements as function-level safety assuming the requirements + // for creating `self` are met + unsafe { core::slice::from_raw_parts(self.base_ptr().cast(), self.size()) } + } + + /// Interpret `self` as a mutable byte slice. This assumes that **all bytes** + /// in `self` are initialized. + /// + /// # Safety + /// + /// Assuming that the safety guarantees for creating `self` were followed, + /// the only extra requirement for this to be safe is that **all memory** + /// within the range of `self` must be **initialized**. If *any bytes* within + /// this range are not initialized, using this function is *instantly **undefined + /// behavior***, even if you *do noting* with the result. + /// + /// Also see the [crate-level Safety documentation][`crate#safety`] for more. + unsafe fn assume_initialized_as_bytes_mut(&mut self) -> &mut [u8] { + // SAFETY: same requirements as function-level safety assuming the requirements + // for creating `self` are met + unsafe { core::slice::from_raw_parts_mut(self.base_ptr_mut().cast(), self.size()) } + } + + /// Interpret a range of `self` as a byte slice. This assumes that **all bytes** + /// within `range` are initialized. + /// + /// In the future, this will hopefully not be needed as this operation will be equivalent to + /// something like `self.as_maybe_uninit_bytes_mut()[range].assume_init()`, but the `core`/`std` + /// implementation for this is still being scaffolded. + /// + /// # Safety + /// + /// Assuming that the safety guarantees for creating `self` were followed, + /// the only extra requirement for this to be safe is that **all memory** + /// within `range` must be **initialized**. If *any bytes* within + /// this range are not initialized, using this function is *instantly **undefined + /// behavior***, even if you *do noting* with the result. + /// + /// Also see the [crate-level Safety documentation][`crate#safety`] for more. + unsafe fn assume_range_initialized_as_bytes<R>(&self, range: R) -> &[u8] + where + R: core::slice::SliceIndex<[MaybeUninit<u8>], Output = [MaybeUninit<u8>]>, + { + let maybe_uninit_slice = &self.as_maybe_uninit_bytes()[range]; + // SAFETY: same requirements as function-level safety assuming the requirements + // for creating `self` are met since `MaybeUnint<T>` has same layout as `T` + unsafe { + core::slice::from_raw_parts( + maybe_uninit_slice.as_ptr().cast(), + maybe_uninit_slice.len(), + ) + } + } + + /// Interpret a range of `self` as a mutable byte slice. This assumes that **all bytes** + /// within `range` are initialized. + /// + /// In the future, this will hopefully not be needed as this operation will be equivalent to + /// something like `self.as_maybe_uninit_bytes_mut()[range].assume_init()`, but the `core`/`std` + /// implementation for this is still being scaffolded. + /// + /// # Safety + /// + /// Assuming that the safety guarantees for creating `self` were followed, + /// the only extra requirement for this to be safe is that **all memory** + /// within `range` must be **initialized**. If *any bytes* within + /// this range are not initialized, using this function is *instantly **undefined + /// behavior***, even if you *do noting* with the result. + /// + /// Also see the [crate-level Safety documentation][`crate#safety`] for more. + unsafe fn assume_range_initialized_as_bytes_mut<R>(&mut self, range: R) -> &mut [u8] + where + R: core::slice::SliceIndex<[MaybeUninit<u8>], Output = [MaybeUninit<u8>]>, + { + let maybe_uninit_slice = &mut self.as_maybe_uninit_bytes_mut()[range]; + // SAFETY: same requirements as function-level safety assuming the requirements + // for creating `self` are met since `MaybeUnint<T>` has same layout as `T` + unsafe { + core::slice::from_raw_parts_mut( + maybe_uninit_slice.as_mut_ptr().cast(), + maybe_uninit_slice.len(), + ) + } + } +} + +// SAFETY: The captured `[MaybeUninit<u8>]` will all be part of the same allocation object, and borrowck +// will assure that the borrows that occur on `self` on the relevant methods live long enough since they are +// native borrows anyway. +unsafe impl Slab for [MaybeUninit<u8>] { + fn base_ptr(&self) -> *const u8 { + self.as_ptr().cast() + } + + fn base_ptr_mut(&mut self) -> *mut u8 { + self.as_mut_ptr().cast() + } + + fn size(&self) -> usize { + core::mem::size_of_val(self) + } +} + +/// Takes a `Vec` and unsafely resizes it to the given length, returning a mutable slice to `MaybeUninit<T>` for each +/// item in the newly-resized `Vec`. +/// +/// # Safety +/// +/// You promise that the given `Vec` already has at least `length` capacity. You also promise to either fill all items before dropping +/// the returned slice, or to continue to not violate validity rules for any items that you do not initialize. +#[cfg(feature = "std")] +pub unsafe fn maybe_uninit_slice_from_vec<T>( + vec: &mut Vec<T>, + length: usize, +) -> &mut [MaybeUninit<T>] { + // SAFETY: As long as the function-level safety rules are met, this is valid + unsafe { + #[allow(clippy::uninit_vec)] + vec.set_len(length); + } + + // SAFETY: If function-level safety is met, then we are constructing a slice within a single allocation. `MaybeUninit<T>` is valid + // even for uninit memory, and has the same memory layout as `T`. + unsafe { core::slice::from_raw_parts_mut(vec.as_mut_ptr().cast::<MaybeUninit<T>>(), length) } +} + +/// Copies the elements from `src` to `dst`, returning a mutable reference to the now initialized contents of `dst`. +/// +/// If `T` does not implement `Copy`, use [`clone_into_maybe_uninit_slice`] +/// +/// This is similar to [`slice::copy_from_slice`]. This is identical to the implementation of the method +/// `write_to_slice` on [`MaybeUninit`], but that API is as yet unstable. +/// +/// # Panics +/// +/// This function will panic if the two slices have different lengths. +pub fn copy_into_maybe_uninit_slice<'a, T>(src: &[T], dst: &'a mut [MaybeUninit<T>]) -> &'a mut [T] +where + T: Copy, +{ + let uninit_src: &[MaybeUninit<T>] = + // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout + unsafe { &*(src as *const [T] as *const [MaybeUninit<T>]) }; + + dst.copy_from_slice(uninit_src); + + // SAFETY: Valid elements have just been copied into `this` so it is initialized + unsafe { &mut *(dst as *mut [MaybeUninit<T>] as *mut [T]) } +} + +/// Clones the elements from `src` to `dst`, returning a mutable reference to the now initialized contents of `dst`. +/// Any already initialized elements will not be dropped. +/// +/// If `T` implements `Copy`, use [`copy_into_maybe_uninit_slice`] +/// +/// This is similar to [`slice::clone_from_slice`] but does not drop existing elements. This is identical to the implementation of +/// the method `write_to_slice_cloned` on [`MaybeUninit`], but that API is as yet unstable. +/// +/// # Panics +/// +/// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics. +/// +/// If there is a panic, the already cloned elements will be dropped. +pub fn clone_into_maybe_uninit_slice<'a, T>(src: &[T], dst: &'a mut [MaybeUninit<T>]) -> &'a mut [T] +where + T: Clone, +{ + // unlike copy_from_slice this does not call clone_from_slice on the slice + // this is because `MaybeUninit<T: Clone>` does not implement Clone. + + struct Guard<'a, T> { + slice: &'a mut [MaybeUninit<T>], + initialized: usize, + } + + impl<'a, T> Drop for Guard<'a, T> { + fn drop(&mut self) { + let initialized_part = &mut self.slice[..self.initialized]; + // SAFETY: this raw slice will contain only initialized objects + // that's why, it is allowed to drop it. + unsafe { + core::ptr::drop_in_place( + &mut *(initialized_part as *mut [MaybeUninit<T>] as *mut [T]), + ); + } + } + } + + assert_eq!( + dst.len(), + src.len(), + "destination and source slices have different lengths" + ); + // NOTE: We need to explicitly slice them to the same length + // for bounds checking to be elided, and the optimizer will + // generate memcpy for simple cases (for example T = u8). + let len = dst.len(); + let src = &src[..len]; + + // guard is needed b/c panic might happen during a clone + let mut guard = Guard { + slice: dst, + initialized: 0, + }; + + #[allow(clippy::needless_range_loop)] + for i in 0..len { + guard.slice[i].write(src[i].clone()); + guard.initialized += 1; + } + + #[allow(clippy::mem_forget)] + core::mem::forget(guard); + + // SAFETY: Valid elements have just been written into `this` so it is initialized + unsafe { &mut *(dst as *mut [MaybeUninit<T>] as *mut [T]) } +} + +/// Represents a contiguous piece of a single allocation with some layout. +/// May be wholly or partially uninitialized. +/// +/// This exists as a convenient way to get access to a type implementing [`Slab`] +/// when dealing with your own raw allocations/buffers if you don't want to or +/// cannot implement [`Slab`] for another native type. +pub struct RawAllocation { + /// A pointer to the base address of the allocation + pub base_ptr: NonNull<u8>, + + /// The size of the allocation in bytes + pub size: usize, +} + +impl RawAllocation { + /// Create a new [`RawAllocation`] from a pointer and size. + /// + /// # Safety + /// + /// This function is safe in and of itself, as nothing will be done + /// with the pointer and size upon creation. + pub fn from_raw_parts(base_ptr: NonNull<u8>, size: usize) -> Self { + Self { base_ptr, size } + } + + /// Asserts that we are uniquely borrowing the memory range represented by `self` for + /// the duration of the borrow, giving us a [`BorrowedRawAllocation`] which implements [`Slab`]. + /// + /// # Safety + /// + /// Using this method makes some strong guarantees about the contained `base_ptr` and `size` + /// for the duration of the borrow. See the [safety][`Slab#safety`] documentation for the + /// [`Slab`] trait for a list of the guarantees you must make to use this method. + /// + /// Also see the [top-level safety documentation][`crate#safety`] + #[allow(clippy::needless_lifetimes)] // Important to be explicit in this case because of unsafety + pub unsafe fn borrow_as_slab<'a>(&'a mut self) -> BorrowedRawAllocation<'a> { + BorrowedRawAllocation { + base_ptr: self.base_ptr, + size: self.size, + phantom: PhantomData, + } + } +} + +/// Represents the unique borrow of a contiguous piece of a single allocation with some layout that is used as a +/// data copying destination. May be wholly or partially uninitialized. +/// +/// This type can only be obtained through the [`borrow_as_slab`][`RawAllocation::borrow_as_slab`] method on [`RawAllocation`]. +pub struct BorrowedRawAllocation<'a> { + base_ptr: NonNull<u8>, + size: usize, + phantom: PhantomData<&'a ()>, +} + +// SAFETY: So long as the safety requirements of `borrow_as_slab` are met, this is also safe +// since it's just a basic pass-thru of info. +unsafe impl<'a> Slab for BorrowedRawAllocation<'a> { + fn base_ptr(&self) -> *const u8 { + self.base_ptr.as_ptr() as *const u8 + } + + fn base_ptr_mut(&mut self) -> *mut u8 { + self.base_ptr.as_ptr() + } + + fn size(&self) -> usize { + self.size + } +} + +/// Given pointer and offset, returns a new offset aligned to `align`. +/// +/// `align` *must* be a power of two and >= 1 or else the result is meaningless. +fn align_offset_up_to(ptr: usize, offset: usize, align: usize) -> Option<usize> { + let offsetted_ptr = ptr.checked_add(offset)?; + let aligned_ptr = offsetted_ptr.checked_add(align - 1)? & !(align - 1); + // don't need to check since we know aligned_ptr is >= ptr at this point + Some(aligned_ptr - ptr) +} + +/// Compute and validate offsets for a copy operation with the given parameters. +fn compute_offsets<S: Slab>( + dst: &S, + start_offset: usize, + t_layout: Layout, + min_alignment: usize, +) -> Result<CopyRecord, CopyError> { + let copy_layout = t_layout.align_to(min_alignment.next_power_of_two())?; + + let copy_start_offset = + align_offset_up_to(dst.base_ptr() as usize, start_offset, copy_layout.align()) + .ok_or(CopyError::InvalidLayout)?; + let copy_end_offset = copy_start_offset + .checked_add(copy_layout.size()) + .ok_or(CopyError::InvalidLayout)?; + let copy_end_offset_padded = copy_start_offset + .checked_add(copy_layout.pad_to_align().size()) + .ok_or(CopyError::InvalidLayout)?; + + // check start is inside slab + // if within slab, we also know that copy_start_offset is <= isize::MAX since slab.size() must be <= isize::MAX + if copy_start_offset > dst.size() { + return Err(CopyError::OffsetOutOfBounds); + } + + // check end is inside slab + if copy_end_offset_padded > dst.size() { + return Err(CopyError::OutOfMemory); + } + + Ok(CopyRecord { + copy_start_offset, + copy_end_offset, + copy_end_offset_padded, + }) +} + +/// An error that may occur during a copy operation. +#[derive(Debug)] +pub enum CopyError { + /// Copy would exceed the end of the allocation + OutOfMemory, + /// Requested to copy to an offset outside the bounds of the allocation + OffsetOutOfBounds, + /// Computed invalid layout for copy operation, probably caused by incredibly large size, offset, or min-alignment parameters + InvalidLayout, +} + +impl core::fmt::Display for CopyError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", match self { + Self::OutOfMemory => "Copy would exceed the end of the allocation", + Self::OffsetOutOfBounds => "Requested copy to a location starting outside the allocation", + Self::InvalidLayout => "Invalid layout, probably caused by incredibly large size, offset, or alignment parameters", + }) + } +} + +#[cfg(feature = "std")] +impl std::error::Error for CopyError {} + +impl From<LayoutError> for CopyError { + fn from(_err: LayoutError) -> Self { + Self::InvalidLayout + } +} + +/// Record of the results of a copy operation +#[derive(Debug, Copy, Clone)] +pub struct CopyRecord { + /// The offset from the start of the allocation, in bytes, at which the + /// copy operation began to write data. + /// + /// Not necessarily equal to the `start_offset`, since this offset + /// includes necessary padding to assure alignment. + pub copy_start_offset: usize, + + /// The offset from the start of the allocation, in bytes, at which the + /// copy operation no longer wrote data. + /// + /// This does not include any padding at the end necessary to maintain + /// alignment requirements. + pub copy_end_offset: usize, + + /// The offset from the start of the allocation, in bytes, at which the + /// copy operation no longer wrote data, plus any padding necessary to + /// maintain derived alignment requirements. + pub copy_end_offset_padded: usize, +} + +/// Copies `src` into the memory represented by `dst` starting at a minimum location +/// of `start_offset` bytes past the start of `dst`. +/// +/// - `start_offset` is the offset into the allocation represented by `dst`, +/// in bytes, before which any copied data will *certainly not* be placed. However, +/// the actual beginning of the copied data may not be exactly at `start_offset` if +/// padding bytes are needed to satisfy alignment requirements. The actual beginning +/// of the copied bytes is contained in the returned [`CopyRecord`]. +/// +/// # Safety +/// +/// This function is safe on its own, however it is very possible to do unsafe +/// things if you read the copied data in the wrong way. See the +/// [crate-level Safety documentation][`crate#safety`] for more. +#[inline] +pub fn copy_to_offset<T: Copy, S: Slab>( + src: &T, + dst: &mut S, + start_offset: usize, +) -> Result<CopyRecord, CopyError> { + copy_to_offset_with_align(src, dst, start_offset, 1) +} + +/// Copies `src` into the memory represented by `dst` starting at a minimum location +/// of `start_offset` bytes past the start of `dst` and with minimum alignment +/// `min_alignment`. +/// +/// - `start_offset` is the offset into the allocation represented by `dst`, +/// in bytes, before which any copied data will *certainly not* be placed. However, +/// the actual beginning of the copied data may not be exactly at `start_offset` if +/// padding bytes are needed to satisfy alignment requirements. The actual beginning +/// of the copied bytes is contained in the returned [`CopyRecord`]. +/// - `min_alignment` is the minimum alignment to which the copy will be aligned. The +/// copy may not actually be aligned to `min_alignment` depending on the alignment requirements +/// of `T`. +/// +/// # Safety +/// +/// This function is safe on its own, however it is very possible to do unsafe +/// things if you read the copied data in the wrong way. See the +/// [crate-level Safety documentation][`crate#safety`] for more. +pub fn copy_to_offset_with_align<T: Copy, S: Slab>( + src: &T, + dst: &mut S, + start_offset: usize, + min_alignment: usize, +) -> Result<CopyRecord, CopyError> { + let t_layout = Layout::new::<T>(); + let record = compute_offsets(&*dst, start_offset, t_layout, min_alignment)?; + + // SAFETY: if compute_offsets succeeded, this has already been checked to be safe. + let dst_ptr = unsafe { dst.base_ptr_mut().add(record.copy_start_offset) }.cast::<T>(); + + // SAFETY: + // - src is valid as we have a reference to it + // - dst is valid so long as requirements for `slab` were met, i.e. + // we have unique access to the region described and that it is valid for the duration + // of 'a. + // - areas not overlapping as long as safety requirements of creation of `self` were met, + // i.e. that we have exclusive access to the region of memory described. + // - dst aligned at least to align_of::<T>() + // - checked that copy stays within bounds of our allocation + unsafe { + core::ptr::copy_nonoverlapping(src as *const T, dst_ptr, 1); + } + + Ok(record) +} + +/// Copies from `slice` into the memory represented by `dst` starting at a minimum location +/// of `start_offset` bytes past the start of `self`. +/// +/// - `start_offset` is the offset into the allocation represented by `dst`, +/// in bytes, before which any copied data will *certainly not* be placed. However, +/// the actual beginning of the copied data may not be exactly at `start_offset` if +/// padding bytes are needed to satisfy alignment requirements. The actual beginning +/// of the copied bytes is contained in the returned [`CopyRecord`]. +/// +/// # Safety +/// +/// This function is safe on its own, however it is very possible to do unsafe +/// things if you read the copied data in the wrong way. See the +/// [crate-level Safety documentation][`crate#safety`] for more. +#[inline] +pub fn copy_from_slice_to_offset<T: Copy, S: Slab>( + src: &[T], + dst: &mut S, + start_offset: usize, +) -> Result<CopyRecord, CopyError> { + copy_from_slice_to_offset_with_align(src, dst, start_offset, 1) +} + +/// Copies from `slice` into the memory represented by `dst` starting at a minimum location +/// of `start_offset` bytes past the start of `dst`. +/// +/// - `start_offset` is the offset into the allocation represented by `dst`, +/// in bytes, before which any copied data will *certainly not* be placed. However, +/// the actual beginning of the copied data may not be exactly at `start_offset` if +/// padding bytes are needed to satisfy alignment requirements. The actual beginning +/// of the copied bytes is contained in the returned [`CopyRecord`]. +/// - `min_alignment` is the minimum alignment to which the copy will be aligned. The +/// copy may not actually be aligned to `min_alignment` depending on the alignment requirements +/// of `T` and the underlying allocation. +/// - The whole data of the slice will be copied directly, so, alignment between elements +/// ignores `min_alignment`. +/// +/// # Safety +/// +/// This function is safe on its own, however it is very possible to do unsafe +/// things if you read the copied data in the wrong way. See the +/// [crate-level Safety documentation][`crate#safety`] for more. +pub fn copy_from_slice_to_offset_with_align<T: Copy, S: Slab>( + src: &[T], + dst: &mut S, + start_offset: usize, + min_alignment: usize, +) -> Result<CopyRecord, CopyError> { + let t_layout = Layout::for_value(src); + let record = compute_offsets(&*dst, start_offset, t_layout, min_alignment)?; + + // SAFETY: if compute_offsets succeeded, this has already been checked to be safe. + let dst_ptr = unsafe { dst.base_ptr_mut().add(record.copy_start_offset) }.cast::<T>(); + + // SAFETY: + // - src is valid as we have a reference to it + // - dst is valid so long as requirements for `slab` were met, i.e. + // we have unique access to the region described and that it is valid for the duration + // of 'a. + // - areas not overlapping as long as safety requirements of creation of `self` were met, + // i.e. that we have exclusive access to the region of memory described. + // - dst aligned at least to align_of::<T>() + // - checked that copy stays within bounds of our allocation + unsafe { + core::ptr::copy_nonoverlapping(src.as_ptr(), dst_ptr, src.len()); + } + + Ok(record) +} + +/// Copies from `src` iterator into the memory represented by `dst` starting at a minimum location +/// of `start_offset` bytes past the start of `dst`. +/// +/// Returns a vector of [`CopyRecord`]s, one for each item in the `src` iterator. +/// +/// - `start_offset` is the offset into the allocation represented by `dst`, +/// in bytes, before which any copied data will *certainly not* be placed. However, +/// the actual beginning of the copied data may not be exactly at `start_offset` if +/// padding bytes are needed to satisfy alignment requirements. The actual beginning +/// of the copied bytes is contained in the returned [`CopyRecord`]s. +/// - `min_alignment` is the minimum alignment to which the copy will be aligned. The +/// copy may not actually be aligned to `min_alignment` depending on the alignment requirements +/// of `T`. +/// - For this variation, `min_alignment` will also be respected *between* elements yielded by +/// the iterator. To copy inner elements aligned only to `align_of::<T>()`, see +/// [`copy_from_iter_to_offset_with_align_packed`] +/// +/// # Safety +/// +/// This function is safe on its own, however it is very possible to do unsafe +/// things if you read the copied data in the wrong way. See the +/// [crate-level Safety documentation][`crate#safety`] for more. +#[cfg(feature = "std")] +pub fn copy_from_iter_to_offset_with_align<T: Copy, Iter: Iterator<Item = T>, S: Slab>( + src: Iter, + dst: &mut S, + start_offset: usize, + min_alignment: usize, +) -> Result<Vec<CopyRecord>, CopyError> { + let mut offset = start_offset; + + src.map(|item| { + let copy_record = copy_to_offset_with_align(&item, dst, offset, min_alignment)?; + offset = copy_record.copy_end_offset; + Ok(copy_record) + }) + .collect::<Result<Vec<_>, _>>() +} + +/// Like [`copy_from_iter_to_offset_with_align`] except that +/// alignment between elements yielded by the iterator will ignore `min_alignment` +/// and rather only be aligned to the alignment of `T`. +/// +/// Because of this, only one [`CopyRecord`] is returned specifying the record of the +/// entire block of copied data. If the `src` iterator is empty, returns `None`. +pub fn copy_from_iter_to_offset_with_align_packed<T: Copy, Iter: Iterator<Item = T>, S: Slab>( + mut src: Iter, + dst: &mut S, + start_offset: usize, + min_alignment: usize, +) -> Result<Option<CopyRecord>, CopyError> { + let first_record = if let Some(first_item) = src.next() { + copy_to_offset_with_align(&first_item, dst, start_offset, min_alignment)? + } else { + return Ok(None); + }; + + let mut prev_record = first_record; + + for item in src { + let copy_record = copy_to_offset_with_align(&item, dst, prev_record.copy_end_offset, 1)?; + prev_record = copy_record; + } + + Ok(Some(CopyRecord { + copy_start_offset: first_record.copy_start_offset, + copy_end_offset: prev_record.copy_end_offset, + copy_end_offset_padded: prev_record.copy_end_offset_padded, + })) +} |