├── .github ├── dependabot.yml └── workflows │ ├── ci.yaml │ └── release.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src └── lib.rs └── tests └── padding.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | commit-message: 8 | prefix: '' 9 | labels: [] 10 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | schedule: 9 | - cron: '0 2 * * 0' 10 | 11 | env: 12 | CARGO_INCREMENTAL: 0 13 | CARGO_NET_RETRY: 10 14 | CARGO_TERM_COLOR: always 15 | RUST_BACKTRACE: 1 16 | RUSTFLAGS: -D warnings -A deprecated 17 | RUSTDOCFLAGS: -D warnings 18 | RUSTUP_MAX_RETRIES: 10 19 | 20 | defaults: 21 | run: 22 | shell: bash 23 | 24 | jobs: 25 | test: 26 | runs-on: ${{ matrix.os }} 27 | strategy: 28 | fail-fast: false 29 | matrix: 30 | os: [ubuntu-latest] 31 | rust: [nightly, beta, stable] 32 | steps: 33 | - uses: actions/checkout@v3 34 | - name: Install Rust 35 | run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} 36 | - run: cargo build --all --all-features --all-targets 37 | - name: Run cargo check (without dev-dependencies to catch missing feature flags) 38 | if: startsWith(matrix.rust, 'nightly') 39 | run: cargo check -Z features=dev_dep 40 | - run: cargo test 41 | 42 | msrv: 43 | runs-on: ubuntu-latest 44 | strategy: 45 | matrix: 46 | # When updating this, the reminder to update the minimum supported 47 | # Rust version in Cargo.toml. 48 | rust: ['1.31'] 49 | steps: 50 | - uses: actions/checkout@v3 51 | - name: Install Rust 52 | run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} 53 | - run: cargo build 54 | 55 | clippy: 56 | runs-on: ubuntu-latest 57 | steps: 58 | - uses: actions/checkout@v3 59 | - name: Install Rust 60 | run: rustup update stable 61 | - run: cargo clippy --all-features --all-targets 62 | 63 | fmt: 64 | runs-on: ubuntu-latest 65 | steps: 66 | - uses: actions/checkout@v3 67 | - name: Install Rust 68 | run: rustup update stable 69 | - run: cargo fmt --all --check 70 | 71 | security_audit: 72 | runs-on: ubuntu-latest 73 | steps: 74 | - uses: actions/checkout@v3 75 | # https://github.com/rustsec/audit-check/issues/2 76 | - uses: rustsec/audit-check@master 77 | with: 78 | token: ${{ secrets.GITHUB_TOKEN }} 79 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - v[0-9]+.* 7 | 8 | jobs: 9 | create-release: 10 | if: github.repository_owner == 'smol-rs' 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - uses: taiki-e/create-gh-release-action@v1 15 | with: 16 | changelog: CHANGELOG.md 17 | branch: master 18 | env: 19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Version 1.3.0 2 | 3 | - This crate is now deprecated in favor of [crossbeam-utils::CachePadded](https://docs.rs/crossbeam-utils/latest/crossbeam_utils/struct.CachePadded.html). 4 | 5 | # Version 1.2.0 6 | 7 | - Improve implementation of `CachePadded`. (#8) 8 | 9 | # Version 1.1.1 10 | 11 | - Forbid unsafe code. 12 | 13 | # Version 1.1.0 14 | 15 | - Mark `CachePadded::new()` as const fn. 16 | 17 | # Version 1.0.0 18 | 19 | - Initial version 20 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cache-padded" 3 | # When publishing a new version: 4 | # - Update CHANGELOG.md 5 | # - Create "v1.x.y" git tag 6 | version = "1.3.0" 7 | authors = ["Stjepan Glavina "] 8 | edition = "2018" 9 | rust-version = "1.31" 10 | description = "Prevent false sharing by padding and aligning to the length of a cache line" 11 | license = "Apache-2.0 OR MIT" 12 | repository = "https://github.com/smol-rs/cache-padded" 13 | homepage = "https://github.com/smol-rs/cache-padded" 14 | keywords = ["cache", "padding", "lock-free", "atomic"] 15 | categories = ["concurrency", "no-std"] 16 | exclude = ["/.*"] 17 | -------------------------------------------------------------------------------- /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 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cache-padded (deprecated) 2 | 3 | [![Build](https://github.com/smol-rs/cache-padded/workflows/Build%20and%20test/badge.svg)]( 4 | https://github.com/smol-rs/cache-padded/actions) 5 | [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( 6 | https://github.com/smol-rs/cache-padded) 7 | [![Cargo](https://img.shields.io/crates/v/cache-padded.svg)]( 8 | https://crates.io/crates/cache-padded) 9 | [![Documentation](https://docs.rs/cache-padded/badge.svg)]( 10 | https://docs.rs/cache-padded) 11 | 12 | **This crate is now deprecated in favor of [crossbeam-utils::CachePadded](https://docs.rs/crossbeam-utils/latest/crossbeam_utils/struct.CachePadded.html).** 13 | 14 | Prevent false sharing by padding and aligning to the length of a cache line. 15 | 16 | In concurrent programming, sometimes it is desirable to make sure commonly accessed shared data 17 | is not all placed into the same cache line. Updating an atomic value invalides the whole cache 18 | line it belongs to, which makes the next access to the same cache line slower for other CPU 19 | cores. Use `CachePadded` to ensure updating one piece of data doesn't invalidate other cached 20 | data. 21 | 22 | ## Size and alignment 23 | 24 | Cache lines are assumed to be N bytes long, depending on the architecture: 25 | 26 | * On x86-64, aarch64, and powerpc64, N = 128. 27 | * On arm, mips, mips64, and riscv64, N = 32. 28 | * On s390x, N = 256. 29 | * On all others, N = 64. 30 | 31 | Note that N is just a reasonable guess and is not guaranteed to match the actual cache line 32 | length of the machine the program is running on. 33 | 34 | The size of `CachePadded` is the smallest multiple of N bytes large enough to accommodate 35 | a value of type `T`. 36 | 37 | The alignment of `CachePadded` is the maximum of N bytes and the alignment of `T`. 38 | 39 | ## Examples 40 | 41 | Alignment and padding: 42 | 43 | ```rust 44 | use cache_padded::CachePadded; 45 | 46 | let array = [CachePadded::new(1i8), CachePadded::new(2i8)]; 47 | let addr1 = &*array[0] as *const i8 as usize; 48 | let addr2 = &*array[1] as *const i8 as usize; 49 | 50 | assert!(addr2 - addr1 >= 64); 51 | assert_eq!(addr1 % 64, 0); 52 | assert_eq!(addr2 % 64, 0); 53 | ``` 54 | 55 | When building a concurrent queue with a head and a tail index, it is wise to place indices in 56 | different cache lines so that concurrent threads pushing and popping elements don't invalidate 57 | each other's cache lines: 58 | 59 | ```rust 60 | use cache_padded::CachePadded; 61 | use std::sync::atomic::AtomicUsize; 62 | 63 | struct Queue { 64 | head: CachePadded, 65 | tail: CachePadded, 66 | buffer: *mut T, 67 | } 68 | ``` 69 | 70 | ## License 71 | 72 | Licensed under either of 73 | 74 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 75 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 76 | 77 | at your option. 78 | 79 | #### Contribution 80 | 81 | Unless you explicitly state otherwise, any contribution intentionally submitted 82 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 83 | dual licensed as above, without any additional terms or conditions. 84 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Prevent false sharing by padding and aligning to the length of a cache line. 2 | //! 3 | //! In concurrent programming, sometimes it is desirable to make sure commonly accessed shared data 4 | //! is not all placed into the same cache line. Updating an atomic value invalidates the whole cache 5 | //! line it belongs to, which makes the next access to the same cache line slower for other CPU 6 | //! cores. Use [`CachePadded`] to ensure updating one piece of data doesn't invalidate other cached 7 | //! data. 8 | //! 9 | //! # Size and alignment 10 | //! 11 | //! Cache lines are assumed to be N bytes long, depending on the architecture: 12 | //! 13 | //! * On x86-64, aarch64, and powerpc64, N = 128. 14 | //! * On arm, mips, mips64, and riscv64, N = 32. 15 | //! * On s390x, N = 256. 16 | //! * On all others, N = 64. 17 | //! 18 | //! Note that N is just a reasonable guess and is not guaranteed to match the actual cache line 19 | //! length of the machine the program is running on. 20 | //! 21 | //! The size of `CachePadded` is the smallest multiple of N bytes large enough to accommodate 22 | //! a value of type `T`. 23 | //! 24 | //! The alignment of `CachePadded` is the maximum of N bytes and the alignment of `T`. 25 | //! 26 | //! # Examples 27 | //! 28 | //! Alignment and padding: 29 | //! 30 | //! ``` 31 | //! use cache_padded::CachePadded; 32 | //! 33 | //! let array = [CachePadded::new(1i8), CachePadded::new(2i8)]; 34 | //! let addr1 = &*array[0] as *const i8 as usize; 35 | //! let addr2 = &*array[1] as *const i8 as usize; 36 | //! 37 | //! assert!(addr2 - addr1 >= 64); 38 | //! assert_eq!(addr1 % 64, 0); 39 | //! assert_eq!(addr2 % 64, 0); 40 | //! ``` 41 | //! 42 | //! When building a concurrent queue with a head and a tail index, it is wise to place indices in 43 | //! different cache lines so that concurrent threads pushing and popping elements don't invalidate 44 | //! each other's cache lines: 45 | //! 46 | //! ``` 47 | //! use cache_padded::CachePadded; 48 | //! use std::sync::atomic::AtomicUsize; 49 | //! 50 | //! struct Queue { 51 | //! head: CachePadded, 52 | //! tail: CachePadded, 53 | //! buffer: *mut T, 54 | //! } 55 | //! ``` 56 | 57 | #![no_std] 58 | #![forbid(unsafe_code)] 59 | #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] 60 | #![deprecated( 61 | since = "1.3.0", 62 | note = "This crate is now deprecated in favor of [crossbeam-utils::CachePadded](https://docs.rs/crossbeam-utils/latest/crossbeam_utils/struct.CachePadded.html)." 63 | )] 64 | 65 | use core::fmt; 66 | use core::ops::{Deref, DerefMut}; 67 | 68 | /// Pads and aligns data to the length of a cache line. 69 | // Starting from Intel's Sandy Bridge, spatial prefetcher is now pulling pairs of 64-byte cache 70 | // lines at a time, so we have to align to 128 bytes rather than 64. 71 | // 72 | // Sources: 73 | // - https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf 74 | // - https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107 75 | // 76 | // ARM's big.LITTLE architecture has asymmetric cores and "big" cores have 128-byte cache line size. 77 | // 78 | // Sources: 79 | // - https://www.mono-project.com/news/2016/09/12/arm64-icache/ 80 | // 81 | // powerpc64 has 128-byte cache line size. 82 | // 83 | // Sources: 84 | // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_ppc64x.go#L9 85 | #[cfg_attr( 86 | any( 87 | target_arch = "x86_64", 88 | target_arch = "aarch64", 89 | target_arch = "powerpc64", 90 | ), 91 | repr(align(128)) 92 | )] 93 | // arm, mips, mips64, and riscv64 have 32-byte cache line size. 94 | // 95 | // Sources: 96 | // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_arm.go#L7 97 | // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips.go#L7 98 | // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mipsle.go#L7 99 | // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips64x.go#L9 100 | // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_riscv64.go#L7 101 | #[cfg_attr( 102 | any( 103 | target_arch = "arm", 104 | target_arch = "mips", 105 | target_arch = "mips64", 106 | target_arch = "riscv64", 107 | ), 108 | repr(align(32)) 109 | )] 110 | // s390x has 256-byte cache line size. 111 | // 112 | // Sources: 113 | // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_s390x.go#L7 114 | #[cfg_attr(target_arch = "s390x", repr(align(256)))] 115 | // x86 and wasm have 64-byte cache line size. 116 | // 117 | // Sources: 118 | // - https://github.com/golang/go/blob/dda2991c2ea0c5914714469c4defc2562a907230/src/internal/cpu/cpu_x86.go#L9 119 | // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_wasm.go#L7 120 | // 121 | // All others are assumed to have 64-byte cache line size. 122 | #[cfg_attr( 123 | not(any( 124 | target_arch = "x86_64", 125 | target_arch = "aarch64", 126 | target_arch = "powerpc64", 127 | target_arch = "arm", 128 | target_arch = "mips", 129 | target_arch = "mips64", 130 | target_arch = "riscv64", 131 | target_arch = "s390x", 132 | )), 133 | repr(align(64)) 134 | )] 135 | #[derive(Clone, Copy, Default, Hash, PartialEq, Eq)] 136 | pub struct CachePadded(T); 137 | 138 | impl CachePadded { 139 | /// Pads and aligns a piece of data to the length of a cache line. 140 | /// 141 | /// # Examples 142 | /// 143 | /// ``` 144 | /// use cache_padded::CachePadded; 145 | /// 146 | /// let padded = CachePadded::new(1); 147 | /// ``` 148 | pub const fn new(t: T) -> CachePadded { 149 | CachePadded(t) 150 | } 151 | 152 | /// Returns the inner data. 153 | /// 154 | /// # Examples 155 | /// 156 | /// ``` 157 | /// use cache_padded::CachePadded; 158 | /// 159 | /// let padded = CachePadded::new(7); 160 | /// let data = padded.into_inner(); 161 | /// assert_eq!(data, 7); 162 | /// ``` 163 | pub fn into_inner(self) -> T { 164 | self.0 165 | } 166 | } 167 | 168 | impl Deref for CachePadded { 169 | type Target = T; 170 | 171 | fn deref(&self) -> &T { 172 | &self.0 173 | } 174 | } 175 | 176 | impl DerefMut for CachePadded { 177 | fn deref_mut(&mut self) -> &mut T { 178 | &mut self.0 179 | } 180 | } 181 | 182 | impl fmt::Debug for CachePadded { 183 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 184 | f.debug_tuple("CachePadded").field(&self.0).finish() 185 | } 186 | } 187 | 188 | impl From for CachePadded { 189 | fn from(t: T) -> Self { 190 | CachePadded::new(t) 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /tests/padding.rs: -------------------------------------------------------------------------------- 1 | use std::cell::Cell; 2 | use std::mem; 3 | 4 | use cache_padded::CachePadded; 5 | 6 | #[test] 7 | fn default() { 8 | let x: CachePadded = Default::default(); 9 | assert_eq!(*x, 0); 10 | } 11 | 12 | #[test] 13 | fn store_u64() { 14 | let x: CachePadded = CachePadded::new(17); 15 | assert_eq!(*x, 17); 16 | } 17 | 18 | #[test] 19 | fn store_pair() { 20 | let x: CachePadded<(u64, u64)> = CachePadded::new((17, 37)); 21 | assert_eq!(x.0, 17); 22 | assert_eq!(x.1, 37); 23 | } 24 | 25 | #[test] 26 | fn distance() { 27 | let arr = [CachePadded::new(17u8), CachePadded::new(37u8)]; 28 | let a = &*arr[0] as *const u8; 29 | let b = &*arr[1] as *const u8; 30 | assert!(unsafe { a.offset(64) } <= b); 31 | } 32 | 33 | #[test] 34 | fn different_sizes() { 35 | CachePadded::new(17u8); 36 | CachePadded::new(17u16); 37 | CachePadded::new(17u32); 38 | CachePadded::new([17u64; 0]); 39 | CachePadded::new([17u64; 1]); 40 | CachePadded::new([17u64; 2]); 41 | CachePadded::new([17u64; 3]); 42 | CachePadded::new([17u64; 4]); 43 | CachePadded::new([17u64; 5]); 44 | CachePadded::new([17u64; 6]); 45 | CachePadded::new([17u64; 7]); 46 | CachePadded::new([17u64; 8]); 47 | } 48 | 49 | #[test] 50 | fn large() { 51 | let a = [17u64; 9]; 52 | let b = CachePadded::new(a); 53 | assert!(mem::size_of_val(&a) <= mem::size_of_val(&b)); 54 | } 55 | 56 | #[test] 57 | fn debug() { 58 | assert_eq!(format!("{:?}", CachePadded::new(17u64)), "CachePadded(17)"); 59 | } 60 | 61 | #[test] 62 | fn drops() { 63 | let count = Cell::new(0); 64 | 65 | struct Foo<'a>(&'a Cell); 66 | 67 | impl<'a> Drop for Foo<'a> { 68 | fn drop(&mut self) { 69 | self.0.set(self.0.get() + 1); 70 | } 71 | } 72 | 73 | let a = CachePadded::new(Foo(&count)); 74 | let b = CachePadded::new(Foo(&count)); 75 | 76 | assert_eq!(count.get(), 0); 77 | drop(a); 78 | assert_eq!(count.get(), 1); 79 | drop(b); 80 | assert_eq!(count.get(), 2); 81 | } 82 | 83 | #[allow(clippy::clone_on_copy)] // This is intentional 84 | #[test] 85 | fn clone() { 86 | let a = CachePadded::new(17); 87 | let b = a.clone(); 88 | assert_eq!(*a, *b); 89 | } 90 | 91 | #[test] 92 | fn runs_custom_clone() { 93 | let count = Cell::new(0); 94 | 95 | struct Foo<'a>(&'a Cell); 96 | 97 | impl<'a> Clone for Foo<'a> { 98 | fn clone(&self) -> Foo<'a> { 99 | self.0.set(self.0.get() + 1); 100 | Foo::<'a>(self.0) 101 | } 102 | } 103 | 104 | let a = CachePadded::new(Foo(&count)); 105 | let _ = a.clone(); 106 | 107 | assert_eq!(count.get(), 1); 108 | } 109 | --------------------------------------------------------------------------------