pax_global_header00006660000000000000000000000064147416746310014527gustar00rootroot0000000000000052 comment=cbbce9e3977ef154023bbda0660027c5e523766a Nugine-outref-cbbce9e/000077500000000000000000000000001474167463100151145ustar00rootroot00000000000000Nugine-outref-cbbce9e/.github/000077500000000000000000000000001474167463100164545ustar00rootroot00000000000000Nugine-outref-cbbce9e/.github/dependabot.yml000066400000000000000000000010731474167463100213050ustar00rootroot00000000000000# To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "cargo" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "monthly" groups: dependencies: patterns: - "*" Nugine-outref-cbbce9e/.github/workflows/000077500000000000000000000000001474167463100205115ustar00rootroot00000000000000Nugine-outref-cbbce9e/.github/workflows/ci.yml000066400000000000000000000020671474167463100216340ustar00rootroot00000000000000name: CI on: push: branches: - main - 'feat/**' pull_request: branches: - main - 'feat/**' schedule: - cron: '0 0 * * 0' # at midnight of each sunday workflow_dispatch: jobs: develop: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@just - uses: dtolnay/rust-toolchain@nightly with: components: rustfmt, clippy, miri - uses: Swatinem/rust-cache@v2 - run: just ci msrv: runs-on: ubuntu-latest strategy: fail-fast: false matrix: toolchain: - 1.63.0 # MSRV - stable steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@just - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.toolchain }} - uses: Swatinem/rust-cache@v2 - run: just test audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@cargo-audit - run: cargo audit -D warnings Nugine-outref-cbbce9e/.github/workflows/publish.yml000066400000000000000000000005421474167463100227030ustar00rootroot00000000000000name: Publish on: release: types: [published] jobs: publish: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@just - uses: dtolnay/rust-toolchain@nightly - run: cargo login ${{ secrets.CRATES_IO_API_TOKEN }} - run: cargo publish --dry-run - run: cargo publish Nugine-outref-cbbce9e/.gitignore000066400000000000000000000000351474167463100171020ustar00rootroot00000000000000/Cargo.lock /target /.vscode Nugine-outref-cbbce9e/CODE_OF_CONDUCT.md000066400000000000000000000006701474167463100177160ustar00rootroot00000000000000# Code of Conduct This project follows the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct). **ADDITIONAL**: DO NOT submit anything about real world politics. For example, the political statements in the pages below will be rejected. + + + Nugine-outref-cbbce9e/CONTRIBUTING.md000066400000000000000000000017011474167463100173440ustar00rootroot00000000000000# Development Guide ## Requirements | Toolchain | Version | | :-----------------------------------: | :-----: | | [Rust](https://rustup.rs/) | ^1.63.0 | | [just](https://github.com/casey/just) | ^1.36.0 | ## Workflow ### Download source code ```bash git clone https://github.com/Nugine/outref.git cd outref ``` ### Run basic checks and tests ```bash just dev ``` ### Open documentation ```bash just doc ``` ### Run CI checks locally ```bash just ci ``` ## Git ### Commit Message We follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification. ### Pull Request Before creating or updating a pull request, please make sure to run the following commands: ```bash just dev ``` It's recommended to resolve any warnings or errors before submitting. Note that some lints may be too restrict. You can allow some of them if you think they are not helpful to the code quality. Nugine-outref-cbbce9e/Cargo.toml000066400000000000000000000004141474167463100170430ustar00rootroot00000000000000[package] name = "outref" version = "0.5.2" edition = "2021" description = "Out reference" license = "MIT" repository = "https://github.com/Nugine/outref" keywords = ["write-only", "reference", "slice"] categories = ["no-std", "rust-patterns"] rust-version = "1.63.0" Nugine-outref-cbbce9e/LICENSE000066400000000000000000000020461474167463100161230ustar00rootroot00000000000000MIT License Copyright (c) 2022 Nugine 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.Nugine-outref-cbbce9e/README.md000066400000000000000000000007621474167463100164000ustar00rootroot00000000000000# outref [![Latest Version]][crates.io] [![Documentation]][docs.rs] ![License] Out reference (`&'a out T`). [crates.io]: https://crates.io/crates/outref [Latest Version]: https://img.shields.io/crates/v/outref.svg [Documentation]: https://docs.rs/outref/badge.svg [docs.rs]: https://docs.rs/outref [License]: https://img.shields.io/crates/l/outref.svg Documentation: ## Contributing + [Development Guide](./CONTRIBUTING.md) + [Code of Conduct](./CODE_OF_CONDUCT.md) Nugine-outref-cbbce9e/justfile000066400000000000000000000007361474167463100166720ustar00rootroot00000000000000dev: just fmt just lint just test just miri fmt *ARGS: cargo fmt --all {{ARGS}} lint *ARGS: cargo clippy --all-features --tests --benches {{ARGS}} test *ARGS: cargo test --all-features {{ARGS}} miri *ARGS: cargo +nightly miri test --all-features {{ARGS}} doc *ARGS: RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --open --no-deps --all-features {{ARGS}} ci: just fmt --check just lint -- -D warnings just test just miri Nugine-outref-cbbce9e/src/000077500000000000000000000000001474167463100157035ustar00rootroot00000000000000Nugine-outref-cbbce9e/src/lib.rs000066400000000000000000000200451474167463100170200ustar00rootroot00000000000000//! Out reference ([`&'a out T`](Out)). #![deny( missing_docs, clippy::all, clippy::cargo, clippy::missing_const_for_fn, clippy::missing_inline_in_public_items, clippy::must_use_candidate )] #![cfg_attr(not(test), no_std)] use core::marker::PhantomData; use core::mem::MaybeUninit; use core::ptr::{self, NonNull}; use core::slice; /// Out reference ([`&'a out T`](Out)). /// /// An out reference is similar to a mutable reference, but it may point to uninitialized memory. /// An out reference may be used to initialize the pointee or represent a data buffer. /// /// [`&'a out T`](Out) can be converted from: /// + [`&'a mut MaybeUninit`](core::mem::MaybeUninit) /// and [`&'a mut [MaybeUninit]`](core::mem::MaybeUninit), /// where the `T` may be uninitialized. /// + [`&'a mut T`](reference) and [`&'a mut [T]`](prim@slice), /// where the `T` is initialized and [Copy]. /// /// It is not allowed to corrupt or de-initialize the pointee, which may cause unsoundness. /// It is the main difference between [`&'a out T`](Out) /// and [`&'a mut MaybeUninit`](core::mem::MaybeUninit) /// /[`&'a mut [MaybeUninit]`](core::mem::MaybeUninit). /// /// Any reads through an out reference may read uninitialized value(s) and cause undefined behavior. /// /// [`AsOut`] provides a shortcut for converting a mutable reference to an out reference. /// /// # Examples /// /// ```rust /// use core::ptr; /// use core::slice; /// use core::mem::MaybeUninit; /// /// use outref::AsOut; /// use outref::Out; /// /// fn copy<'d, T: Copy>(src: &[T], mut dst: Out<'d, [T]>) -> &'d mut [T] { /// assert_eq!(src.len(), dst.len()); /// unsafe { /// let count = src.len(); /// let src = src.as_ptr(); /// let dst = dst.as_mut_ptr(); /// ptr::copy_nonoverlapping(src, dst, count); /// slice::from_raw_parts_mut(dst, count) /// } /// } /// /// fn copy_init<'d, T: Copy>(src: &[T], dst: &'d mut [T]) -> &'d mut [T] { /// copy(src, dst.as_out()) /// } /// /// fn copy_uninit<'d, T: Copy>(src: &[T], dst: &'d mut [MaybeUninit]) -> &'d mut [T] { /// copy(src, dst.as_out()) /// } /// ``` #[repr(transparent)] pub struct Out<'a, T: 'a + ?Sized> { data: NonNull, _marker: PhantomData<&'a mut T>, } unsafe impl Send for Out<'_, T> {} unsafe impl Sync for Out<'_, T> {} impl Unpin for Out<'_, T> {} impl<'a, T: ?Sized> Out<'a, T> { /// Forms an [`Out<'a, T>`](Out) /// /// # Safety /// /// * `data` must be valid for writes. /// * `data` must be properly aligned. #[inline(always)] #[must_use] pub unsafe fn new(data: *mut T) -> Self { Self { data: NonNull::new_unchecked(data), _marker: PhantomData, } } /// Converts to a mutable (unique) reference to the value. /// /// # Safety /// The referenced value must be initialized when calling this function. #[inline(always)] #[must_use] pub unsafe fn assume_init(mut self) -> &'a mut T { self.data.as_mut() } /// Reborrows the out reference for a shorter lifetime. #[inline(always)] #[must_use] pub fn reborrow<'s>(&'s mut self) -> Out<'s, T> where 'a: 's, { Self { data: self.data, _marker: PhantomData, } } } impl<'a, T> Out<'a, T> { /// Forms an [`Out<'a, T>`](Out). #[inline(always)] #[must_use] pub fn from_mut(data: &'a mut T) -> Self where T: Copy, { unsafe { Self::new(data) } } /// Forms an [`Out<'a, T>`](Out) from an uninitialized value. #[inline(always)] #[must_use] pub fn from_uninit(data: &'a mut MaybeUninit) -> Self { let data: *mut T = MaybeUninit::as_mut_ptr(data); unsafe { Self::new(data.cast()) } } /// Converts to [`&'a mut MaybeUninit`](core::mem::MaybeUninit) /// # Safety /// It is not allowed to corrupt or de-initialize the pointee. #[inline(always)] #[must_use] pub unsafe fn into_uninit(self) -> &'a mut MaybeUninit { &mut *self.data.as_ptr().cast() } /// Returns an unsafe mutable pointer to the value. #[inline(always)] #[must_use] pub fn as_mut_ptr(&mut self) -> *mut T { self.data.as_ptr().cast() } } impl<'a, T> Out<'a, [T]> { /// Forms an [`Out<'a, [T]>`](Out). #[inline(always)] #[must_use] pub fn from_slice(slice: &'a mut [T]) -> Self where T: Copy, { unsafe { Self::new(slice) } } /// Forms an [`Out<'a, [T]>`](Out) from an uninitialized slice. #[inline(always)] #[must_use] pub fn from_uninit_slice(slice: &'a mut [MaybeUninit]) -> Self { let slice: *mut [T] = { let len = slice.len(); let data = slice.as_mut_ptr().cast(); ptr::slice_from_raw_parts_mut(data, len) }; unsafe { Self::new(slice) } } /// Converts to [`&'a mut [MaybeUninit]`](core::mem::MaybeUninit) /// # Safety /// It is not allowed to corrupt or de-initialize the pointee. #[inline(always)] #[must_use] pub unsafe fn into_uninit_slice(self) -> &'a mut [MaybeUninit] { let len = self.len(); let data = self.data.as_ptr().cast(); slice::from_raw_parts_mut(data, len) } /// Returns true if the slice has a length of 0. #[inline(always)] #[must_use] pub const fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the number of elements in the slice. #[inline(always)] #[must_use] pub const fn len(&self) -> usize { NonNull::len(self.data) } /// Returns an unsafe mutable pointer to the slice's buffer. #[inline(always)] #[must_use] pub fn as_mut_ptr(&mut self) -> *mut T { self.data.as_ptr().cast() } } /// Extension trait for converting a mutable reference to an out reference. /// /// # Safety /// This trait can be trusted to be implemented correctly for all types. pub unsafe trait AsOut { /// Returns an out reference to self. fn as_out(&mut self) -> Out<'_, T>; } unsafe impl AsOut for T where T: Copy, { #[inline(always)] #[must_use] fn as_out(&mut self) -> Out<'_, T> { Out::from_mut(self) } } unsafe impl AsOut for MaybeUninit { #[inline(always)] #[must_use] fn as_out(&mut self) -> Out<'_, T> { Out::from_uninit(self) } } unsafe impl AsOut<[T]> for [T] where T: Copy, { #[inline(always)] #[must_use] fn as_out(&mut self) -> Out<'_, [T]> { Out::from_slice(self) } } unsafe impl AsOut<[T]> for [MaybeUninit] { #[inline(always)] #[must_use] fn as_out(&mut self) -> Out<'_, [T]> { Out::from_uninit_slice(self) } } #[cfg(test)] mod tests { use super::*; use core::{mem, ptr}; unsafe fn raw_fill_copied(dst: *mut T, len: usize, val: T) { if mem::size_of::() == 0 { return; } if len == 0 { return; } if mem::size_of::() == 1 { let val: u8 = mem::transmute_copy(&val); dst.write_bytes(val, len); } else { dst.write(val); let mut n = 1; while n <= len / 2 { ptr::copy_nonoverlapping(dst, dst.add(n), n); n *= 2; } let count = len - n; if count > 0 { ptr::copy_nonoverlapping(dst, dst.add(n), count); } } } fn fill(mut buf: Out<'_, [T]>, val: T) -> &'_ mut [T] { unsafe { let len = buf.len(); let dst = buf.as_mut_ptr(); raw_fill_copied(dst, len, val); buf.assume_init() } } #[test] fn fill_vec() { for n in 0..128 { let mut v: Vec = Vec::with_capacity(n); fill(v.spare_capacity_mut().as_out(), 0x12345678); unsafe { v.set_len(n) }; for &x in &v { assert_eq!(x, 0x12345678); } drop(v); } } }