├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── cargo.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE ├── README.md ├── atomics ├── CHANGELOG.md ├── Cargo.toml ├── README.md └── src │ ├── lib.rs │ ├── macros │ ├── arithmetic.rs │ ├── bitwise.rs │ ├── fetch_compare_store.rs │ ├── float.rs │ ├── float_arithmetic.rs │ ├── float_saturating_arithmetic.rs │ ├── mod.rs │ ├── native.rs │ └── saturating_arithmetic.rs │ ├── traits │ ├── arithmetic.rs │ ├── atomic.rs │ ├── bitwise.rs │ ├── fetch_compare_store.rs │ ├── mod.rs │ └── saturating_arithmetic.rs │ └── types │ ├── bool.rs │ ├── f32.rs │ ├── f64.rs │ ├── i16.rs │ ├── i32.rs │ ├── i64.rs │ ├── i8.rs │ ├── isize.rs │ ├── mod.rs │ ├── u16.rs │ ├── u32.rs │ ├── u64.rs │ ├── u8.rs │ └── usize.rs ├── heatmap ├── Cargo.toml ├── README.md ├── benches │ └── heatmap.rs └── src │ ├── error.rs │ ├── heatmap.rs │ ├── lib.rs │ └── window.rs ├── histogram ├── Cargo.toml ├── README.md ├── benches │ └── bench.rs └── src │ ├── bucket.rs │ ├── error.rs │ ├── histogram.rs │ ├── lib.rs │ └── percentile.rs ├── logger ├── Cargo.toml ├── examples │ ├── demo-multi.rs │ └── demo-single.rs └── src │ ├── format.rs │ ├── lib.rs │ ├── multi.rs │ ├── nop.rs │ ├── outputs.rs │ ├── sampling.rs │ ├── single.rs │ └── traits.rs ├── metrics ├── Cargo.toml ├── derive │ ├── Cargo.toml │ └── src │ │ ├── args.rs │ │ ├── lib.rs │ │ └── metric.rs ├── src │ ├── counter.rs │ ├── dynmetrics.rs │ ├── gauge.rs │ ├── heatmap.rs │ ├── lazy.rs │ └── lib.rs └── tests │ ├── alternate_crate.rs │ ├── described_metrics.rs │ ├── dynmetrics.rs │ ├── heatmap.rs │ ├── metric_macros.rs │ ├── named_metric.rs │ ├── namespaced_metric.rs │ └── unnamed_metric.rs ├── ratelimiter ├── CHANGELOG.md ├── Cargo.toml ├── README.md ├── examples │ ├── blastoff.rs │ └── bursty.rs └── src │ └── lib.rs ├── streamstats ├── Cargo.toml └── src │ └── lib.rs ├── time ├── Cargo.toml ├── benches │ └── benches.rs ├── examples │ └── demo.rs └── src │ ├── datetime.rs │ ├── duration.rs │ ├── instant.rs │ ├── lib.rs │ ├── macros.rs │ ├── units.rs │ └── unix.rs ├── timer ├── CHANGELOG.md ├── Cargo.toml ├── README.md └── src │ └── lib.rs └── waterfall ├── CHANGELOG.md ├── Cargo.toml ├── README.md ├── examples └── simulator.rs └── src ├── lib.rs └── palettes ├── classic.rs ├── ironbow.rs └── mod.rs /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | One line summary of the issue here. 2 | 3 | ### Expected behavior 4 | 5 | As concisely as possible, describe the expected behavior. 6 | 7 | ### Actual behavior 8 | 9 | As concisely as possible, describe the observed behavior. 10 | 11 | ### Steps to reproduce the behavior 12 | 13 | Please list all relevant steps to reproduce the observed behavior. 14 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Problem 2 | 3 | Explain the context and why you're making that change. What is the 4 | problem you're trying to solve? In some cases there is not a problem 5 | and this can be thought of being the motivation for your change. 6 | 7 | Solution 8 | 9 | Describe the modifications you've done. 10 | 11 | Result 12 | 13 | What will change as a result of your pull request? Note that sometimes 14 | this section is unnecessary because it is self-explanatory based on 15 | the solution. 16 | -------------------------------------------------------------------------------- /.github/workflows/cargo.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | pull_request: 4 | branches: 5 | - master 6 | 7 | env: 8 | CARGO_TERM_COLOR: always 9 | RUST_BACKTRACE: full 10 | 11 | jobs: 12 | build: 13 | strategy: 14 | matrix: 15 | os: [ ubuntu-20.04, macos-11 ] 16 | profile: [ release, debug ] 17 | name: build-${{ matrix.os }}-${{ matrix.profile }} 18 | runs-on: ${{ matrix.os }} 19 | steps: 20 | - uses: actions/checkout@v2 21 | - uses: actions-rs/toolchain@v1 22 | with: 23 | toolchain: stable 24 | 25 | - name: Update cargo flags 26 | if: ${{ matrix.profile == 'release' }} 27 | run: echo 'CARGO_FLAGS=--release' >> $GITHUB_ENV 28 | shell: bash 29 | - name: Update cargo flags 30 | if: ${{ matrix.profile == 'debug' }} 31 | run: echo 'CARGO_FLAGS=' >> $GITHUB_ENV 32 | shell: bash 33 | 34 | - uses: Swatinem/rust-cache@v1 35 | with: 36 | key: ${{ matrix.profile }} 37 | - uses: actions-rs/cargo@v1 38 | name: build 39 | with: 40 | command: test 41 | args: ${{ env.CARGO_FLAGS }} --workspace --all-features --tests --lib --bins --examples --no-run 42 | - uses: actions-rs/cargo@v1 43 | name: test 44 | with: 45 | command: test 46 | args: ${{ env.CARGO_FLAGS }} --workspace --all-features --tests --lib --bins --examples 47 | - uses: actions-rs/cargo@v1 48 | if: ${{ matrix.profile == 'debug' }} 49 | name: doctests 50 | with: 51 | command: test 52 | args: ${{ env.CARGO_FLAGS }} --workspace --all-features --doc -- --test-threads 16 53 | 54 | # Fast clippy check to ensure things compile 55 | check: 56 | strategy: 57 | matrix: 58 | os: [ ubuntu-20.04, macos-11 ] 59 | name: check-${{ matrix.os }} 60 | runs-on: ${{ matrix.os }} 61 | steps: 62 | - uses: actions/checkout@v2 63 | - uses: actions-rs/toolchain@v1 64 | with: 65 | toolchain: stable 66 | - uses: Swatinem/rust-cache@v1 67 | - uses: actions-rs/cargo@v1 68 | with: 69 | command: check 70 | args: --release 71 | 72 | rustfmt: 73 | name: rustfmt 74 | runs-on: ubuntu-latest 75 | steps: 76 | - uses: actions/checkout@v2 77 | - uses: actions-rs/toolchain@v1 78 | with: 79 | toolchain: stable 80 | - uses: actions-rs/cargo@v1 81 | with: 82 | command: fmt 83 | args: --all -- --check 84 | 85 | # Note: We could run these using the pull_request_target trigger. I haven't 86 | # done this since I'm not sure if it would be secure. 87 | # 88 | # See this link for more details on this 89 | # https://securitylab.github.com/research/github-actions-preventing-pwn-requests/ 90 | clippy: 91 | name: clippy 92 | runs-on: ubuntu-latest 93 | steps: 94 | - uses: actions/checkout@v2 95 | - uses: actions-rs/clippy-check@v1 96 | with: 97 | token: ${{ secrets.GITHUB_TOKEN }} 98 | 99 | audit: 100 | name: audit 101 | runs-on: ubuntu-latest 102 | steps: 103 | - uses: actions/checkout@v2 104 | - uses: actions-rs/audit-check@v1 105 | with: 106 | token: ${{ secrets.GITHUB_TOKEN }} 107 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | **/target/ 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 8 | Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # Ignore simulated waterfalls 14 | waterfall/*.png 15 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | We feel that a welcoming community is important and we ask that you follow Twitter's 2 | [Open Source Code of Conduct](https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md) 3 | in all interactions with the community. 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to get patches from you! 4 | 5 | ## Getting Started 6 | 7 | You can find [open issues](https://github.com/twitter/rustcommon/issues) to work 8 | on labelled 'help-wanted' or 'easy'. If you have and idea for an improvement or 9 | feature that's not covered by an existing issue, please create one first to get 10 | early feedback on your idea. 11 | 12 | ## Building 13 | 14 | A guide to building can be found in the README 15 | 16 | ## Workflow 17 | 18 | We follow the [GitHub Flow Workflow](https://guides.github.com/introduction/flow/) 19 | 20 | 1. Fork the project 21 | 1. Check out the `master` branch 22 | 1. Create a feature branch 23 | 1. Write code and tests for your change 24 | 1. From your branch, make a pull request against `twitter/rustcommon/master` 25 | 1. Work with repo maintainers to get your change reviewed 26 | 1. Wait for your change to be pulled into `twitter/rustcommon/master` 27 | 1. Delete your feature branch 28 | 29 | ## Testing 30 | 31 | All testing is driven by the standard Rust toolchain using `cargo test` to run 32 | tests locally. In addition, tests will be run automatically in travis-ci for all 33 | pull requests and merges into this repository. 34 | 35 | ## Style 36 | 37 | We use rustfmt to enforce code style. Please be sure to run `cargo fmt` to make 38 | sure your changes adhere to the style. As rustfmt is under constant development, 39 | you may find that it changes style for files you haven't edited. In this case, 40 | open a [new issue](https://github.com/twitter/rustcommon/issues/new). Do not 41 | include formatting changes for unrelated files in your main pull request as it 42 | can make review more time consuming to understand the changes. A separate pull 43 | request to first address any existing style issues will help keep code review 44 | as fast as possible. You can get rustfmt via: `rustup component add rustfmt` 45 | 46 | Additionally, we use clippy as our linting tool. Please be sure to run 47 | `cargo clippy` to make sure your changes pass the linter. As with rustfmt, 48 | clippy is under constant development and new lints are added regularly. If you 49 | find that clippy is catching existing issues unrelated to your changes, open a 50 | [new issue](https://github.com/twitter/rustcommon/issues/new). Keeping these 51 | changes in a separate pull request will help keep review as fast as possible. 52 | 53 | Style and linting checks will be run automatically in travis-ci for all pull 54 | requests and merges into this repository. 55 | 56 | ## Issues 57 | 58 | When creating an issue please try to ahere to the following format: 59 | 60 | module-name: One line summary of the issue (less than 72 characters) 61 | 62 | ### Expected behavior 63 | 64 | As concisely as possible, describe the expected behavior. 65 | 66 | ### Actual behavior 67 | 68 | As concisely as possible, describe the observed behavior. 69 | 70 | ### Steps to reproduce the behavior 71 | 72 | List all relevant steps to reproduce the observed behavior. 73 | 74 | ## Pull Requests 75 | 76 | Comments should be formatted to a width no greater than 80 columns. 77 | 78 | Files should be exempt of trailing spaces. 79 | 80 | We adhere to a specific format for commit messages. Please write your commit 81 | messages along these guidelines. Please keep the line width no greater than 80 82 | columns (You can use `fmt -n -p -w 80` to accomplish this). 83 | 84 | module-name: One line description of your change (less than 72 characters) 85 | 86 | Problem 87 | 88 | Explain the context and why you're making that change. What is the problem 89 | you're trying to solve? In some cases there is not a problem and this can be 90 | thought of being the motivation for your change. 91 | 92 | Solution 93 | 94 | Describe the modifications you've done. 95 | 96 | Result 97 | 98 | What will change as a result of your pull request? Note that sometimes this 99 | section is unnecessary because it is self-explanatory based on the solution. 100 | 101 | Some important notes regarding the summary line: 102 | 103 | * Describe what was done; not the result 104 | * Use the active voice 105 | * Use the present tense 106 | * Capitalize properly 107 | * Do not end in a period — this is a title/subject 108 | * Prefix the subject with its scope 109 | 110 | ## Code Review 111 | 112 | All pull requests will be reviewed on GitHub and changes may be requested prior 113 | to merging your pull request. Once the changes are approved, the pull request 114 | will be squash-merged into a single commit which retains authorship metadata. 115 | 116 | ## Documentation 117 | 118 | We also welcome improvements to the project documentation or to the existing 119 | docs. Please file an [issue](https://github.com/twitter/rustcommon/issues). 120 | 121 | # License 122 | 123 | By contributing your code, you agree to license your contribution under the 124 | terms of the APLv2: https://github.com/twitter/rustcommon/blob/master/LICENSE 125 | 126 | # Code of Conduct 127 | 128 | Read our [Code of Conduct](CODE_OF_CONDUCT.md) for the project. 129 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "atomics", 4 | "heatmap", 5 | "histogram", 6 | "logger", 7 | "metrics", 8 | "metrics/derive", 9 | "ratelimiter", 10 | "streamstats", 11 | "time", 12 | "timer", 13 | "waterfall", 14 | ] 15 | 16 | [profile.bench] 17 | opt-level = 3 18 | debug = true 19 | rpath = false 20 | lto = true 21 | debug-assertions = false 22 | codegen-units = 1 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rustcommon 2 | 3 | rustcommon is a collection of common libraries we use in our Rust projects. This 4 | includes datastructures, logging, metrics, timers, and ratelimiting. 5 | 6 | ## Overview 7 | 8 | rustcommon is a workspace repository which contains several crates (libraries) 9 | which we use in our Rust projects such as rpc-perf and Rezolus. These common 10 | libraries may be useful in other projects, and as such, we are providing them 11 | here for ease of discovery. 12 | 13 | Each crate within this repository contains its own readme and changelog 14 | detailing the purpose and history of the library. 15 | 16 | ## Getting Started 17 | 18 | ### Building 19 | 20 | rustcommon is built with the standard Rust toolchain which can be installed and 21 | managed via [rustup](https://rustup.rs) or by following the directions on the 22 | Rust [website](https://www.rust-lang.org/). 23 | 24 | #### Clone and build rustcommon from source 25 | ```bash 26 | git clone https://github.com/twitter/rustcommon 27 | cd rustcommon 28 | 29 | # run tests 30 | cargo test --all 31 | ``` 32 | 33 | ## Support 34 | 35 | Create a [new issue](https://github.com/twitter/rustcommon/issues/new) on GitHub. 36 | 37 | ## Contributing 38 | 39 | We feel that a welcoming community is important and we ask that you follow 40 | Twitter's [Open Source Code of Conduct] in all interactions with the community. 41 | 42 | ## Authors 43 | 44 | * Brian Martin 45 | 46 | A full list of [contributors] can be found on GitHub. 47 | 48 | Follow [@TwitterOSS](https://twitter.com/twitteross) on Twitter for updates. 49 | 50 | ## License 51 | 52 | Copyright 2019-2020 Twitter, Inc. 53 | 54 | Licensed under the Apache License, Version 2.0: 55 | https://www.apache.org/licenses/LICENSE-2.0 56 | 57 | ## Security Issues? 58 | 59 | Please report sensitive security issues via Twitter's bug-bounty program 60 | (https://hackerone.com/twitter) rather than GitHub. 61 | 62 | [contributors]: https://github.com/twitter/rustcommon/graphs/contributors?type=a 63 | [Open Source Code of Conduct]: https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md 64 | -------------------------------------------------------------------------------- /atomics/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Unreleased 2 | 3 | # 1.0.0 - 2019-12-13 4 | 5 | Initial release. 6 | -------------------------------------------------------------------------------- /atomics/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-atomics" 3 | version = "1.0.2" 4 | authors = ["Brian Martin "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | description = "Atomic primitives unified by traits" 8 | homepage = "https://github.com/twitter/rustcommon/atomics" 9 | repository = "https://github.com/twitter/rustcommon" 10 | 11 | [dependencies] 12 | serde = { version = "1.0.144", optional = true } 13 | 14 | [features] 15 | default = ["serde"] 16 | -------------------------------------------------------------------------------- /atomics/README.md: -------------------------------------------------------------------------------- 1 | # rustcommon-atomics 2 | 3 | Atomic types provided with unifying traits for use in generic programming 4 | 5 | ## Overview 6 | 7 | This crate provides wrappers around the atomics found in the rust core library 8 | with the addition of atomic floating point types. The types exported from this 9 | crate are unified through sets of traits which define operations which may be 10 | performed on the atomic types. This makes it possible to use atomic types with 11 | generic programming. 12 | 13 | ## Getting Started 14 | 15 | ### Building 16 | 17 | rustcommon is built with the standard Rust toolchain which can be installed and 18 | managed via [rustup](https://rustup.rs) or by following the directions on the 19 | Rust [website](https://www.rust-lang.org/). 20 | 21 | #### View library documentation 22 | ```bash 23 | cargo doc --open 24 | ``` 25 | 26 | ## Support 27 | 28 | Create a [new issue](https://github.com/twitter/rustcommon/issues/new) on GitHub. 29 | 30 | ## Contributing 31 | 32 | We feel that a welcoming community is important and we ask that you follow 33 | Twitter's [Open Source Code of Conduct] in all interactions with the community. 34 | 35 | ## Authors 36 | 37 | * Brian Martin 38 | 39 | A full list of [contributors] can be found on GitHub. 40 | 41 | Follow [@TwitterOSS](https://twitter.com/twitteross) on Twitter for updates. 42 | 43 | ## License 44 | 45 | Copyright 2019-2020 Twitter, Inc. 46 | 47 | Licensed under the Apache License, Version 2.0: 48 | https://www.apache.org/licenses/LICENSE-2.0 49 | 50 | ## Security Issues? 51 | 52 | Please report sensitive security issues via Twitter's bug-bounty program 53 | (https://hackerone.com/twitter) rather than GitHub. 54 | 55 | [contributors]: https://github.com/twitter/rustcommon/graphs/contributors?type=a 56 | [Open Source Code of Conduct]: https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md 57 | -------------------------------------------------------------------------------- /atomics/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | //! A collection of atomic types which are unified through traits to allow for 6 | //! use as generic types in other datastructures. Also provides non standard 7 | //! atomic types such as an atomic `Option` type. 8 | 9 | #![deny(clippy::all)] 10 | 11 | #[macro_use] 12 | mod macros; 13 | mod traits; 14 | mod types; 15 | 16 | pub use crate::traits::*; 17 | pub use crate::types::*; 18 | 19 | pub use core::sync::atomic::Ordering; 20 | 21 | #[cfg(test)] 22 | mod tests { 23 | use super::*; 24 | 25 | #[test] 26 | fn usize() { 27 | let x = AtomicUsize::new(0); 28 | assert_eq!(x.load(Ordering::SeqCst), 0_usize); 29 | x.store(42, Ordering::SeqCst); 30 | assert_eq!(x.load(Ordering::SeqCst), 42_usize); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /atomics/src/macros/arithmetic.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | macro_rules! arithmetic { 6 | ($name:ident, $type:ty) => { 7 | impl Arithmetic for $name { 8 | #[inline] 9 | fn fetch_add( 10 | &self, 11 | value: ::Primitive, 12 | ordering: Ordering, 13 | ) -> ::Primitive { 14 | self.inner.fetch_add(value, ordering) 15 | } 16 | 17 | #[inline] 18 | fn fetch_sub( 19 | &self, 20 | value: ::Primitive, 21 | ordering: Ordering, 22 | ) -> ::Primitive { 23 | self.inner.fetch_sub(value, ordering) 24 | } 25 | } 26 | }; 27 | } 28 | -------------------------------------------------------------------------------- /atomics/src/macros/bitwise.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | macro_rules! bitwise { 6 | ($name:ident, $type:ty) => { 7 | impl Bitwise for $name { 8 | #[inline] 9 | fn fetch_and( 10 | &self, 11 | value: ::Primitive, 12 | ordering: Ordering, 13 | ) -> ::Primitive { 14 | self.inner.fetch_and(value, ordering) 15 | } 16 | 17 | #[inline] 18 | fn fetch_nand( 19 | &self, 20 | value: ::Primitive, 21 | ordering: Ordering, 22 | ) -> ::Primitive { 23 | self.inner.fetch_nand(value, ordering) 24 | } 25 | 26 | #[inline] 27 | fn fetch_or( 28 | &self, 29 | value: ::Primitive, 30 | ordering: Ordering, 31 | ) -> ::Primitive { 32 | self.inner.fetch_or(value, ordering) 33 | } 34 | 35 | #[inline] 36 | fn fetch_xor( 37 | &self, 38 | value: ::Primitive, 39 | ordering: Ordering, 40 | ) -> ::Primitive { 41 | self.inner.fetch_xor(value, ordering) 42 | } 43 | } 44 | }; 45 | } 46 | -------------------------------------------------------------------------------- /atomics/src/macros/fetch_compare_store.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | macro_rules! fetch_compare_store { 6 | ($name:ident, $type:ty) => { 7 | impl FetchCompareStore for $name { 8 | fn fetch_max( 9 | &self, 10 | value: ::Primitive, 11 | ordering: Ordering, 12 | ) -> ::Primitive { 13 | self.inner.fetch_max(value, ordering) 14 | } 15 | 16 | fn fetch_min( 17 | &self, 18 | value: ::Primitive, 19 | ordering: Ordering, 20 | ) -> ::Primitive { 21 | self.inner.fetch_min(value, ordering) 22 | } 23 | } 24 | }; 25 | } 26 | -------------------------------------------------------------------------------- /atomics/src/macros/float.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | macro_rules! float { 6 | ( 7 | $(#[$outer:meta])* 8 | pub struct $name:ident: $type:ty = $atomic:ty; 9 | ) => { 10 | $(#[$outer])* 11 | pub struct $name { 12 | inner: $atomic, 13 | } 14 | 15 | impl $name { 16 | #[inline] 17 | pub fn new(value: $type) -> $name { 18 | $name { 19 | inner: <$atomic>::new(value.to_bits()), 20 | } 21 | } 22 | } 23 | 24 | impl Default for $name { 25 | fn default() -> $name { 26 | <$name>::new(<$type>::default()) 27 | } 28 | } 29 | 30 | impl Atomic for $name { 31 | type Primitive = $type; 32 | 33 | 34 | #[inline] 35 | fn load(&self, ordering: Ordering) -> Self::Primitive { 36 | <$type>::from_bits(self.inner.load(ordering)) 37 | } 38 | 39 | #[inline] 40 | fn store(&self, value: Self::Primitive, ordering: Ordering) { 41 | self.inner.store(value.to_bits(), ordering) 42 | } 43 | 44 | #[inline] 45 | fn swap(&self, new: Self::Primitive, ordering: Ordering) -> Self::Primitive { 46 | <$type>::from_bits(self.inner.swap(new.to_bits(), ordering)) 47 | } 48 | 49 | #[inline] 50 | fn compare_exchange( 51 | &self, 52 | current: Self::Primitive, 53 | new: Self::Primitive, 54 | success: Ordering, 55 | failure: Ordering, 56 | ) -> Result { 57 | self.inner 58 | .compare_exchange(current.to_bits(), new.to_bits(), success, failure) 59 | .map(<$type>::from_bits) 60 | .map_err(<$type>::from_bits) 61 | } 62 | 63 | #[inline] 64 | fn compare_exchange_weak( 65 | &self, 66 | current: Self::Primitive, 67 | new: Self::Primitive, 68 | success: Ordering, 69 | failure: Ordering, 70 | ) -> Result { 71 | self.inner 72 | .compare_exchange_weak(current.to_bits(), new.to_bits(), success, failure) 73 | .map(<$type>::from_bits) 74 | .map_err(<$type>::from_bits) 75 | } 76 | } 77 | 78 | impl std::fmt::Debug for $name where $type: std::fmt::Debug { 79 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 80 | write!(f, "{:?}", self.inner) 81 | } 82 | } 83 | }; 84 | } 85 | -------------------------------------------------------------------------------- /atomics/src/macros/float_arithmetic.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | macro_rules! float_arithmetic { 6 | ($name:ident, $type:ty) => { 7 | impl Arithmetic for $name { 8 | #[inline] 9 | fn fetch_add( 10 | &self, 11 | value: ::Primitive, 12 | ordering: Ordering, 13 | ) -> ::Primitive { 14 | let load_ordering = match ordering { 15 | Ordering::AcqRel => Ordering::Acquire, 16 | Ordering::Release => Ordering::Relaxed, 17 | _ => ordering, 18 | }; 19 | let current = self.inner.load(load_ordering); 20 | let mut new = <$type>::from_bits(current) + value; 21 | loop { 22 | let result = self.inner.compare_exchange( 23 | current, 24 | new.to_bits(), 25 | ordering, 26 | load_ordering, 27 | ); 28 | match result { 29 | Ok(v) => { 30 | return <$type>::from_bits(v); 31 | } 32 | Err(v) => { 33 | new = <$type>::from_bits(v) + value; 34 | } 35 | } 36 | } 37 | } 38 | 39 | #[inline] 40 | fn fetch_sub( 41 | &self, 42 | value: ::Primitive, 43 | ordering: Ordering, 44 | ) -> ::Primitive { 45 | let load_ordering = match ordering { 46 | Ordering::AcqRel => Ordering::Acquire, 47 | Ordering::Release => Ordering::Relaxed, 48 | _ => ordering, 49 | }; 50 | let current = self.inner.load(load_ordering); 51 | let mut new = <$type>::from_bits(current) - value; 52 | loop { 53 | let result = self.inner.compare_exchange( 54 | current, 55 | new.to_bits(), 56 | ordering, 57 | load_ordering, 58 | ); 59 | match result { 60 | Ok(v) => { 61 | return <$type>::from_bits(v); 62 | } 63 | Err(v) => { 64 | new = <$type>::from_bits(v) - value; 65 | } 66 | } 67 | } 68 | } 69 | } 70 | }; 71 | } 72 | -------------------------------------------------------------------------------- /atomics/src/macros/float_saturating_arithmetic.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | macro_rules! saturating_arithmetic { 6 | ($name:ident, $type:ty, $core:ident) => { 7 | impl SaturatingArithmetic for $name { 8 | 9 | #[inline] 10 | fn fetch_saturating_add(&self, value: ::Primitive, ordering: Ordering) -> ::Primitive { 11 | let load_ordering = match ordering { 12 | Ordering::AcqRel => Ordering::Acquire, 13 | Ordering::Release => Ordering::Relaxed, 14 | _ => ordering, 15 | }; 16 | let mut previous = self.load(load_ordering); 17 | if previous == <$core>::MAX { 18 | // already at numeric bound, return previous value. 19 | return previous; 20 | } else { 21 | loop { 22 | let sum = previous + value; 23 | let new = if sum == <$core>::INFINITY { 24 | <$core>::MAX 25 | } else { 26 | sum 27 | }; 28 | let result = self.compare_exchange(previous, new, ordering, load_ordering); 29 | match result { 30 | Ok(v) => { 31 | return v; 32 | } 33 | Err(v) => { 34 | previous = v; 35 | if previous == <$type>::max_value() { 36 | // value concurrently updated and now at numeric bound. 37 | // return its new value as the previous value. 38 | return previous; 39 | } 40 | } 41 | } 42 | } 43 | } 44 | } 45 | 46 | #[inline] 47 | fn fetch_saturating_sub(&self, value: ::Primitive, ordering: Ordering) -> ::Primitive { 48 | let load_ordering = match ordering { 49 | Ordering::AcqRel => Ordering::Acquire, 50 | Ordering::Release => Ordering::Relaxed, 51 | _ => ordering, 52 | }; 53 | let mut previous = self.load(load_ordering); 54 | if previous == <$type>::min_value() { 55 | // already at numeric bound, return previous value. 56 | return previous; 57 | } else { 58 | loop { 59 | let diff = previous - value; 60 | let new = if diff == <$core>::NEG_INFINITY { 61 | <$core>::MAX 62 | } else { 63 | diff 64 | }; 65 | let result = self.compare_exchange(previous, new, ordering, load_ordering); 66 | match result { 67 | Ok(v) => { 68 | return v; 69 | } 70 | Err(v) => { 71 | previous = v; 72 | if previous == <$type>::max_value() { 73 | // value concurrently updated and now at numeric bound. 74 | // return its new value as the previous value. 75 | return previous; 76 | } 77 | } 78 | } 79 | } 80 | } 81 | } 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /atomics/src/macros/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | #[macro_use] 6 | mod arithmetic; 7 | 8 | #[macro_use] 9 | mod bitwise; 10 | 11 | #[macro_use] 12 | mod fetch_compare_store; 13 | 14 | #[macro_use] 15 | mod float; 16 | 17 | #[macro_use] 18 | mod float_arithmetic; 19 | 20 | #[macro_use] 21 | mod native; 22 | 23 | #[macro_use] 24 | mod saturating_arithmetic; 25 | -------------------------------------------------------------------------------- /atomics/src/macros/native.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | macro_rules! native { 6 | ( 7 | $(#[$outer:meta])* 8 | pub struct $name:ident: $type:ty = $atomic:ty; 9 | ) => { 10 | $(#[$outer])* 11 | pub struct $name { 12 | inner: $atomic, 13 | } 14 | 15 | impl $name { 16 | #[inline] 17 | pub fn new(value: $type) -> $name { 18 | $name { 19 | inner: <$atomic>::new(value), 20 | } 21 | } 22 | } 23 | 24 | impl Default for $name { 25 | fn default() -> $name { 26 | <$name>::new(<$type>::default()) 27 | } 28 | } 29 | 30 | impl Atomic for $name { 31 | type Primitive = $type; 32 | 33 | 34 | #[inline] 35 | fn load(&self, ordering: Ordering) -> Self::Primitive { 36 | self.inner.load(ordering) 37 | } 38 | 39 | #[inline] 40 | fn store(&self, value: Self::Primitive, ordering: Ordering) { 41 | self.inner.store(value, ordering) 42 | } 43 | 44 | #[inline] 45 | fn swap(&self, new: Self::Primitive, ordering: Ordering) -> Self::Primitive { 46 | self.inner.swap(new, ordering) 47 | } 48 | 49 | #[inline] 50 | fn compare_exchange( 51 | &self, 52 | current: Self::Primitive, 53 | new: Self::Primitive, 54 | success: Ordering, 55 | failure: Ordering, 56 | ) -> Result { 57 | self.inner.compare_exchange(current, new, success, failure) 58 | } 59 | 60 | #[inline] 61 | fn compare_exchange_weak( 62 | &self, 63 | current: Self::Primitive, 64 | new: Self::Primitive, 65 | success: Ordering, 66 | failure: Ordering, 67 | ) -> Result { 68 | self.inner 69 | .compare_exchange_weak(current, new, success, failure) 70 | } 71 | } 72 | 73 | impl std::fmt::Debug for $name where $type: std::fmt::Debug { 74 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 75 | write!(f, "{:?}", self.inner) 76 | } 77 | } 78 | }; 79 | } 80 | -------------------------------------------------------------------------------- /atomics/src/macros/saturating_arithmetic.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | macro_rules! saturating_arithmetic { 6 | ($name:ident, $type:ty) => { 7 | impl SaturatingArithmetic for $name { 8 | #[inline] 9 | fn fetch_saturating_add( 10 | &self, 11 | value: ::Primitive, 12 | ordering: Ordering, 13 | ) -> ::Primitive { 14 | let load_ordering = match ordering { 15 | Ordering::AcqRel => Ordering::Acquire, 16 | Ordering::Release => Ordering::Relaxed, 17 | _ => ordering, 18 | }; 19 | let mut previous = self.load(load_ordering); 20 | if previous == <$type>::max_value() { 21 | // already at numeric bound, return previous value. 22 | return previous; 23 | } else { 24 | loop { 25 | let new = previous.saturating_add(value); 26 | let result = self.compare_exchange(previous, new, ordering, load_ordering); 27 | match result { 28 | Ok(v) => { 29 | return v; 30 | } 31 | Err(v) => { 32 | previous = v; 33 | if previous == <$type>::max_value() { 34 | // value concurrently updated and now at numeric bound. 35 | // return its new value as the previous value. 36 | return previous; 37 | } 38 | } 39 | } 40 | } 41 | } 42 | } 43 | 44 | #[inline] 45 | fn fetch_saturating_sub( 46 | &self, 47 | value: ::Primitive, 48 | ordering: Ordering, 49 | ) -> ::Primitive { 50 | let load_ordering = match ordering { 51 | Ordering::AcqRel => Ordering::Acquire, 52 | Ordering::Release => Ordering::Relaxed, 53 | _ => ordering, 54 | }; 55 | let mut previous = self.load(load_ordering); 56 | if previous == <$type>::min_value() { 57 | // already at numeric bound, return previous value. 58 | return previous; 59 | } else { 60 | loop { 61 | let new = previous.saturating_sub(value); 62 | let result = self.compare_exchange(previous, new, ordering, load_ordering); 63 | match result { 64 | Ok(v) => { 65 | return v; 66 | } 67 | Err(v) => { 68 | previous = v; 69 | if previous == <$type>::max_value() { 70 | // value concurrently updated and now at numeric bound. 71 | // return its new value as the previous value. 72 | return previous; 73 | } 74 | } 75 | } 76 | } 77 | } 78 | } 79 | } 80 | }; 81 | } 82 | -------------------------------------------------------------------------------- /atomics/src/traits/arithmetic.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | /// Arithmetic operations on atomic types 8 | pub trait Arithmetic: Atomic { 9 | /// Adds to the current value, returning the previous value. 10 | /// 11 | /// This operation wraps around on overflow. 12 | /// 13 | /// This operation takes an `Ordering` argument which describes the memory 14 | /// ordering of the operation. All ordering modes are possible. Using 15 | /// `Acquire` makes the store part of the operation `Relaxed`, and using 16 | /// `Release` makes the load part of the operation `Relaxed`. 17 | fn fetch_add( 18 | &self, 19 | value: ::Primitive, 20 | ordering: Ordering, 21 | ) -> ::Primitive; 22 | 23 | /// Subtracts from the current value, returning the previous value. 24 | /// 25 | /// This operation wraps around on overflow. 26 | /// 27 | /// This operation takes an `Ordering` argument which describes the memory 28 | /// ordering of the operation. All ordering modes are possible. Using 29 | /// `Acquire` makes the store part of the operation `Relaxed`, and using 30 | /// `Release` makes the load part of the operation `Relaxed`. 31 | fn fetch_sub( 32 | &self, 33 | value: ::Primitive, 34 | ordering: Ordering, 35 | ) -> ::Primitive; 36 | } 37 | -------------------------------------------------------------------------------- /atomics/src/traits/atomic.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | /// Common operations on atomic types 8 | pub trait Atomic { 9 | type Primitive; 10 | 11 | /// Creates a new atomic type from a primitive type. 12 | // fn new(value: T) -> Self; 13 | 14 | /// Loads the value from the atomic type. 15 | /// 16 | /// `load` takes an `Ordering` argument which describes the memory ordering 17 | /// of this operation. Possible values are `SeqCst`, `Acquire`, and 18 | /// `Relaxed` 19 | fn load(&self, order: Ordering) -> Self::Primitive; 20 | 21 | /// Stores a value into the atomic type. 22 | /// 23 | /// `store` takes an `Ordering` argument which describes the memory ordering 24 | /// of this operation. Possible values are `SeqCst`, `Acquire`, `Release`, 25 | /// and `Relaxed`. 26 | fn store(&self, value: Self::Primitive, order: Ordering); 27 | 28 | /// Stores a value into the atomic type, returning the previous value. 29 | /// `swap` takes an `Ordering` argument which describes the memory ordering 30 | /// of this operation. All ordering modes are possible. Note that using 31 | /// `Acquire` makes the store part of this operation `Relaxed`, and using 32 | /// `Release` makes the load part `Relaxed`. 33 | fn swap(&self, value: Self::Primitive, order: Ordering) -> Self::Primitive; 34 | 35 | /// Stores a value into the atomic type if the current value is the same as 36 | /// as the `current` value. 37 | /// 38 | /// The return value is a result indicating whether the new value was 39 | /// written and containing the previous value. On success this value is 40 | /// guaranteed to be equal to `current`. 41 | /// 42 | /// `compare_exchange` takes two `Ordering` arguments to describe the 43 | /// memory ordering of this operation. The first describes the required 44 | /// ordering if the operation succeeds while the second describes the 45 | /// required ordering when the operation fails. Using `Acquire` as success 46 | /// ordering makes the store part of this operation `Relaxed`, and using 47 | /// `Release` makes the successful load `Relaxed`. The failure ordering 48 | /// can only be `SeqCst`, `Acquire`, or `Relaxed` and must be equivalent 49 | /// to or weaker than the success ordering. 50 | fn compare_exchange( 51 | &self, 52 | current: Self::Primitive, 53 | new: Self::Primitive, 54 | success: Ordering, 55 | failure: Ordering, 56 | ) -> Result; 57 | 58 | /// Stores a value into the atomic type if the current value is the same as 59 | /// as the `current` value. 60 | /// 61 | /// Unlike `compare_exchange`, this function is allowed to spuriously fail 62 | /// even when the comparison succeeds, which can result in more efficient 63 | /// code on some platforms. The return value is a result indicating whether 64 | /// the new value was written and containing the previous value. 65 | /// 66 | /// `compare_exchange_weak` takes two `Ordering` arguments to describe the 67 | /// memory ordering of this operation. The first describes the required 68 | /// ordering if the operation succeeds while the second describes the 69 | /// required ordering when the operation fails. Using `Acquire` as success 70 | /// ordering makes the store part of this operation `Relaxed`, and using 71 | /// `Release` makes the successful load `Relaxed`. The failure ordering 72 | /// can only be `SeqCst`, `Acquire`, or `Relaxed` and must be equivalent 73 | /// to or weaker than the success ordering. 74 | fn compare_exchange_weak( 75 | &self, 76 | current: Self::Primitive, 77 | new: Self::Primitive, 78 | success: Ordering, 79 | failure: Ordering, 80 | ) -> Result; 81 | } 82 | -------------------------------------------------------------------------------- /atomics/src/traits/bitwise.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | /// Bitwise operations on atomic types 8 | pub trait Bitwise: Atomic { 9 | /// Bitwise "and" with the current value, returning the previous value. 10 | /// 11 | /// This operation takes an `Ordering` argument which describes the memory 12 | /// ordering of the operation. All ordering modes are possible. Using 13 | /// `Acquire` makes the store part of the operation `Relaxed`, and using 14 | /// `Release` makes the load part of the operation `Relaxed`. 15 | fn fetch_and( 16 | &self, 17 | value: ::Primitive, 18 | ordering: Ordering, 19 | ) -> ::Primitive; 20 | 21 | /// Bitwise "nand" with the current value, returning the previous value. 22 | /// 23 | /// This operation takes an `Ordering` argument which describes the memory 24 | /// ordering of the operation. All ordering modes are possible. Using 25 | /// `Acquire` makes the store part of the operation `Relaxed`, and using 26 | /// `Release` makes the load part of the operation `Relaxed`. 27 | fn fetch_nand( 28 | &self, 29 | value: ::Primitive, 30 | ordering: Ordering, 31 | ) -> ::Primitive; 32 | 33 | /// Bitwise "or" with the current value, returning the previous value. 34 | /// 35 | /// This operation takes an `Ordering` argument which describes the memory 36 | /// ordering of the operation. All ordering modes are possible. Using 37 | /// `Acquire` makes the store part of the operation `Relaxed`, and using 38 | /// `Release` makes the load part of the operation `Relaxed`. 39 | fn fetch_or( 40 | &self, 41 | value: ::Primitive, 42 | ordering: Ordering, 43 | ) -> ::Primitive; 44 | 45 | /// Bitwise "xor" with the current value, returning the previous value. 46 | /// 47 | /// This operation takes an `Ordering` argument which describes the memory 48 | /// ordering of the operation. All ordering modes are possible. Using 49 | /// `Acquire` makes the store part of the operation `Relaxed`, and using 50 | /// `Release` makes the load part of the operation `Relaxed`. 51 | fn fetch_xor( 52 | &self, 53 | value: ::Primitive, 54 | ordering: Ordering, 55 | ) -> ::Primitive; 56 | } 57 | -------------------------------------------------------------------------------- /atomics/src/traits/fetch_compare_store.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | /// Operations that fetch, compare, and store 8 | pub trait FetchCompareStore: Atomic { 9 | /// Stores the value if it is greater than the current value. 10 | /// 11 | /// The return value is the previous value. 12 | /// 13 | /// This operation takes an `Ordering` argument which describes the memory 14 | /// ordering of the operation. All ordering modes are possible. When using 15 | /// `AcqRel`, the operation might fail and just perform an `Acquire` load, 16 | /// but not have `Release` semantics. Using `Acquire` makes the store part 17 | /// `Relaxed` if it happens, and using `Release` makes the load part 18 | /// `Relaxed`. 19 | fn fetch_max( 20 | &self, 21 | value: ::Primitive, 22 | ordering: Ordering, 23 | ) -> ::Primitive; 24 | 25 | /// Stores the value if it is less than the current value. 26 | /// 27 | /// The return value is the previous value. 28 | /// 29 | /// This operation takes an `Ordering` argument which describes the memory 30 | /// ordering of the operation. All ordering modes are possible. When using 31 | /// `AcqRel`, the operation might fail and just perform an `Acquire` load, 32 | /// but not have `Release` semantics. Using `Acquire` makes the store part 33 | /// `Relaxed` if it happens, and using `Release` makes the load part 34 | /// `Relaxed`. 35 | fn fetch_min( 36 | &self, 37 | value: ::Primitive, 38 | ordering: Ordering, 39 | ) -> ::Primitive; 40 | } 41 | -------------------------------------------------------------------------------- /atomics/src/traits/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | mod arithmetic; 6 | pub use arithmetic::*; 7 | 8 | mod atomic; 9 | pub use atomic::*; 10 | 11 | mod bitwise; 12 | pub use bitwise::*; 13 | 14 | mod fetch_compare_store; 15 | pub use fetch_compare_store::*; 16 | 17 | mod saturating_arithmetic; 18 | pub use saturating_arithmetic::*; 19 | 20 | // marker traits 21 | 22 | /// Values are signed 23 | pub trait Signed {} 24 | 25 | /// Values are unsigned 26 | pub trait Unsigned {} 27 | -------------------------------------------------------------------------------- /atomics/src/traits/saturating_arithmetic.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | /// Saturating arithmetic on atomic types 8 | pub trait SaturatingArithmetic: Atomic { 9 | /// Adds to the current value, returning the previous value. 10 | /// 11 | /// This operation saturates at the numeric bound. 12 | /// 13 | /// This operation takes an `Ordering` argument which describes the memory 14 | /// ordering of the operation. All ordering modes are possible. When using 15 | /// `AcqRel`, the operation might fail and just perform an `Acquire` load, 16 | /// but not have `Release` semantics. Using `Acquire` makes the store part 17 | /// `Relaxed` if it happens, and using `Release` makes the load part 18 | /// `Relaxed`. 19 | fn fetch_saturating_add( 20 | &self, 21 | value: ::Primitive, 22 | ordering: Ordering, 23 | ) -> ::Primitive; 24 | 25 | /// Subtracts from the current value, returning the previous value. 26 | /// 27 | /// This operation saturates at the numeric bound. 28 | /// 29 | /// This operation takes an `Ordering` argument which describes the memory 30 | /// ordering of the operation. All ordering modes are possible. When using 31 | /// `AcqRel`, the operation might fail and just perform an `Acquire` load, 32 | /// but not have `Release` semantics. Using `Acquire` makes the store part 33 | /// `Relaxed` if it happens, and using `Release` makes the load part 34 | /// `Relaxed`. 35 | fn fetch_saturating_sub( 36 | &self, 37 | value: ::Primitive, 38 | ordering: Ordering, 39 | ) -> ::Primitive; 40 | } 41 | -------------------------------------------------------------------------------- /atomics/src/types/bool.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// A boolean type which can be shared between threads 12 | pub struct AtomicBool: bool = core::sync::atomic::AtomicBool; 13 | ); 14 | 15 | // additional traits 16 | bitwise!(AtomicBool, bool); 17 | 18 | #[cfg(feature = "serde")] 19 | struct AtomicBoolVisitor; 20 | 21 | #[cfg(feature = "serde")] 22 | impl<'de> Visitor<'de> for AtomicBoolVisitor { 23 | type Value = AtomicBool; 24 | 25 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 26 | formatter.write_str("a boolean value") 27 | } 28 | 29 | fn visit_bool(self, value: bool) -> Result 30 | where 31 | E: serde::de::Error, 32 | { 33 | Ok(AtomicBool::new(value)) 34 | } 35 | } 36 | 37 | #[cfg(feature = "serde")] 38 | impl<'de> Deserialize<'de> for AtomicBool { 39 | fn deserialize(deserializer: D) -> Result 40 | where 41 | D: Deserializer<'de>, 42 | { 43 | deserializer.deserialize_bool(AtomicBoolVisitor) 44 | } 45 | } 46 | 47 | #[cfg(feature = "serde")] 48 | impl Serialize for AtomicBool { 49 | #[inline] 50 | fn serialize(&self, serializer: S) -> Result 51 | where 52 | S: Serializer, 53 | { 54 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /atomics/src/types/f32.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | float!( 11 | /// A 32 bit floating point number which can be shared between threads 12 | pub struct AtomicF32: f32 = core::sync::atomic::AtomicU32; 13 | ); 14 | 15 | // additional traits 16 | float_arithmetic!(AtomicF32, f32); 17 | 18 | #[cfg(feature = "serde")] 19 | struct AtomicF32Visitor; 20 | 21 | #[cfg(feature = "serde")] 22 | impl<'de> Visitor<'de> for AtomicF32Visitor { 23 | type Value = AtomicF32; 24 | 25 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 26 | formatter.write_str("a 32bit floating point number") 27 | } 28 | 29 | fn visit_i8(self, value: i8) -> Result 30 | where 31 | E: serde::de::Error, 32 | { 33 | Ok(Self::Value::new(f32::from(value))) 34 | } 35 | 36 | fn visit_i16(self, value: i16) -> Result 37 | where 38 | E: serde::de::Error, 39 | { 40 | Ok(Self::Value::new(f32::from(value))) 41 | } 42 | 43 | fn visit_i32(self, value: i32) -> Result 44 | where 45 | E: serde::de::Error, 46 | { 47 | if let Ok(value) = i16::try_from(value).map(f32::from) { 48 | Ok(Self::Value::new(value)) 49 | } else { 50 | Err(E::custom(format!("f32 is out of range: {}", value))) 51 | } 52 | } 53 | 54 | fn visit_i64(self, value: i64) -> Result 55 | where 56 | E: serde::de::Error, 57 | { 58 | if let Ok(value) = i16::try_from(value).map(f32::from) { 59 | Ok(Self::Value::new(value)) 60 | } else { 61 | Err(E::custom(format!("f32 is out of range: {}", value))) 62 | } 63 | } 64 | 65 | fn visit_u8(self, value: u8) -> Result 66 | where 67 | E: serde::de::Error, 68 | { 69 | Ok(Self::Value::new(f32::from(value))) 70 | } 71 | 72 | fn visit_u16(self, value: u16) -> Result 73 | where 74 | E: serde::de::Error, 75 | { 76 | Ok(Self::Value::new(f32::from(value))) 77 | } 78 | 79 | fn visit_u32(self, value: u32) -> Result 80 | where 81 | E: serde::de::Error, 82 | { 83 | if let Ok(value) = u16::try_from(value).map(f32::from) { 84 | Ok(Self::Value::new(value)) 85 | } else { 86 | Err(E::custom(format!("f32 is out of range: {}", value))) 87 | } 88 | } 89 | 90 | fn visit_u64(self, value: u64) -> Result 91 | where 92 | E: serde::de::Error, 93 | { 94 | if let Ok(value) = u16::try_from(value).map(f32::from) { 95 | Ok(Self::Value::new(value)) 96 | } else { 97 | Err(E::custom(format!("f32 is out of range: {}", value))) 98 | } 99 | } 100 | 101 | fn visit_f32(self, value: f32) -> Result 102 | where 103 | E: serde::de::Error, 104 | { 105 | Ok(Self::Value::new(value)) 106 | } 107 | 108 | fn visit_f64(self, value: f64) -> Result 109 | where 110 | E: serde::de::Error, 111 | { 112 | if value >= f64::from(std::f32::MIN) && value <= f64::from(std::f32::MAX) { 113 | Ok(Self::Value::new(value as f32)) 114 | } else { 115 | Err(E::custom(format!("f32 is out of range: {}", value))) 116 | } 117 | } 118 | } 119 | 120 | #[cfg(feature = "serde")] 121 | impl<'de> Deserialize<'de> for AtomicF32 { 122 | fn deserialize(deserializer: D) -> Result 123 | where 124 | D: Deserializer<'de>, 125 | { 126 | deserializer.deserialize_any(AtomicF32Visitor) 127 | } 128 | } 129 | 130 | #[cfg(feature = "serde")] 131 | impl Serialize for AtomicF32 { 132 | #[inline] 133 | fn serialize(&self, serializer: S) -> Result 134 | where 135 | S: Serializer, 136 | { 137 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 138 | } 139 | } 140 | 141 | #[cfg(test)] 142 | mod tests { 143 | use super::*; 144 | 145 | #[test] 146 | fn load() { 147 | let atomic = AtomicF32::new(0.0); 148 | assert_eq!(atomic.load(Ordering::SeqCst), 0.0); 149 | } 150 | 151 | #[test] 152 | fn store() { 153 | let atomic = AtomicF32::new(0.0); 154 | atomic.store(std::f32::consts::PI, Ordering::SeqCst); 155 | assert_eq!(atomic.load(Ordering::SeqCst), std::f32::consts::PI); 156 | } 157 | 158 | #[test] 159 | fn swap() { 160 | let atomic = AtomicF32::new(0.0); 161 | assert_eq!(atomic.swap(std::f32::consts::PI, Ordering::SeqCst), 0.0); 162 | } 163 | 164 | #[test] 165 | fn compare_exchange() { 166 | let atomic = AtomicF32::new(0.0); 167 | assert_eq!( 168 | atomic.compare_exchange( 169 | 0.0, 170 | std::f32::consts::PI, 171 | Ordering::SeqCst, 172 | Ordering::SeqCst 173 | ), 174 | Ok(0.0) 175 | ); 176 | assert_eq!( 177 | atomic.compare_exchange(0.0, 42.0, Ordering::SeqCst, Ordering::SeqCst), 178 | Err(std::f32::consts::PI) 179 | ); 180 | } 181 | 182 | #[test] 183 | fn compare_exchange_weak() { 184 | let atomic = AtomicF32::new(0.0); 185 | loop { 186 | if atomic 187 | .compare_exchange( 188 | 0.0, 189 | std::f32::consts::PI, 190 | Ordering::SeqCst, 191 | Ordering::SeqCst, 192 | ) 193 | .is_ok() 194 | { 195 | break; 196 | } 197 | } 198 | assert_eq!(atomic.load(Ordering::SeqCst), std::f32::consts::PI); 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /atomics/src/types/f64.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | float!( 11 | /// A 64 bit floating point number which can be shared between threads 12 | pub struct AtomicF64: f64 = core::sync::atomic::AtomicU64; 13 | ); 14 | 15 | // additional traits 16 | float_arithmetic!(AtomicF64, f64); 17 | 18 | #[cfg(feature = "serde")] 19 | struct AtomicF64Visitor; 20 | 21 | #[cfg(feature = "serde")] 22 | impl<'de> Visitor<'de> for AtomicF64Visitor { 23 | type Value = AtomicF64; 24 | 25 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 26 | formatter.write_str("a 64bit floating point number") 27 | } 28 | 29 | fn visit_i8(self, value: i8) -> Result 30 | where 31 | E: serde::de::Error, 32 | { 33 | Ok(Self::Value::new(f64::from(value))) 34 | } 35 | 36 | fn visit_i16(self, value: i16) -> Result 37 | where 38 | E: serde::de::Error, 39 | { 40 | Ok(Self::Value::new(f64::from(value))) 41 | } 42 | 43 | fn visit_i32(self, value: i32) -> Result 44 | where 45 | E: serde::de::Error, 46 | { 47 | Ok(Self::Value::new(f64::from(value))) 48 | } 49 | 50 | fn visit_i64(self, value: i64) -> Result 51 | where 52 | E: serde::de::Error, 53 | { 54 | if let Ok(value) = i32::try_from(value).map(f64::from) { 55 | Ok(Self::Value::new(value)) 56 | } else { 57 | Err(E::custom(format!("f64 is out of range: {}", value))) 58 | } 59 | } 60 | 61 | fn visit_u8(self, value: u8) -> Result 62 | where 63 | E: serde::de::Error, 64 | { 65 | Ok(Self::Value::new(f64::from(value))) 66 | } 67 | 68 | fn visit_u16(self, value: u16) -> Result 69 | where 70 | E: serde::de::Error, 71 | { 72 | Ok(Self::Value::new(f64::from(value))) 73 | } 74 | 75 | fn visit_u32(self, value: u32) -> Result 76 | where 77 | E: serde::de::Error, 78 | { 79 | Ok(Self::Value::new(f64::from(value))) 80 | } 81 | 82 | fn visit_u64(self, value: u64) -> Result 83 | where 84 | E: serde::de::Error, 85 | { 86 | if let Ok(value) = u32::try_from(value).map(f64::from) { 87 | Ok(Self::Value::new(value)) 88 | } else { 89 | Err(E::custom(format!("f64 is out of range: {}", value))) 90 | } 91 | } 92 | 93 | fn visit_f32(self, value: f32) -> Result 94 | where 95 | E: serde::de::Error, 96 | { 97 | Ok(Self::Value::new(f64::from(value))) 98 | } 99 | 100 | fn visit_f64(self, value: f64) -> Result 101 | where 102 | E: serde::de::Error, 103 | { 104 | Ok(Self::Value::new(value)) 105 | } 106 | } 107 | 108 | #[cfg(feature = "serde")] 109 | impl<'de> Deserialize<'de> for AtomicF64 { 110 | fn deserialize(deserializer: D) -> Result 111 | where 112 | D: Deserializer<'de>, 113 | { 114 | deserializer.deserialize_any(AtomicF64Visitor) 115 | } 116 | } 117 | 118 | #[cfg(feature = "serde")] 119 | impl Serialize for AtomicF64 { 120 | #[inline] 121 | fn serialize(&self, serializer: S) -> Result 122 | where 123 | S: Serializer, 124 | { 125 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 126 | } 127 | } 128 | 129 | #[cfg(test)] 130 | mod tests { 131 | use super::*; 132 | 133 | #[test] 134 | fn load() { 135 | let atomic = AtomicF64::new(0.0); 136 | assert_eq!(atomic.load(Ordering::SeqCst), 0.0); 137 | } 138 | 139 | #[test] 140 | fn store() { 141 | let atomic = AtomicF64::new(0.0); 142 | atomic.store(std::f64::consts::PI, Ordering::SeqCst); 143 | assert_eq!(atomic.load(Ordering::SeqCst), std::f64::consts::PI); 144 | } 145 | 146 | #[test] 147 | fn swap() { 148 | let atomic = AtomicF64::new(0.0); 149 | assert_eq!(atomic.swap(std::f64::consts::PI, Ordering::SeqCst), 0.0); 150 | } 151 | 152 | #[test] 153 | fn compare_exchange() { 154 | let atomic = AtomicF64::new(0.0); 155 | assert_eq!( 156 | atomic.compare_exchange( 157 | 0.0, 158 | std::f64::consts::PI, 159 | Ordering::SeqCst, 160 | Ordering::SeqCst 161 | ), 162 | Ok(0.0) 163 | ); 164 | assert_eq!( 165 | atomic.compare_exchange(0.0, 42.0, Ordering::SeqCst, Ordering::SeqCst), 166 | Err(std::f64::consts::PI) 167 | ); 168 | } 169 | 170 | #[test] 171 | fn compare_exchange_weak() { 172 | let atomic = AtomicF64::new(0.0); 173 | loop { 174 | if atomic 175 | .compare_exchange( 176 | 0.0, 177 | std::f64::consts::PI, 178 | Ordering::SeqCst, 179 | Ordering::SeqCst, 180 | ) 181 | .is_ok() 182 | { 183 | break; 184 | } 185 | } 186 | assert_eq!(atomic.load(Ordering::SeqCst), std::f64::consts::PI); 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /atomics/src/types/i16.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// A signed 16 bit integer which can be shared between threads 12 | pub struct AtomicI16: i16 = core::sync::atomic::AtomicI16; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicI16, i16); 17 | bitwise!(AtomicI16, i16); 18 | fetch_compare_store!(AtomicI16, i16); 19 | saturating_arithmetic!(AtomicI16, i16); 20 | 21 | impl Signed for AtomicI16 {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicI16Visitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicI16Visitor { 28 | type Value = AtomicI16; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("a signed 16bit integer") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | Ok(Self::Value::new(i16::from(value))) 39 | } 40 | 41 | fn visit_i16(self, value: i16) -> Result 42 | where 43 | E: serde::de::Error, 44 | { 45 | Ok(Self::Value::new(value)) 46 | } 47 | 48 | fn visit_i32(self, value: i32) -> Result 49 | where 50 | E: serde::de::Error, 51 | { 52 | if let Ok(value) = i16::try_from(value) { 53 | Ok(Self::Value::new(value)) 54 | } else { 55 | Err(E::custom(format!("i16 is out of range: {}", value))) 56 | } 57 | } 58 | 59 | fn visit_i64(self, value: i64) -> Result 60 | where 61 | E: serde::de::Error, 62 | { 63 | if let Ok(value) = i16::try_from(value) { 64 | Ok(Self::Value::new(value)) 65 | } else { 66 | Err(E::custom(format!("i16 is out of range: {}", value))) 67 | } 68 | } 69 | 70 | fn visit_u8(self, value: u8) -> Result 71 | where 72 | E: serde::de::Error, 73 | { 74 | Ok(Self::Value::new(i16::from(value))) 75 | } 76 | 77 | fn visit_u16(self, value: u16) -> Result 78 | where 79 | E: serde::de::Error, 80 | { 81 | if let Ok(value) = i16::try_from(value) { 82 | Ok(Self::Value::new(value)) 83 | } else { 84 | Err(E::custom(format!("i16 is out of range: {}", value))) 85 | } 86 | } 87 | 88 | fn visit_u32(self, value: u32) -> Result 89 | where 90 | E: serde::de::Error, 91 | { 92 | if let Ok(value) = i16::try_from(value) { 93 | Ok(Self::Value::new(value)) 94 | } else { 95 | Err(E::custom(format!("i16 is out of range: {}", value))) 96 | } 97 | } 98 | 99 | fn visit_u64(self, value: u64) -> Result 100 | where 101 | E: serde::de::Error, 102 | { 103 | if let Ok(value) = i16::try_from(value) { 104 | Ok(Self::Value::new(value)) 105 | } else { 106 | Err(E::custom(format!("i16 is out of range: {}", value))) 107 | } 108 | } 109 | } 110 | 111 | #[cfg(feature = "serde")] 112 | impl<'de> Deserialize<'de> for AtomicI16 { 113 | fn deserialize(deserializer: D) -> Result 114 | where 115 | D: Deserializer<'de>, 116 | { 117 | deserializer.deserialize_i16(AtomicI16Visitor) 118 | } 119 | } 120 | 121 | #[cfg(feature = "serde")] 122 | impl Serialize for AtomicI16 { 123 | #[inline] 124 | fn serialize(&self, serializer: S) -> Result 125 | where 126 | S: Serializer, 127 | { 128 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 129 | } 130 | } 131 | 132 | #[cfg(test)] 133 | mod tests { 134 | use super::*; 135 | 136 | #[test] 137 | fn load() { 138 | let atomic = AtomicI16::new(0); 139 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 140 | } 141 | 142 | #[test] 143 | fn store() { 144 | let atomic = AtomicI16::new(0); 145 | atomic.store(1, Ordering::SeqCst); 146 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 147 | } 148 | 149 | #[test] 150 | fn swap() { 151 | let atomic = AtomicI16::new(0); 152 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 153 | } 154 | 155 | #[test] 156 | fn compare_exchange() { 157 | let atomic = AtomicI16::new(0); 158 | assert_eq!( 159 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 160 | Ok(0) 161 | ); 162 | assert_eq!( 163 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 164 | Err(1) 165 | ); 166 | } 167 | 168 | #[test] 169 | fn compare_exchange_weak() { 170 | let atomic = AtomicI16::new(0); 171 | loop { 172 | if atomic 173 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 174 | .is_ok() 175 | { 176 | break; 177 | } 178 | } 179 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /atomics/src/types/i32.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// A signed 32 bit integer which can be shared between threads 12 | pub struct AtomicI32: i32 = core::sync::atomic::AtomicI32; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicI32, i32); 17 | bitwise!(AtomicI32, i32); 18 | fetch_compare_store!(AtomicI32, i32); 19 | saturating_arithmetic!(AtomicI32, i32); 20 | 21 | impl Signed for AtomicI32 {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicI32Visitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicI32Visitor { 28 | type Value = AtomicI32; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("a signed 32bit integer") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | Ok(Self::Value::new(i32::from(value))) 39 | } 40 | 41 | fn visit_i16(self, value: i16) -> Result 42 | where 43 | E: serde::de::Error, 44 | { 45 | Ok(Self::Value::new(i32::from(value))) 46 | } 47 | 48 | fn visit_i32(self, value: i32) -> Result 49 | where 50 | E: serde::de::Error, 51 | { 52 | Ok(Self::Value::new(value)) 53 | } 54 | 55 | fn visit_i64(self, value: i64) -> Result 56 | where 57 | E: serde::de::Error, 58 | { 59 | if let Ok(value) = i32::try_from(value) { 60 | Ok(Self::Value::new(value)) 61 | } else { 62 | Err(E::custom(format!("i32 is out of range: {}", value))) 63 | } 64 | } 65 | 66 | fn visit_u8(self, value: u8) -> Result 67 | where 68 | E: serde::de::Error, 69 | { 70 | Ok(Self::Value::new(i32::from(value))) 71 | } 72 | 73 | fn visit_u16(self, value: u16) -> Result 74 | where 75 | E: serde::de::Error, 76 | { 77 | Ok(Self::Value::new(i32::from(value))) 78 | } 79 | 80 | fn visit_u32(self, value: u32) -> Result 81 | where 82 | E: serde::de::Error, 83 | { 84 | if let Ok(value) = i32::try_from(value) { 85 | Ok(Self::Value::new(value)) 86 | } else { 87 | Err(E::custom(format!("i32 is out of range: {}", value))) 88 | } 89 | } 90 | 91 | fn visit_u64(self, value: u64) -> Result 92 | where 93 | E: serde::de::Error, 94 | { 95 | if let Ok(value) = i32::try_from(value) { 96 | Ok(Self::Value::new(value)) 97 | } else { 98 | Err(E::custom(format!("i32 is out of range: {}", value))) 99 | } 100 | } 101 | } 102 | 103 | #[cfg(feature = "serde")] 104 | impl<'de> Deserialize<'de> for AtomicI32 { 105 | fn deserialize(deserializer: D) -> Result 106 | where 107 | D: Deserializer<'de>, 108 | { 109 | deserializer.deserialize_i32(AtomicI32Visitor) 110 | } 111 | } 112 | 113 | #[cfg(feature = "serde")] 114 | impl Serialize for AtomicI32 { 115 | #[inline] 116 | fn serialize(&self, serializer: S) -> Result 117 | where 118 | S: Serializer, 119 | { 120 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 121 | } 122 | } 123 | 124 | #[cfg(test)] 125 | mod tests { 126 | use super::*; 127 | 128 | #[test] 129 | fn load() { 130 | let atomic = AtomicI32::new(0); 131 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 132 | } 133 | 134 | #[test] 135 | fn store() { 136 | let atomic = AtomicI32::new(0); 137 | atomic.store(1, Ordering::SeqCst); 138 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 139 | } 140 | 141 | #[test] 142 | fn swap() { 143 | let atomic = AtomicI32::new(0); 144 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 145 | } 146 | 147 | #[test] 148 | fn compare_exchange() { 149 | let atomic = AtomicI32::new(0); 150 | assert_eq!( 151 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 152 | Ok(0) 153 | ); 154 | assert_eq!( 155 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 156 | Err(1) 157 | ); 158 | } 159 | 160 | #[test] 161 | fn compare_exchange_weak() { 162 | let atomic = AtomicI32::new(0); 163 | loop { 164 | if atomic 165 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 166 | .is_ok() 167 | { 168 | break; 169 | } 170 | } 171 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /atomics/src/types/i64.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// A signed 64 bit integer which can be shared between threads 12 | pub struct AtomicI64: i64 = core::sync::atomic::AtomicI64; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicI64, i64); 17 | bitwise!(AtomicI64, i64); 18 | fetch_compare_store!(AtomicI64, i64); 19 | saturating_arithmetic!(AtomicI64, i64); 20 | 21 | impl Signed for AtomicI64 {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicI64Visitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicI64Visitor { 28 | type Value = AtomicI64; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("a signed 64bit integer") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | Ok(Self::Value::new(i64::from(value))) 39 | } 40 | 41 | fn visit_i16(self, value: i16) -> Result 42 | where 43 | E: serde::de::Error, 44 | { 45 | Ok(Self::Value::new(i64::from(value))) 46 | } 47 | 48 | fn visit_i32(self, value: i32) -> Result 49 | where 50 | E: serde::de::Error, 51 | { 52 | Ok(Self::Value::new(i64::from(value))) 53 | } 54 | 55 | fn visit_i64(self, value: i64) -> Result 56 | where 57 | E: serde::de::Error, 58 | { 59 | Ok(Self::Value::new(value)) 60 | } 61 | 62 | fn visit_u8(self, value: u8) -> Result 63 | where 64 | E: serde::de::Error, 65 | { 66 | Ok(Self::Value::new(i64::from(value))) 67 | } 68 | 69 | fn visit_u16(self, value: u16) -> Result 70 | where 71 | E: serde::de::Error, 72 | { 73 | Ok(Self::Value::new(i64::from(value))) 74 | } 75 | 76 | fn visit_u32(self, value: u32) -> Result 77 | where 78 | E: serde::de::Error, 79 | { 80 | Ok(Self::Value::new(i64::from(value))) 81 | } 82 | 83 | fn visit_u64(self, value: u64) -> Result 84 | where 85 | E: serde::de::Error, 86 | { 87 | if let Ok(value) = i64::try_from(value) { 88 | Ok(Self::Value::new(value)) 89 | } else { 90 | Err(E::custom(format!("i64 is out of range: {}", value))) 91 | } 92 | } 93 | } 94 | 95 | #[cfg(feature = "serde")] 96 | impl<'de> Deserialize<'de> for AtomicI64 { 97 | fn deserialize(deserializer: D) -> Result 98 | where 99 | D: Deserializer<'de>, 100 | { 101 | deserializer.deserialize_i64(AtomicI64Visitor) 102 | } 103 | } 104 | 105 | #[cfg(feature = "serde")] 106 | impl Serialize for AtomicI64 { 107 | #[inline] 108 | fn serialize(&self, serializer: S) -> Result 109 | where 110 | S: Serializer, 111 | { 112 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 113 | } 114 | } 115 | 116 | #[cfg(test)] 117 | mod tests { 118 | use super::*; 119 | 120 | #[test] 121 | fn load() { 122 | let atomic = AtomicI64::new(0); 123 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 124 | } 125 | 126 | #[test] 127 | fn store() { 128 | let atomic = AtomicI64::new(0); 129 | atomic.store(1, Ordering::SeqCst); 130 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 131 | } 132 | 133 | #[test] 134 | fn swap() { 135 | let atomic = AtomicI64::new(0); 136 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 137 | } 138 | 139 | #[test] 140 | fn compare_exchange() { 141 | let atomic = AtomicI64::new(0); 142 | assert_eq!( 143 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 144 | Ok(0) 145 | ); 146 | assert_eq!( 147 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 148 | Err(1) 149 | ); 150 | } 151 | 152 | #[test] 153 | fn compare_exchange_weak() { 154 | let atomic = AtomicI64::new(0); 155 | loop { 156 | if atomic 157 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 158 | .is_ok() 159 | { 160 | break; 161 | } 162 | } 163 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /atomics/src/types/i8.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// A signed 8 bit integer which can be shared between threads 12 | pub struct AtomicI8: i8 = core::sync::atomic::AtomicI8; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicI8, i8); 17 | bitwise!(AtomicI8, i8); 18 | fetch_compare_store!(AtomicI8, i8); 19 | saturating_arithmetic!(AtomicI8, i8); 20 | 21 | impl Signed for AtomicI8 {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicI8Visitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicI8Visitor { 28 | type Value = AtomicI8; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("a signed 8bit integer") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | Ok(Self::Value::new(value)) 39 | } 40 | 41 | fn visit_i16(self, value: i16) -> Result 42 | where 43 | E: serde::de::Error, 44 | { 45 | if let Ok(value) = i8::try_from(value) { 46 | Ok(Self::Value::new(value)) 47 | } else { 48 | Err(E::custom(format!("i8 is out of range: {}", value))) 49 | } 50 | } 51 | 52 | fn visit_i32(self, value: i32) -> Result 53 | where 54 | E: serde::de::Error, 55 | { 56 | if let Ok(value) = i8::try_from(value) { 57 | Ok(Self::Value::new(value)) 58 | } else { 59 | Err(E::custom(format!("i8 is out of range: {}", value))) 60 | } 61 | } 62 | 63 | fn visit_i64(self, value: i64) -> Result 64 | where 65 | E: serde::de::Error, 66 | { 67 | if let Ok(value) = i8::try_from(value) { 68 | Ok(Self::Value::new(value)) 69 | } else { 70 | Err(E::custom(format!("i8 is out of range: {}", value))) 71 | } 72 | } 73 | 74 | fn visit_u8(self, value: u8) -> Result 75 | where 76 | E: serde::de::Error, 77 | { 78 | if let Ok(value) = i8::try_from(value) { 79 | Ok(Self::Value::new(value)) 80 | } else { 81 | Err(E::custom(format!("i8 is out of range: {}", value))) 82 | } 83 | } 84 | 85 | fn visit_u16(self, value: u16) -> Result 86 | where 87 | E: serde::de::Error, 88 | { 89 | if let Ok(value) = i8::try_from(value) { 90 | Ok(Self::Value::new(value)) 91 | } else { 92 | Err(E::custom(format!("i8 is out of range: {}", value))) 93 | } 94 | } 95 | 96 | fn visit_u32(self, value: u32) -> Result 97 | where 98 | E: serde::de::Error, 99 | { 100 | if let Ok(value) = i8::try_from(value) { 101 | Ok(Self::Value::new(value)) 102 | } else { 103 | Err(E::custom(format!("i8 is out of range: {}", value))) 104 | } 105 | } 106 | 107 | fn visit_u64(self, value: u64) -> Result 108 | where 109 | E: serde::de::Error, 110 | { 111 | if let Ok(value) = i8::try_from(value) { 112 | Ok(Self::Value::new(value)) 113 | } else { 114 | Err(E::custom(format!("i8 is out of range: {}", value))) 115 | } 116 | } 117 | } 118 | 119 | #[cfg(feature = "serde")] 120 | impl<'de> Deserialize<'de> for AtomicI8 { 121 | fn deserialize(deserializer: D) -> Result 122 | where 123 | D: Deserializer<'de>, 124 | { 125 | deserializer.deserialize_i8(AtomicI8Visitor) 126 | } 127 | } 128 | 129 | #[cfg(feature = "serde")] 130 | impl Serialize for AtomicI8 { 131 | #[inline] 132 | fn serialize(&self, serializer: S) -> Result 133 | where 134 | S: Serializer, 135 | { 136 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 137 | } 138 | } 139 | 140 | #[cfg(test)] 141 | mod tests { 142 | use super::*; 143 | 144 | #[test] 145 | fn load() { 146 | let atomic = AtomicI8::new(0); 147 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 148 | } 149 | 150 | #[test] 151 | fn store() { 152 | let atomic = AtomicI8::new(0); 153 | atomic.store(1, Ordering::SeqCst); 154 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 155 | } 156 | 157 | #[test] 158 | fn swap() { 159 | let atomic = AtomicI8::new(0); 160 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 161 | } 162 | 163 | #[test] 164 | fn compare_exchange() { 165 | let atomic = AtomicI8::new(0); 166 | assert_eq!( 167 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 168 | Ok(0) 169 | ); 170 | assert_eq!( 171 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 172 | Err(1) 173 | ); 174 | } 175 | 176 | #[test] 177 | fn compare_exchange_weak() { 178 | let atomic = AtomicI8::new(0); 179 | loop { 180 | if atomic 181 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 182 | .is_ok() 183 | { 184 | break; 185 | } 186 | } 187 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /atomics/src/types/isize.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// A signed pointer-sized integer which can be shared between threads 12 | pub struct AtomicIsize: isize = core::sync::atomic::AtomicIsize; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicIsize, isize); 17 | bitwise!(AtomicIsize, isize); 18 | fetch_compare_store!(AtomicIsize, isize); 19 | saturating_arithmetic!(AtomicIsize, isize); 20 | 21 | impl Signed for AtomicIsize {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicIsizeVisitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicIsizeVisitor { 28 | type Value = AtomicIsize; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("a signed integer matching the pointer width") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | Ok(Self::Value::new(isize::from(value))) 39 | } 40 | 41 | fn visit_i16(self, value: i16) -> Result 42 | where 43 | E: serde::de::Error, 44 | { 45 | Ok(Self::Value::new(isize::from(value))) 46 | } 47 | 48 | fn visit_i32(self, value: i32) -> Result 49 | where 50 | E: serde::de::Error, 51 | { 52 | if let Ok(value) = isize::try_from(value) { 53 | Ok(Self::Value::new(value)) 54 | } else { 55 | Err(E::custom(format!("isize is out of range: {}", value))) 56 | } 57 | } 58 | 59 | fn visit_i64(self, value: i64) -> Result 60 | where 61 | E: serde::de::Error, 62 | { 63 | if let Ok(value) = isize::try_from(value) { 64 | Ok(Self::Value::new(value)) 65 | } else { 66 | Err(E::custom(format!("isize is out of range: {}", value))) 67 | } 68 | } 69 | 70 | fn visit_u8(self, value: u8) -> Result 71 | where 72 | E: serde::de::Error, 73 | { 74 | Ok(Self::Value::new(isize::from(value))) 75 | } 76 | 77 | fn visit_u16(self, value: u16) -> Result 78 | where 79 | E: serde::de::Error, 80 | { 81 | if let Ok(value) = isize::try_from(value) { 82 | Ok(Self::Value::new(value)) 83 | } else { 84 | Err(E::custom(format!("isize is out of range: {}", value))) 85 | } 86 | } 87 | 88 | fn visit_u32(self, value: u32) -> Result 89 | where 90 | E: serde::de::Error, 91 | { 92 | if let Ok(value) = isize::try_from(value) { 93 | Ok(Self::Value::new(value)) 94 | } else { 95 | Err(E::custom(format!("isize is out of range: {}", value))) 96 | } 97 | } 98 | 99 | fn visit_u64(self, value: u64) -> Result 100 | where 101 | E: serde::de::Error, 102 | { 103 | if let Ok(value) = isize::try_from(value) { 104 | Ok(Self::Value::new(value)) 105 | } else { 106 | Err(E::custom(format!("isize is out of range: {}", value))) 107 | } 108 | } 109 | } 110 | 111 | #[cfg(feature = "serde")] 112 | impl<'de> Deserialize<'de> for AtomicIsize { 113 | fn deserialize(deserializer: D) -> Result 114 | where 115 | D: Deserializer<'de>, 116 | { 117 | deserializer.deserialize_any(AtomicIsizeVisitor) 118 | } 119 | } 120 | 121 | #[cfg(feature = "serde")] 122 | impl Serialize for AtomicIsize { 123 | #[inline] 124 | fn serialize(&self, serializer: S) -> Result 125 | where 126 | S: Serializer, 127 | { 128 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 129 | } 130 | } 131 | 132 | #[cfg(test)] 133 | mod tests { 134 | use super::*; 135 | 136 | #[test] 137 | fn load() { 138 | let atomic = AtomicIsize::new(0); 139 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 140 | } 141 | 142 | #[test] 143 | fn store() { 144 | let atomic = AtomicIsize::new(0); 145 | atomic.store(1, Ordering::SeqCst); 146 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 147 | } 148 | 149 | #[test] 150 | fn swap() { 151 | let atomic = AtomicIsize::new(0); 152 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 153 | } 154 | 155 | #[test] 156 | fn compare_exchange() { 157 | let atomic = AtomicIsize::new(0); 158 | assert_eq!( 159 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 160 | Ok(0) 161 | ); 162 | assert_eq!( 163 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 164 | Err(1) 165 | ); 166 | } 167 | 168 | #[test] 169 | fn compare_exchange_weak() { 170 | let atomic = AtomicIsize::new(0); 171 | loop { 172 | if atomic 173 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 174 | .is_ok() 175 | { 176 | break; 177 | } 178 | } 179 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /atomics/src/types/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | mod bool; 6 | pub use self::bool::*; 7 | 8 | mod f32; 9 | pub use self::f32::*; 10 | 11 | mod f64; 12 | pub use self::f64::*; 13 | 14 | mod i8; 15 | pub use self::i8::*; 16 | 17 | mod i16; 18 | pub use self::i16::*; 19 | 20 | mod i32; 21 | pub use self::i32::*; 22 | 23 | mod i64; 24 | pub use self::i64::*; 25 | 26 | mod isize; 27 | pub use self::isize::*; 28 | 29 | mod u8; 30 | pub use self::u8::*; 31 | 32 | mod u16; 33 | pub use self::u16::*; 34 | 35 | mod u32; 36 | pub use self::u32::*; 37 | 38 | mod u64; 39 | pub use self::u64::*; 40 | 41 | mod usize; 42 | pub use self::usize::*; 43 | -------------------------------------------------------------------------------- /atomics/src/types/u16.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// An unsigned 16 bit integer which can be shared between threads 12 | pub struct AtomicU16: u16 = core::sync::atomic::AtomicU16; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicU16, u16); 17 | bitwise!(AtomicU16, u16); 18 | fetch_compare_store!(AtomicU16, u16); 19 | saturating_arithmetic!(AtomicU16, u16); 20 | 21 | impl Unsigned for AtomicU16 {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicU16Visitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicU16Visitor { 28 | type Value = AtomicU16; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("an unsigned 16bit integer") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | if let Ok(value) = u16::try_from(value) { 39 | Ok(Self::Value::new(value)) 40 | } else { 41 | Err(E::custom(format!("u16 is out of range: {}", value))) 42 | } 43 | } 44 | 45 | fn visit_i16(self, value: i16) -> Result 46 | where 47 | E: serde::de::Error, 48 | { 49 | if let Ok(value) = u16::try_from(value) { 50 | Ok(Self::Value::new(value)) 51 | } else { 52 | Err(E::custom(format!("u16 is out of range: {}", value))) 53 | } 54 | } 55 | 56 | fn visit_i32(self, value: i32) -> Result 57 | where 58 | E: serde::de::Error, 59 | { 60 | if let Ok(value) = u16::try_from(value) { 61 | Ok(Self::Value::new(value)) 62 | } else { 63 | Err(E::custom(format!("u16 is out of range: {}", value))) 64 | } 65 | } 66 | 67 | fn visit_i64(self, value: i64) -> Result 68 | where 69 | E: serde::de::Error, 70 | { 71 | if let Ok(value) = u16::try_from(value) { 72 | Ok(Self::Value::new(value)) 73 | } else { 74 | Err(E::custom(format!("u16 is out of range: {}", value))) 75 | } 76 | } 77 | 78 | fn visit_u8(self, value: u8) -> Result 79 | where 80 | E: serde::de::Error, 81 | { 82 | Ok(Self::Value::new(u16::from(value))) 83 | } 84 | 85 | fn visit_u16(self, value: u16) -> Result 86 | where 87 | E: serde::de::Error, 88 | { 89 | Ok(Self::Value::new(value)) 90 | } 91 | 92 | fn visit_u32(self, value: u32) -> Result 93 | where 94 | E: serde::de::Error, 95 | { 96 | if let Ok(value) = u16::try_from(value) { 97 | Ok(Self::Value::new(value)) 98 | } else { 99 | Err(E::custom(format!("u16 is out of range: {}", value))) 100 | } 101 | } 102 | 103 | fn visit_u64(self, value: u64) -> Result 104 | where 105 | E: serde::de::Error, 106 | { 107 | if let Ok(value) = u16::try_from(value) { 108 | Ok(Self::Value::new(value)) 109 | } else { 110 | Err(E::custom(format!("u16 is out of range: {}", value))) 111 | } 112 | } 113 | } 114 | 115 | #[cfg(feature = "serde")] 116 | impl<'de> Deserialize<'de> for AtomicU16 { 117 | fn deserialize(deserializer: D) -> Result 118 | where 119 | D: Deserializer<'de>, 120 | { 121 | deserializer.deserialize_any(AtomicU16Visitor) 122 | } 123 | } 124 | 125 | #[cfg(feature = "serde")] 126 | impl Serialize for AtomicU16 { 127 | #[inline] 128 | fn serialize(&self, serializer: S) -> Result 129 | where 130 | S: Serializer, 131 | { 132 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 133 | } 134 | } 135 | 136 | #[cfg(test)] 137 | mod tests { 138 | use super::*; 139 | 140 | #[test] 141 | fn load() { 142 | let atomic = AtomicU16::new(0); 143 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 144 | } 145 | 146 | #[test] 147 | fn store() { 148 | let atomic = AtomicU16::new(0); 149 | atomic.store(1, Ordering::SeqCst); 150 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 151 | } 152 | 153 | #[test] 154 | fn swap() { 155 | let atomic = AtomicU16::new(0); 156 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 157 | } 158 | 159 | #[test] 160 | fn compare_exchange() { 161 | let atomic = AtomicU16::new(0); 162 | assert_eq!( 163 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 164 | Ok(0) 165 | ); 166 | assert_eq!( 167 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 168 | Err(1) 169 | ); 170 | } 171 | 172 | #[test] 173 | fn compare_exchange_weak() { 174 | let atomic = AtomicU16::new(0); 175 | loop { 176 | if atomic 177 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 178 | .is_ok() 179 | { 180 | break; 181 | } 182 | } 183 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /atomics/src/types/u32.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// An unsigned 32 bit integer which can be shared between threads 12 | pub struct AtomicU32: u32 = core::sync::atomic::AtomicU32; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicU32, u32); 17 | bitwise!(AtomicU32, u32); 18 | fetch_compare_store!(AtomicU32, u32); 19 | saturating_arithmetic!(AtomicU32, u32); 20 | 21 | impl Unsigned for AtomicU32 {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicU32Visitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicU32Visitor { 28 | type Value = AtomicU32; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("an unsigned 32bit integer") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | if let Ok(value) = u32::try_from(value) { 39 | Ok(Self::Value::new(value)) 40 | } else { 41 | Err(E::custom(format!("u32 is out of range: {}", value))) 42 | } 43 | } 44 | 45 | fn visit_i16(self, value: i16) -> Result 46 | where 47 | E: serde::de::Error, 48 | { 49 | if let Ok(value) = u32::try_from(value) { 50 | Ok(Self::Value::new(value)) 51 | } else { 52 | Err(E::custom(format!("u32 is out of range: {}", value))) 53 | } 54 | } 55 | 56 | fn visit_i32(self, value: i32) -> Result 57 | where 58 | E: serde::de::Error, 59 | { 60 | if let Ok(value) = u32::try_from(value) { 61 | Ok(Self::Value::new(value)) 62 | } else { 63 | Err(E::custom(format!("u32 is out of range: {}", value))) 64 | } 65 | } 66 | 67 | fn visit_i64(self, value: i64) -> Result 68 | where 69 | E: serde::de::Error, 70 | { 71 | if let Ok(value) = u32::try_from(value) { 72 | Ok(Self::Value::new(value)) 73 | } else { 74 | Err(E::custom(format!("u32 is out of range: {}", value))) 75 | } 76 | } 77 | 78 | fn visit_u8(self, value: u8) -> Result 79 | where 80 | E: serde::de::Error, 81 | { 82 | Ok(Self::Value::new(u32::from(value))) 83 | } 84 | 85 | fn visit_u16(self, value: u16) -> Result 86 | where 87 | E: serde::de::Error, 88 | { 89 | Ok(Self::Value::new(u32::from(value))) 90 | } 91 | 92 | fn visit_u32(self, value: u32) -> Result 93 | where 94 | E: serde::de::Error, 95 | { 96 | Ok(Self::Value::new(value)) 97 | } 98 | 99 | fn visit_u64(self, value: u64) -> Result 100 | where 101 | E: serde::de::Error, 102 | { 103 | if let Ok(value) = u32::try_from(value) { 104 | Ok(Self::Value::new(value)) 105 | } else { 106 | Err(E::custom(format!("u32 is out of range: {}", value))) 107 | } 108 | } 109 | } 110 | 111 | #[cfg(feature = "serde")] 112 | impl<'de> Deserialize<'de> for AtomicU32 { 113 | fn deserialize(deserializer: D) -> Result 114 | where 115 | D: Deserializer<'de>, 116 | { 117 | deserializer.deserialize_any(AtomicU32Visitor) 118 | } 119 | } 120 | 121 | #[cfg(feature = "serde")] 122 | impl Serialize for AtomicU32 { 123 | #[inline] 124 | fn serialize(&self, serializer: S) -> Result 125 | where 126 | S: Serializer, 127 | { 128 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 129 | } 130 | } 131 | 132 | #[cfg(test)] 133 | mod tests { 134 | use super::*; 135 | 136 | #[test] 137 | fn load() { 138 | let atomic = AtomicU32::new(0); 139 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 140 | } 141 | 142 | #[test] 143 | fn store() { 144 | let atomic = AtomicU32::new(0); 145 | atomic.store(1, Ordering::SeqCst); 146 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 147 | } 148 | 149 | #[test] 150 | fn swap() { 151 | let atomic = AtomicU32::new(0); 152 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 153 | } 154 | 155 | #[test] 156 | fn compare_exchange() { 157 | let atomic = AtomicU32::new(0); 158 | assert_eq!( 159 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 160 | Ok(0) 161 | ); 162 | assert_eq!( 163 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 164 | Err(1) 165 | ); 166 | } 167 | 168 | #[test] 169 | fn compare_exchange_weak() { 170 | let atomic = AtomicU32::new(0); 171 | loop { 172 | if atomic 173 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 174 | .is_ok() 175 | { 176 | break; 177 | } 178 | } 179 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /atomics/src/types/u64.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// An unsigned 64 bit integer which can be shared between threads 12 | pub struct AtomicU64: u64 = core::sync::atomic::AtomicU64; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicU64, u64); 17 | bitwise!(AtomicU64, u64); 18 | fetch_compare_store!(AtomicU64, u64); 19 | saturating_arithmetic!(AtomicU64, ::Primitive); 20 | 21 | impl Unsigned for AtomicU64 {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicU64Visitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicU64Visitor { 28 | type Value = AtomicU64; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("an unsigned 64bit integer") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | if let Ok(value) = u64::try_from(value) { 39 | Ok(Self::Value::new(value)) 40 | } else { 41 | Err(E::custom(format!("u64 is out of range: {}", value))) 42 | } 43 | } 44 | 45 | fn visit_i16(self, value: i16) -> Result 46 | where 47 | E: serde::de::Error, 48 | { 49 | if let Ok(value) = u64::try_from(value) { 50 | Ok(Self::Value::new(value)) 51 | } else { 52 | Err(E::custom(format!("u64 is out of range: {}", value))) 53 | } 54 | } 55 | 56 | fn visit_i32(self, value: i32) -> Result 57 | where 58 | E: serde::de::Error, 59 | { 60 | if let Ok(value) = u64::try_from(value) { 61 | Ok(Self::Value::new(value)) 62 | } else { 63 | Err(E::custom(format!("u64 is out of range: {}", value))) 64 | } 65 | } 66 | 67 | fn visit_i64(self, value: i64) -> Result 68 | where 69 | E: serde::de::Error, 70 | { 71 | if let Ok(value) = u64::try_from(value) { 72 | Ok(Self::Value::new(value)) 73 | } else { 74 | Err(E::custom(format!("u64 is out of range: {}", value))) 75 | } 76 | } 77 | 78 | fn visit_u8(self, value: u8) -> Result 79 | where 80 | E: serde::de::Error, 81 | { 82 | Ok(Self::Value::new(u64::from(value))) 83 | } 84 | 85 | fn visit_u16(self, value: u16) -> Result 86 | where 87 | E: serde::de::Error, 88 | { 89 | Ok(Self::Value::new(u64::from(value))) 90 | } 91 | 92 | fn visit_u32(self, value: u32) -> Result 93 | where 94 | E: serde::de::Error, 95 | { 96 | Ok(Self::Value::new(u64::from(value))) 97 | } 98 | 99 | fn visit_u64(self, value: u64) -> Result 100 | where 101 | E: serde::de::Error, 102 | { 103 | Ok(Self::Value::new(value)) 104 | } 105 | } 106 | 107 | #[cfg(feature = "serde")] 108 | impl<'de> Deserialize<'de> for AtomicU64 { 109 | fn deserialize(deserializer: D) -> Result 110 | where 111 | D: Deserializer<'de>, 112 | { 113 | deserializer.deserialize_any(AtomicU64Visitor) 114 | } 115 | } 116 | 117 | #[cfg(feature = "serde")] 118 | impl Serialize for AtomicU64 { 119 | #[inline] 120 | fn serialize(&self, serializer: S) -> Result 121 | where 122 | S: Serializer, 123 | { 124 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 125 | } 126 | } 127 | 128 | #[cfg(test)] 129 | mod tests { 130 | use super::*; 131 | 132 | #[test] 133 | fn load() { 134 | let atomic = AtomicU64::new(0); 135 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 136 | } 137 | 138 | #[test] 139 | fn store() { 140 | let atomic = AtomicU64::new(0); 141 | atomic.store(1, Ordering::SeqCst); 142 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 143 | } 144 | 145 | #[test] 146 | fn swap() { 147 | let atomic = AtomicU64::new(0); 148 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 149 | } 150 | 151 | #[test] 152 | fn compare_exchange() { 153 | let atomic = AtomicU64::new(0); 154 | assert_eq!( 155 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 156 | Ok(0) 157 | ); 158 | assert_eq!( 159 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 160 | Err(1) 161 | ); 162 | } 163 | 164 | #[test] 165 | fn compare_exchange_weak() { 166 | let atomic = AtomicU64::new(0); 167 | loop { 168 | if atomic 169 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 170 | .is_ok() 171 | { 172 | break; 173 | } 174 | } 175 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /atomics/src/types/u8.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// An unsigned 8 bit integer which can be shared between threads 12 | pub struct AtomicU8: u8 = core::sync::atomic::AtomicU8; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicU8, u8); 17 | bitwise!(AtomicU8, u8); 18 | fetch_compare_store!(AtomicU8, u8); 19 | saturating_arithmetic!(AtomicU8, u8); 20 | 21 | impl Unsigned for AtomicU8 {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicU8Visitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicU8Visitor { 28 | type Value = AtomicU8; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("an unsigned 8bit integer") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | if let Ok(value) = u8::try_from(value) { 39 | Ok(Self::Value::new(value)) 40 | } else { 41 | Err(E::custom(format!("u8 is out of range: {}", value))) 42 | } 43 | } 44 | 45 | fn visit_i16(self, value: i16) -> Result 46 | where 47 | E: serde::de::Error, 48 | { 49 | if let Ok(value) = u8::try_from(value) { 50 | Ok(Self::Value::new(value)) 51 | } else { 52 | Err(E::custom(format!("u8 is out of range: {}", value))) 53 | } 54 | } 55 | 56 | fn visit_i32(self, value: i32) -> Result 57 | where 58 | E: serde::de::Error, 59 | { 60 | if let Ok(value) = u8::try_from(value) { 61 | Ok(Self::Value::new(value)) 62 | } else { 63 | Err(E::custom(format!("u8 is out of range: {}", value))) 64 | } 65 | } 66 | 67 | fn visit_i64(self, value: i64) -> Result 68 | where 69 | E: serde::de::Error, 70 | { 71 | if let Ok(value) = u8::try_from(value) { 72 | Ok(Self::Value::new(value)) 73 | } else { 74 | Err(E::custom(format!("u8 is out of range: {}", value))) 75 | } 76 | } 77 | 78 | fn visit_u8(self, value: u8) -> Result 79 | where 80 | E: serde::de::Error, 81 | { 82 | Ok(Self::Value::new(value)) 83 | } 84 | 85 | fn visit_u16(self, value: u16) -> Result 86 | where 87 | E: serde::de::Error, 88 | { 89 | if let Ok(value) = u8::try_from(value) { 90 | Ok(Self::Value::new(value)) 91 | } else { 92 | Err(E::custom(format!("u8 is out of range: {}", value))) 93 | } 94 | } 95 | 96 | fn visit_u32(self, value: u32) -> Result 97 | where 98 | E: serde::de::Error, 99 | { 100 | if let Ok(value) = u8::try_from(value) { 101 | Ok(Self::Value::new(value)) 102 | } else { 103 | Err(E::custom(format!("u8 is out of range: {}", value))) 104 | } 105 | } 106 | 107 | fn visit_u64(self, value: u64) -> Result 108 | where 109 | E: serde::de::Error, 110 | { 111 | if let Ok(value) = u8::try_from(value) { 112 | Ok(Self::Value::new(value)) 113 | } else { 114 | Err(E::custom(format!("u8 is out of range: {}", value))) 115 | } 116 | } 117 | } 118 | 119 | #[cfg(feature = "serde")] 120 | impl<'de> Deserialize<'de> for AtomicU8 { 121 | fn deserialize(deserializer: D) -> Result 122 | where 123 | D: Deserializer<'de>, 124 | { 125 | deserializer.deserialize_any(AtomicU8Visitor) 126 | } 127 | } 128 | 129 | #[cfg(feature = "serde")] 130 | impl Serialize for AtomicU8 { 131 | #[inline] 132 | fn serialize(&self, serializer: S) -> Result 133 | where 134 | S: Serializer, 135 | { 136 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 137 | } 138 | } 139 | 140 | #[cfg(test)] 141 | mod tests { 142 | use super::*; 143 | 144 | #[test] 145 | fn load() { 146 | let atomic = AtomicU8::new(0); 147 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 148 | } 149 | 150 | #[test] 151 | fn store() { 152 | let atomic = AtomicU8::new(0); 153 | atomic.store(1, Ordering::SeqCst); 154 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 155 | } 156 | 157 | #[test] 158 | fn swap() { 159 | let atomic = AtomicU8::new(0); 160 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 161 | } 162 | 163 | #[test] 164 | fn compare_exchange() { 165 | let atomic = AtomicU8::new(0); 166 | assert_eq!( 167 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 168 | Ok(0) 169 | ); 170 | assert_eq!( 171 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 172 | Err(1) 173 | ); 174 | } 175 | 176 | #[test] 177 | fn compare_exchange_weak() { 178 | let atomic = AtomicU8::new(0); 179 | loop { 180 | if atomic 181 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 182 | .is_ok() 183 | { 184 | break; 185 | } 186 | } 187 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /atomics/src/types/usize.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | #[cfg(feature = "serde")] 8 | use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; 9 | 10 | native!( 11 | /// An unsigned pointer-sized integer which can be shared between threads 12 | pub struct AtomicUsize: usize = core::sync::atomic::AtomicUsize; 13 | ); 14 | 15 | // additional traits 16 | arithmetic!(AtomicUsize, usize); 17 | bitwise!(AtomicUsize, usize); 18 | fetch_compare_store!(AtomicUsize, usize); 19 | saturating_arithmetic!(AtomicUsize, usize); 20 | 21 | impl Unsigned for AtomicUsize {} 22 | 23 | #[cfg(feature = "serde")] 24 | struct AtomicUsizeVisitor; 25 | 26 | #[cfg(feature = "serde")] 27 | impl<'de> Visitor<'de> for AtomicUsizeVisitor { 28 | type Value = AtomicUsize; 29 | 30 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { 31 | formatter.write_str("a signed integer matching the pointer width") 32 | } 33 | 34 | fn visit_i8(self, value: i8) -> Result 35 | where 36 | E: serde::de::Error, 37 | { 38 | if let Ok(value) = usize::try_from(value) { 39 | Ok(Self::Value::new(value)) 40 | } else { 41 | Err(E::custom(format!("usize is out of range: {}", value))) 42 | } 43 | } 44 | 45 | fn visit_i16(self, value: i16) -> Result 46 | where 47 | E: serde::de::Error, 48 | { 49 | if let Ok(value) = usize::try_from(value) { 50 | Ok(Self::Value::new(value)) 51 | } else { 52 | Err(E::custom(format!("usize is out of range: {}", value))) 53 | } 54 | } 55 | 56 | fn visit_i32(self, value: i32) -> Result 57 | where 58 | E: serde::de::Error, 59 | { 60 | if let Ok(value) = usize::try_from(value) { 61 | Ok(Self::Value::new(value)) 62 | } else { 63 | Err(E::custom(format!("usize is out of range: {}", value))) 64 | } 65 | } 66 | 67 | fn visit_i64(self, value: i64) -> Result 68 | where 69 | E: serde::de::Error, 70 | { 71 | if let Ok(value) = usize::try_from(value) { 72 | Ok(Self::Value::new(value)) 73 | } else { 74 | Err(E::custom(format!("usize is out of range: {}", value))) 75 | } 76 | } 77 | 78 | fn visit_u8(self, value: u8) -> Result 79 | where 80 | E: serde::de::Error, 81 | { 82 | Ok(Self::Value::new(usize::from(value))) 83 | } 84 | 85 | fn visit_u16(self, value: u16) -> Result 86 | where 87 | E: serde::de::Error, 88 | { 89 | if let Ok(value) = usize::try_from(value) { 90 | Ok(Self::Value::new(value)) 91 | } else { 92 | Err(E::custom(format!("usize is out of range: {}", value))) 93 | } 94 | } 95 | 96 | fn visit_u32(self, value: u32) -> Result 97 | where 98 | E: serde::de::Error, 99 | { 100 | if let Ok(value) = usize::try_from(value) { 101 | Ok(Self::Value::new(value)) 102 | } else { 103 | Err(E::custom(format!("usize is out of range: {}", value))) 104 | } 105 | } 106 | 107 | fn visit_u64(self, value: u64) -> Result 108 | where 109 | E: serde::de::Error, 110 | { 111 | if let Ok(value) = usize::try_from(value) { 112 | Ok(Self::Value::new(value)) 113 | } else { 114 | Err(E::custom(format!("usize is out of range: {}", value))) 115 | } 116 | } 117 | } 118 | 119 | #[cfg(feature = "serde")] 120 | impl<'de> Deserialize<'de> for AtomicUsize { 121 | fn deserialize(deserializer: D) -> Result 122 | where 123 | D: Deserializer<'de>, 124 | { 125 | deserializer.deserialize_any(AtomicUsizeVisitor) 126 | } 127 | } 128 | 129 | #[cfg(feature = "serde")] 130 | impl Serialize for AtomicUsize { 131 | #[inline] 132 | fn serialize(&self, serializer: S) -> Result 133 | where 134 | S: Serializer, 135 | { 136 | serializer.serialize_some(&self.load(Ordering::SeqCst)) 137 | } 138 | } 139 | 140 | #[cfg(test)] 141 | mod tests { 142 | use super::*; 143 | 144 | #[test] 145 | fn load() { 146 | let atomic = AtomicUsize::new(0); 147 | assert_eq!(atomic.load(Ordering::SeqCst), 0); 148 | } 149 | 150 | #[test] 151 | fn store() { 152 | let atomic = AtomicUsize::new(0); 153 | atomic.store(1, Ordering::SeqCst); 154 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 155 | } 156 | 157 | #[test] 158 | fn swap() { 159 | let atomic = AtomicUsize::new(0); 160 | assert_eq!(atomic.swap(1, Ordering::SeqCst), 0); 161 | } 162 | 163 | #[test] 164 | fn compare_exchange() { 165 | let atomic = AtomicUsize::new(0); 166 | assert_eq!( 167 | atomic.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst), 168 | Ok(0) 169 | ); 170 | assert_eq!( 171 | atomic.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), 172 | Err(1) 173 | ); 174 | } 175 | 176 | #[test] 177 | fn compare_exchange_weak() { 178 | let atomic = AtomicUsize::new(0); 179 | loop { 180 | if atomic 181 | .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst) 182 | .is_ok() 183 | { 184 | break; 185 | } 186 | } 187 | assert_eq!(atomic.load(Ordering::SeqCst), 1); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /heatmap/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "heatmap" 3 | version = "0.0.0" 4 | authors = ["Brian Martin "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | description = "Heatmap datastructure for tracking distributions across a time window" 8 | homepage = "https://github.com/twitter/rustcommon/heatmap" 9 | repository = "https://github.com/twitter/rustcommon" 10 | 11 | [dependencies] 12 | histogram = { path = "../histogram" } 13 | rustcommon-time = { path = "../time" } 14 | thiserror = "1.0.34" 15 | 16 | [dev-dependencies] 17 | criterion = "0.3.6" 18 | 19 | [[bench]] 20 | name = "heatmap" 21 | harness = false 22 | -------------------------------------------------------------------------------- /heatmap/README.md: -------------------------------------------------------------------------------- 1 | # histogram 2 | 3 | A simple histogram implementation inspired by HDRHistogram and our base-2 4 | implementation from [ccommon]. It uses atomic counters to record increments for 5 | each value. 6 | 7 | ## Getting Started 8 | 9 | ### Building 10 | 11 | rustcommon is built with the standard Rust toolchain which can be installed and 12 | managed via [rustup](https://rustup.rs) or by following the directions on the 13 | Rust [website](https://www.rust-lang.org/). 14 | 15 | #### View library documentation 16 | ```bash 17 | cargo doc --open 18 | ``` 19 | 20 | ## Support 21 | 22 | Create a [new issue](https://github.com/twitter/rustcommon/issues/new) on GitHub. 23 | 24 | ## Contributing 25 | 26 | We feel that a welcoming community is important and we ask that you follow 27 | Twitter's [Open Source Code of Conduct] in all interactions with the community. 28 | 29 | ## Authors 30 | 31 | * Brian Martin 32 | 33 | A full list of [contributors] can be found on GitHub. 34 | 35 | Follow [@TwitterOSS](https://twitter.com/twitteross) on Twitter for updates. 36 | 37 | ## License 38 | 39 | Copyright 2020 Twitter, Inc. 40 | 41 | Licensed under the Apache License, Version 2.0: 42 | https://www.apache.org/licenses/LICENSE-2.0 43 | 44 | ## Security Issues? 45 | 46 | Please report sensitive security issues via Twitter's bug-bounty program 47 | (https://hackerone.com/twitter) rather than GitHub. 48 | 49 | [ccommon]: https://github.com/twitter/ccommon/ 50 | [contributors]: https://github.com/twitter/rustcommon/graphs/contributors?type=a 51 | [Open Source Code of Conduct]: https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md 52 | -------------------------------------------------------------------------------- /heatmap/benches/heatmap.rs: -------------------------------------------------------------------------------- 1 | use criterion::Throughput; 2 | use criterion::{criterion_group, criterion_main, Criterion}; 3 | use heatmap::*; 4 | 5 | fn heatmap(c: &mut Criterion) { 6 | let heatmap = Heatmap::new(0, 4, 20, Duration::from_secs(1), Duration::from_millis(1)).unwrap(); 7 | 8 | let mut group = c.benchmark_group("heatmap"); 9 | 10 | group.throughput(Throughput::Elements(1)); 11 | let mut time = Instant::now(); 12 | let interval = Duration::from_millis(1); 13 | group.bench_function("increment", |b| { 14 | b.iter(|| { 15 | time += interval; 16 | heatmap.increment(Instant::now(), 1, 1) 17 | }) 18 | }); 19 | } 20 | 21 | criterion_group!(benches, heatmap); 22 | criterion_main!(benches); 23 | -------------------------------------------------------------------------------- /heatmap/src/error.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use histogram::Error as HistogramError; 6 | use thiserror::Error; 7 | 8 | #[derive(Error, Debug, PartialEq, Eq)] 9 | pub enum Error { 10 | #[error("heatmap contains no samples")] 11 | /// The heatmap contains no samples. 12 | Empty, 13 | #[error("invalid percentile")] 14 | /// The provided percentile is outside of the range 0.0 - 100.0 (inclusive) 15 | InvalidPercentile, 16 | #[error("value out of range")] 17 | /// The provided value is outside of the storable range. 18 | OutOfRange, 19 | #[error("invalid heatmap config")] 20 | /// The heatmap configuration is invalid, see docs for `Heatmap::new()` for 21 | /// the constraints. 22 | InvalidConfig, 23 | } 24 | 25 | impl From for Error { 26 | fn from(other: HistogramError) -> Self { 27 | match other { 28 | HistogramError::Empty => Self::Empty, 29 | HistogramError::InvalidPercentile => Self::InvalidPercentile, 30 | HistogramError::OutOfRange => Self::OutOfRange, 31 | HistogramError::InvalidConfig => Self::InvalidConfig, 32 | HistogramError::IncompatibleHistogram => { 33 | // SAFETY: a heatmap has histograms which all have the same 34 | // configuration and therefore the operations which act on two 35 | // histograms will always have two compatible histograms 36 | panic!("imposible state") 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /heatmap/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | mod error; 6 | mod heatmap; 7 | mod window; 8 | 9 | use core::sync::atomic::AtomicU64; 10 | use rustcommon_time::Nanoseconds; 11 | 12 | pub use self::heatmap::Heatmap; 13 | pub use error::Error; 14 | pub use window::Window; 15 | 16 | pub type Instant = rustcommon_time::Instant>; 17 | pub type Duration = rustcommon_time::Duration>; 18 | 19 | type AtomicInstant = rustcommon_time::Instant>; 20 | 21 | #[cfg(test)] 22 | mod tests { 23 | use super::*; 24 | 25 | #[test] 26 | fn age_out() { 27 | let heatmap = 28 | Heatmap::new(0, 4, 20, Duration::from_secs(1), Duration::from_millis(1)).unwrap(); 29 | assert_eq!(heatmap.percentile(0.0).map(|v| v.high()), Err(Error::Empty)); 30 | heatmap.increment(Instant::now(), 1, 1); 31 | assert_eq!(heatmap.percentile(0.0).map(|v| v.high()), Ok(1)); 32 | std::thread::sleep(std::time::Duration::from_millis(100)); 33 | assert_eq!(heatmap.percentile(0.0).map(|v| v.high()), Ok(1)); 34 | std::thread::sleep(std::time::Duration::from_millis(2000)); 35 | assert_eq!(heatmap.percentile(0.0).map(|v| v.high()), Err(Error::Empty)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /heatmap/src/window.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use histogram::Histogram; 6 | use rustcommon_time::*; 7 | 8 | pub struct Window<'a> { 9 | pub(crate) start: Instant>, 10 | pub(crate) stop: Instant>, 11 | pub(crate) histogram: &'a Histogram, 12 | } 13 | 14 | impl<'a> Window<'a> { 15 | pub fn start(&self) -> Instant> { 16 | self.start 17 | } 18 | 19 | pub fn stop(&self) -> Instant> { 20 | self.stop 21 | } 22 | 23 | pub fn histogram(&self) -> &'a Histogram { 24 | &self.histogram 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /histogram/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "histogram" 3 | version = "0.0.0" 4 | edition = "2021" 5 | authors = ["Brian Martin "] 6 | license = "Apache-2.0" 7 | 8 | [dependencies] 9 | thiserror = "1.0.34" 10 | 11 | [dev-dependencies] 12 | criterion = "0.3.6" 13 | 14 | [[bench]] 15 | name = "bench" 16 | harness = false 17 | -------------------------------------------------------------------------------- /histogram/README.md: -------------------------------------------------------------------------------- 1 | # histogram 2 | 3 | A simple histogram implementation inspired by HDRHistogram and our base-2 4 | implementation from [ccommon]. It uses atomic counters to record increments for 5 | each value. 6 | 7 | ## Getting Started 8 | 9 | ### Building 10 | 11 | rustcommon is built with the standard Rust toolchain which can be installed and 12 | managed via [rustup](https://rustup.rs) or by following the directions on the 13 | Rust [website](https://www.rust-lang.org/). 14 | 15 | #### View library documentation 16 | ```bash 17 | cargo doc --open 18 | ``` 19 | 20 | ## Support 21 | 22 | Create a [new issue](https://github.com/twitter/rustcommon/issues/new) on GitHub. 23 | 24 | ## Contributing 25 | 26 | We feel that a welcoming community is important and we ask that you follow 27 | Twitter's [Open Source Code of Conduct] in all interactions with the community. 28 | 29 | ## Authors 30 | 31 | * Brian Martin 32 | 33 | A full list of [contributors] can be found on GitHub. 34 | 35 | Follow [@TwitterOSS](https://twitter.com/twitteross) on Twitter for updates. 36 | 37 | ## License 38 | 39 | Copyright 2020 Twitter, Inc. 40 | 41 | Licensed under the Apache License, Version 2.0: 42 | https://www.apache.org/licenses/LICENSE-2.0 43 | 44 | ## Security Issues? 45 | 46 | Please report sensitive security issues via Twitter's bug-bounty program 47 | (https://hackerone.com/twitter) rather than GitHub. 48 | 49 | [ccommon]: https://github.com/twitter/ccommon/ 50 | [contributors]: https://github.com/twitter/rustcommon/graphs/contributors?type=a 51 | [Open Source Code of Conduct]: https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md 52 | -------------------------------------------------------------------------------- /histogram/benches/bench.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use criterion::{criterion_group, criterion_main, Criterion, Throughput}; 6 | use histogram::Histogram; 7 | 8 | fn increment(c: &mut Criterion) { 9 | let histogram = Histogram::new(0, 10, 30).unwrap(); 10 | 11 | let mut group = c.benchmark_group("histogram/increment"); 12 | group.throughput(Throughput::Elements(1)); 13 | 14 | group.throughput(Throughput::Elements(1)); 15 | group.bench_function("min", |b| b.iter(|| histogram.increment(1, 1))); 16 | group.bench_function("max", |b| b.iter(|| histogram.increment(1073741823, 1))); 17 | } 18 | 19 | criterion_group!(benches, increment,); 20 | criterion_main!(benches); 21 | -------------------------------------------------------------------------------- /histogram/src/bucket.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | /// A `Bucket` represents a discrete range of values and the sum of recorded 6 | /// counts within this range. 7 | #[derive(Clone, Copy)] 8 | pub struct Bucket { 9 | pub(crate) low: u64, 10 | pub(crate) high: u64, 11 | pub(crate) count: u32, 12 | } 13 | 14 | impl Bucket { 15 | /// The lowest value represented by this `Bucket`. 16 | pub fn low(&self) -> u64 { 17 | self.low 18 | } 19 | 20 | /// The highest value represented by this `Bucket`. 21 | pub fn high(&self) -> u64 { 22 | self.high 23 | } 24 | 25 | /// The sum of the recorded counts which fall into this `Bucket`. 26 | pub fn count(&self) -> u32 { 27 | self.count 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /histogram/src/error.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use thiserror::Error; 6 | 7 | /// Possible errors returned by operations on a histogram. 8 | #[derive(Error, Debug, PartialEq, Eq)] 9 | pub enum Error { 10 | #[error("histogram contains no samples")] 11 | /// The histogram contains no samples. 12 | Empty, 13 | #[error("invalid percentile")] 14 | /// The provided percentile is outside of the range 0.0 - 100.0 (inclusive) 15 | InvalidPercentile, 16 | #[error("value out of range")] 17 | /// The provided value is outside of the storable range. 18 | OutOfRange, 19 | #[error("incompatible histogram")] 20 | /// The operation requires histograms with the same parameters. 21 | IncompatibleHistogram, 22 | #[error("invalid histogram config")] 23 | /// The histogram configuration is invalid, see docs for `Histogram::new()` 24 | /// for the constraints. 25 | InvalidConfig, 26 | } 27 | -------------------------------------------------------------------------------- /histogram/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | mod bucket; 6 | mod error; 7 | mod histogram; 8 | mod percentile; 9 | 10 | pub use self::histogram::{Builder, Histogram}; 11 | pub use bucket::Bucket; 12 | pub use error::Error; 13 | pub use percentile::Percentile; 14 | 15 | #[cfg(test)] 16 | mod tests { 17 | use super::*; 18 | 19 | #[test] 20 | // run some test cases for various histogram sizes 21 | fn num_buckets() { 22 | let histogram = Histogram::new(0, 2, 10).unwrap(); 23 | assert_eq!(histogram.buckets(), 20); 24 | 25 | let histogram = Histogram::new(0, 10, 20).unwrap(); 26 | assert_eq!(histogram.buckets(), 6144); 27 | 28 | let histogram = Histogram::new(0, 10, 30).unwrap(); 29 | assert_eq!(histogram.buckets(), 11264); 30 | 31 | let histogram = Histogram::new(1, 10, 20).unwrap(); 32 | assert_eq!(histogram.buckets(), 3072); 33 | 34 | let histogram = Histogram::new(0, 9, 20).unwrap(); 35 | assert_eq!(histogram.buckets(), 3328); 36 | } 37 | 38 | #[test] 39 | fn percentiles() { 40 | let histogram = Histogram::new(0, 2, 10).unwrap(); 41 | 42 | for v in 1..1024 { 43 | assert!(histogram.increment(v, 1).is_ok()); 44 | assert!(histogram.percentile(100.0).map(|b| b.high()).unwrap_or(0) >= v); 45 | assert!(histogram.percentile(100.0).map(|b| b.low()).unwrap_or(0) <= v); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /histogram/src/percentile.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | /// A `Percentile` represents a quantile reading taken from a histogram. 8 | #[derive(Clone, Copy)] 9 | pub struct Percentile { 10 | pub(crate) percentile: f64, 11 | pub(crate) bucket: Bucket, 12 | } 13 | 14 | impl Percentile { 15 | /// Returns the percentile represented by this reading, from [0.0 - 100.0] 16 | pub fn percentile(&self) -> f64 { 17 | self.percentile 18 | } 19 | 20 | /// Returns the bucket which contains the reading. 21 | pub fn bucket(&self) -> Bucket { 22 | self.bucket 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /logger/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-logger" 3 | version = "0.1.1" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | ahash = "0.8.0" 10 | rustcommon-metrics = { path = "../metrics" } 11 | rustcommon-time = { path = "../time" } 12 | log = { version = "0.4.17", features = ["std"] } 13 | mpmc = "0.1.6" 14 | -------------------------------------------------------------------------------- /logger/examples/demo-multi.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use core::time::Duration; 6 | use rustcommon_logger::*; 7 | 8 | macro_rules! command { 9 | ($($arg:tt)*) => ( 10 | // we choose error level here because it is the lowest level and will 11 | // not be filtered unless the level filter is set to `off` 12 | error!(target: "command", $($arg)*); 13 | ) 14 | } 15 | 16 | macro_rules! noplog { 17 | ($($arg:tt)*) => ( 18 | // we choose error level here because it is the lowest level and will 19 | // not be filtered unless the level filter is set to `off` 20 | error!(target: "noplog", $($arg)*); 21 | ) 22 | } 23 | 24 | fn main() { 25 | let default = LogBuilder::new() 26 | .output(Box::new(Stdout::new())) 27 | .build() 28 | .expect("failed to initialize default log"); 29 | 30 | let command = LogBuilder::new() 31 | .output(Box::new( 32 | File::new("command.log", "command.old", 100).expect("failed to create file log"), 33 | )) 34 | .format(klog_format) 35 | .build() 36 | .expect("failed to initialize command log"); 37 | 38 | let noplog = NopLogBuilder::new().build(); 39 | 40 | let mut drain = MultiLogBuilder::new() 41 | .default(default) 42 | .add_target("command", command) 43 | .add_target("noplog", noplog) 44 | .build() 45 | .start(); 46 | 47 | std::thread::spawn(move || loop { 48 | let _ = drain.flush(); 49 | std::thread::sleep(Duration::from_millis(100)); 50 | }); 51 | 52 | error!("error"); 53 | warn!("warning"); 54 | info!("info"); 55 | debug!("debug"); 56 | trace!("trace"); 57 | 58 | command!("\"get 0\" 0 0"); 59 | 60 | noplog!("this won't get displayed"); 61 | 62 | std::thread::sleep(Duration::from_millis(1000)); 63 | } 64 | -------------------------------------------------------------------------------- /logger/examples/demo-single.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use core::time::Duration; 6 | use rustcommon_logger::*; 7 | 8 | fn main() { 9 | let log = LogBuilder::new() 10 | .output(Box::new(Stdout::new())) 11 | .build() 12 | .expect("failed to initialize log"); 13 | 14 | let mut drain = log.start(); 15 | 16 | std::thread::spawn(move || loop { 17 | let _ = drain.flush(); 18 | std::thread::sleep(Duration::from_millis(100)); 19 | }); 20 | 21 | error!("error"); 22 | warn!("warning"); 23 | info!("info"); 24 | debug!("debug"); 25 | trace!("trace"); 26 | 27 | std::thread::sleep(Duration::from_millis(1000)); 28 | } 29 | -------------------------------------------------------------------------------- /logger/src/format.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | use rustcommon_time::{DateTime, SecondsFormat}; 8 | 9 | pub type FormatFunction = fn( 10 | write: &mut dyn std::io::Write, 11 | now: DateTime, 12 | record: &Record, 13 | ) -> Result<(), std::io::Error>; 14 | 15 | pub fn default_format( 16 | w: &mut dyn std::io::Write, 17 | now: DateTime, 18 | record: &Record, 19 | ) -> Result<(), std::io::Error> { 20 | writeln!( 21 | w, 22 | "{} {} [{}] {}", 23 | now.to_rfc3339_opts(SecondsFormat::Millis, false), 24 | record.level(), 25 | record.module_path().unwrap_or(""), 26 | record.args() 27 | ) 28 | } 29 | 30 | pub fn klog_format( 31 | w: &mut dyn std::io::Write, 32 | now: DateTime, 33 | record: &Record, 34 | ) -> Result<(), std::io::Error> { 35 | writeln!( 36 | w, 37 | "{} {}", 38 | now.to_rfc3339_opts(SecondsFormat::Millis, false), 39 | record.args() 40 | ) 41 | } 42 | -------------------------------------------------------------------------------- /logger/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | //! This crate provides an asynchronous logging backend that can direct logs to 6 | //! one or more outputs. 7 | //! 8 | //! The core of this crate is the `AsyncLog` type, which is constructed using a 9 | //! builder that is specific to your logging needs. After building the 10 | //! `AsyncLog`, it can be registered as the global logger using the `start` 11 | //! method. You will be left with a `Box` which should be 12 | //! periodically flushed outside of any critical path. For example, in an admin 13 | //! thread or dedicated logging thread. 14 | //! 15 | //! For logging to a single file, the `LogBuilder` type can be used to construct 16 | //! an `AsyncLog` which has low overhead, but directs log messages to a single 17 | //! `Output`. 18 | //! 19 | //! A `SamplingLogBuilder` can be used to construct an `AsyncLog` which will 20 | //! filter the log messages using sampling before directing the log messages to 21 | //! a single `Output`. 22 | //! 23 | //! A `MultiLogBuilder` can be used to construct an `AsyncLog` which routes log 24 | //! messages based on the `target` metadata of the log `Record`. If there is an 25 | //! `AsyncLog` registered for that specific `target`, then the log message will 26 | //! be routed to that instance of `AsyncLog`. Log messages that do not match any 27 | //! specific target will be routed to the default `AsyncLog` that has been added 28 | //! to the `MultiLogBuilder`. If there is no default, messages that do not match 29 | //! any specific target will be simply dropped. 30 | //! 31 | //! This combination of logging types allows us to compose a logging backend 32 | //! which meets the application's needs. For example, you can use a local log 33 | //! macro to set the target to some specific category and log those messages to 34 | //! a file, while letting all other log messages pass to standard out. This 35 | //! could allow splitting command/access/audit logs from the normal logging. 36 | 37 | pub use log::*; 38 | 39 | mod format; 40 | mod multi; 41 | mod nop; 42 | mod outputs; 43 | mod sampling; 44 | mod single; 45 | mod traits; 46 | 47 | pub use format::*; 48 | pub use multi::*; 49 | pub use nop::*; 50 | pub use outputs::*; 51 | pub use sampling::*; 52 | pub use single::*; 53 | pub use traits::*; 54 | 55 | use mpmc::Queue; 56 | use rustcommon_time::DateTime; 57 | 58 | pub(crate) type LogBuffer = Vec; 59 | 60 | use rustcommon_metrics::*; 61 | 62 | counter!(LOG_CREATE, "logging targets initialized"); 63 | counter!( 64 | LOG_CREATE_EX, 65 | "number of exceptions while initializing logging targets" 66 | ); 67 | counter!(LOG_DESTROY, "logging targets destroyed"); 68 | gauge!(LOG_CURR, "current number of logging targets"); 69 | counter!( 70 | LOG_OPEN, 71 | "number of logging destinations which have been opened" 72 | ); 73 | counter!( 74 | LOG_OPEN_EX, 75 | "number of exceptions while opening logging destinations" 76 | ); 77 | counter!(LOG_WRITE, "number of writes to all loging destinations"); 78 | counter!( 79 | LOG_WRITE_BYTE, 80 | "number of bytes written to all logging destinations" 81 | ); 82 | counter!( 83 | LOG_WRITE_EX, 84 | "number of exceptions while writing to logging destinations" 85 | ); 86 | counter!( 87 | LOG_SKIP, 88 | "number of log messages skipped due to sampling policy" 89 | ); 90 | counter!( 91 | LOG_DROP, 92 | "number of log messages dropped due to full queues" 93 | ); 94 | counter!(LOG_DROP_BYTE, "number of bytes dropped due to full queues"); 95 | counter!( 96 | LOG_FLUSH, 97 | "number of times logging destinations have been flushed" 98 | ); 99 | counter!( 100 | LOG_FLUSH_EX, 101 | "number of exceptions while flushing logging destinations" 102 | ); 103 | 104 | /// A type which implements an asynchronous logging backend. 105 | pub struct AsyncLog { 106 | pub(crate) logger: Box, 107 | pub(crate) drain: Box, 108 | pub(crate) level_filter: LevelFilter, 109 | } 110 | 111 | impl AsyncLog { 112 | /// Register the logger and return a type which implements `Drain`. It is 113 | /// up to the user to periodically call flush on the resulting drain. 114 | pub fn start(self) -> Box { 115 | let level_filter = self.level_filter; 116 | log::set_boxed_logger(self.logger) 117 | .map(|()| log::set_max_level(level_filter)) 118 | .expect("failed to start logger"); 119 | self.drain 120 | } 121 | } 122 | 123 | #[macro_export] 124 | macro_rules! fatal { 125 | () => ( 126 | error!(); 127 | std::process::exit(1); 128 | ); 129 | ($fmt:expr) => ( 130 | error!($fmt); 131 | std::process::exit(1); 132 | ); 133 | ($fmt:expr, $($arg:tt)*) => ( 134 | error!($fmt, $($arg)*); 135 | std::process::exit(1); 136 | ); 137 | } 138 | -------------------------------------------------------------------------------- /logger/src/multi.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | use std::io::Error; 7 | 8 | use ahash::AHashMap as HashMap; 9 | 10 | pub(crate) struct MultiLogger { 11 | default: Option>, 12 | targets: HashMap>, 13 | level_filter: LevelFilter, 14 | } 15 | 16 | impl MultiLogger { 17 | fn get_target(&self, target: &str) -> Option<&dyn Log> { 18 | self.targets 19 | .get(target) 20 | .map(|t| t.as_ref()) 21 | .or_else(|| self.default.as_deref()) 22 | } 23 | } 24 | 25 | impl Log for MultiLogger { 26 | fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { 27 | if metadata.level() > self.level_filter { 28 | false 29 | } else if let Some(target) = self.get_target(metadata.target()) { 30 | target.enabled(metadata) 31 | } else { 32 | false 33 | } 34 | } 35 | 36 | fn log(&self, record: &log::Record<'_>) { 37 | if record.metadata().level() > self.level_filter { 38 | return; 39 | } 40 | if let Some(target) = self.get_target(record.target()) { 41 | if target.enabled(record.metadata()) { 42 | target.log(record) 43 | } 44 | } 45 | } 46 | 47 | fn flush(&self) {} 48 | } 49 | 50 | pub(crate) struct MultiLogDrain { 51 | default: Option>, 52 | targets: HashMap>, 53 | } 54 | 55 | impl Drain for MultiLogDrain { 56 | fn flush(&mut self) -> Result<(), Error> { 57 | if let Some(ref mut default) = self.default { 58 | default.flush()?; 59 | } 60 | for (_target, log_handle) in self.targets.iter_mut() { 61 | log_handle.flush()?; 62 | } 63 | Ok(()) 64 | } 65 | } 66 | 67 | /// A type to construct a multi-target `AsyncLog` which routes messages based 68 | /// on the log's `target` metadata to a corresponding `AsyncLog`. Targets which 69 | /// do not match a specific target will be routed to the default `AsyncLog` if 70 | /// one is configured. 71 | pub struct MultiLogBuilder { 72 | default: Option, 73 | targets: HashMap, 74 | level_filter: LevelFilter, 75 | } 76 | 77 | impl Default for MultiLogBuilder { 78 | fn default() -> Self { 79 | Self { 80 | default: None, 81 | targets: HashMap::new(), 82 | level_filter: LevelFilter::Trace, 83 | } 84 | } 85 | } 86 | 87 | impl MultiLogBuilder { 88 | /// Create a new MultiLog builder 89 | pub fn new() -> Self { 90 | Default::default() 91 | } 92 | 93 | pub fn default(mut self, log: AsyncLog) -> Self { 94 | self.default = Some(log); 95 | self 96 | } 97 | 98 | pub fn add_target(mut self, target: &str, log: AsyncLog) -> Self { 99 | self.targets.insert(target.to_owned(), log); 100 | self 101 | } 102 | 103 | pub fn level_filter(mut self, level_filter: LevelFilter) -> Self { 104 | self.level_filter = level_filter; 105 | self 106 | } 107 | 108 | pub fn build(mut self) -> AsyncLog { 109 | let mut loggers = MultiLogger { 110 | default: None, 111 | targets: HashMap::new(), 112 | level_filter: self.level_filter, 113 | }; 114 | 115 | let mut drains = MultiLogDrain { 116 | default: None, 117 | targets: HashMap::new(), 118 | }; 119 | 120 | if let Some(log) = self.default.take() { 121 | loggers.default = Some(log.logger); 122 | drains.default = Some(log.drain); 123 | } 124 | 125 | for (name, log) in self.targets.drain() { 126 | loggers.targets.insert(name.to_owned(), log.logger); 127 | drains.targets.insert(name.to_owned(), log.drain); 128 | } 129 | 130 | AsyncLog { 131 | logger: Box::new(loggers), 132 | drain: Box::new(drains), 133 | level_filter: self.level_filter, 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /logger/src/nop.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | use std::io::Error; 7 | 8 | /// Implements a no-op logger which drops all log messages. 9 | pub(crate) struct NopLogger {} 10 | 11 | impl NopLogger { 12 | pub fn level_filter(&self) -> LevelFilter { 13 | LevelFilter::Off 14 | } 15 | } 16 | 17 | impl Log for NopLogger { 18 | fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool { 19 | false 20 | } 21 | 22 | fn log(&self, _record: &log::Record<'_>) {} 23 | 24 | fn flush(&self) {} 25 | } 26 | 27 | /// Implements a no-op drain type which does nothing. 28 | pub(crate) struct NopLogDrain {} 29 | 30 | impl Drain for NopLogDrain { 31 | fn flush(&mut self) -> Result<(), Error> { 32 | Ok(()) 33 | } 34 | } 35 | 36 | /// A type to construct a basic `AsyncLog` which drops all log messages. 37 | pub struct NopLogBuilder {} 38 | 39 | impl Default for NopLogBuilder { 40 | fn default() -> Self { 41 | Self {} 42 | } 43 | } 44 | 45 | impl NopLogBuilder { 46 | /// Create a new log builder. 47 | pub fn new() -> Self { 48 | Default::default() 49 | } 50 | 51 | /// Consumes the builder and returns an `AsyncLog`. 52 | pub fn build(self) -> AsyncLog { 53 | let logger = NopLogger {}; 54 | let drain = NopLogDrain {}; 55 | let level_filter = logger.level_filter(); 56 | AsyncLog { 57 | logger: Box::new(logger), 58 | drain: Box::new(drain), 59 | level_filter, 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /logger/src/outputs.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | use std::io::{BufWriter, Error, Write}; 8 | use std::path::{Path, PathBuf}; 9 | 10 | /// An output that writes to `stdout`. 11 | pub struct Stdout { 12 | writer: BufWriter, 13 | } 14 | 15 | impl Default for Stdout { 16 | fn default() -> Self { 17 | Self::new() 18 | } 19 | } 20 | 21 | impl Stdout { 22 | pub fn new() -> Self { 23 | Self { 24 | writer: BufWriter::new(std::io::stdout()), 25 | } 26 | } 27 | } 28 | 29 | impl Write for Stdout { 30 | fn write(&mut self, buf: &[u8]) -> Result { 31 | self.writer.write(buf) 32 | } 33 | fn flush(&mut self) -> std::result::Result<(), Error> { 34 | self.writer.flush() 35 | } 36 | } 37 | 38 | impl Output for Stdout {} 39 | 40 | /// An output that writes to `stderr`. 41 | pub struct Stderr { 42 | writer: BufWriter, 43 | } 44 | 45 | impl Default for Stderr { 46 | fn default() -> Self { 47 | Self::new() 48 | } 49 | } 50 | 51 | impl Stderr { 52 | pub fn new() -> Self { 53 | Self { 54 | writer: BufWriter::new(std::io::stderr()), 55 | } 56 | } 57 | } 58 | 59 | impl Write for Stderr { 60 | fn write(&mut self, buf: &[u8]) -> Result { 61 | self.writer.write(buf) 62 | } 63 | fn flush(&mut self) -> std::result::Result<(), std::io::Error> { 64 | self.writer.flush() 65 | } 66 | } 67 | 68 | impl Output for Stderr {} 69 | 70 | /// A file based output which allows rotating the current log file off to a 71 | /// backup location. 72 | pub struct File { 73 | active: PathBuf, 74 | backup: PathBuf, 75 | max_size: u64, 76 | writer: BufWriter, 77 | } 78 | 79 | impl File { 80 | /// Create a new file based output. The active path will be the live log 81 | /// file. When the size of the live log is exceeded, it will automatically 82 | /// be rotated to the backup path. 83 | pub fn new>(active: T, backup: T, max_size: u64) -> Result { 84 | LOG_OPEN.increment(); 85 | let file = match std::fs::File::create(active.as_ref()) { 86 | Ok(f) => f, 87 | Err(e) => { 88 | LOG_OPEN_EX.increment(); 89 | return Err(e); 90 | } 91 | }; 92 | let writer = BufWriter::new(file); 93 | Ok(Self { 94 | active: active.as_ref().to_owned(), 95 | backup: backup.as_ref().to_owned(), 96 | max_size, 97 | writer, 98 | }) 99 | } 100 | 101 | /// Return the current size of the live log in bytes. 102 | fn size(&self) -> Result { 103 | Ok(self.writer.get_ref().metadata()?.len()) 104 | } 105 | 106 | /// Rotate the current log file if necessary. 107 | fn rotate(&mut self) -> Result<(), Error> { 108 | let size = self.size()?; 109 | if size >= self.max_size { 110 | // rename the open file 111 | std::fs::rename(&self.active, &self.backup)?; 112 | 113 | // create a new file for the live log 114 | LOG_OPEN.increment(); 115 | let file = match std::fs::File::create(&self.active) { 116 | Ok(f) => f, 117 | Err(e) => { 118 | LOG_OPEN_EX.increment(); 119 | return Err(e); 120 | } 121 | }; 122 | self.writer = BufWriter::new(file); 123 | } 124 | 125 | Ok(()) 126 | } 127 | } 128 | 129 | impl Write for File { 130 | fn write(&mut self, buf: &[u8]) -> Result { 131 | self.writer.write(buf) 132 | } 133 | fn flush(&mut self) -> std::result::Result<(), Error> { 134 | self.writer.flush()?; 135 | self.rotate() 136 | } 137 | } 138 | 139 | impl Output for File {} 140 | -------------------------------------------------------------------------------- /logger/src/sampling.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | use core::sync::atomic::{AtomicUsize, Ordering}; 7 | 8 | /// Implements a logger which only logs 1 in N log messages. 9 | pub(crate) struct SamplingLogger { 10 | logger: Logger, 11 | counter: AtomicUsize, 12 | sample: usize, 13 | } 14 | 15 | impl SamplingLogger { 16 | pub fn level_filter(&self) -> LevelFilter { 17 | self.logger.level_filter() 18 | } 19 | } 20 | 21 | impl Log for SamplingLogger { 22 | fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { 23 | metadata.level() <= self.level_filter() 24 | } 25 | 26 | fn log(&self, record: &log::Record<'_>) { 27 | // If the log message is filtered by the log level, return early. 28 | if !self.enabled(record.metadata()) { 29 | return; 30 | } 31 | 32 | let count = self.counter.fetch_add(1, Ordering::Relaxed); 33 | 34 | // if this is the Nth message, we should log it 35 | if (count % self.sample) == 0 { 36 | self.logger.log(record) 37 | } else { 38 | LOG_SKIP.increment(); 39 | } 40 | } 41 | 42 | fn flush(&self) {} 43 | } 44 | 45 | /// A type to construct a basic `AsyncLog` which routes 1 in N log messages to a 46 | /// single `Output`. 47 | pub struct SamplingLogBuilder { 48 | log_builder: LogBuilder, 49 | sample: usize, 50 | } 51 | 52 | impl Default for SamplingLogBuilder { 53 | fn default() -> Self { 54 | Self { 55 | log_builder: LogBuilder::default(), 56 | sample: 100, 57 | } 58 | } 59 | } 60 | 61 | impl SamplingLogBuilder { 62 | /// Create a new log builder. 63 | pub fn new() -> Self { 64 | Default::default() 65 | } 66 | 67 | /// Sets the depth of the log queue. Deeper queues are less likely to drop 68 | /// messages, but come at the cost of additional memory utilization. 69 | pub fn log_queue_depth(mut self, messages: usize) -> Self { 70 | self.log_builder = self.log_builder.log_queue_depth(messages); 71 | self 72 | } 73 | 74 | /// Sets the buffer size for a single message. Oversized messages will 75 | /// result in an extra allocation, but keeping this small allows deeper 76 | /// queues for the same total buffer size without dropping log messages. 77 | pub fn single_message_size(mut self, bytes: usize) -> Self { 78 | self.log_builder = self.log_builder.single_message_size(bytes); 79 | self 80 | } 81 | 82 | /// Sets the output for the logger. 83 | pub fn output(mut self, output: Box) -> Self { 84 | self.log_builder = self.log_builder.output(output); 85 | self 86 | } 87 | 88 | /// Sets the format function to be used to format messages to this log. 89 | pub fn format(mut self, format: FormatFunction) -> Self { 90 | self.log_builder = self.log_builder.format(format); 91 | self 92 | } 93 | 94 | /// Sets the sampling to 1 in N requests 95 | pub fn sample(mut self, sample: usize) -> Self { 96 | self.sample = sample; 97 | self 98 | } 99 | 100 | /// Consumes the builder and returns a configured `SamplingLogger` and `LogDrain`. 101 | pub(crate) fn build_raw(self) -> Result<(SamplingLogger, LogDrain), &'static str> { 102 | let (logger, log_handle) = self.log_builder.build_raw()?; 103 | let logger = SamplingLogger { 104 | logger, 105 | // initialize to 1 not 0 so the first fetch_add returns a 1 106 | counter: AtomicUsize::new(1), 107 | sample: self.sample, 108 | }; 109 | Ok((logger, log_handle)) 110 | } 111 | 112 | /// Consumes the builder and returns an `AsyncLog`. 113 | pub fn build(self) -> Result { 114 | let (logger, drain) = self.build_raw()?; 115 | let level_filter = logger.level_filter(); 116 | Ok(AsyncLog { 117 | logger: Box::new(logger), 118 | drain: Box::new(drain), 119 | level_filter, 120 | }) 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /logger/src/traits.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use std::io::{Error, Write}; 6 | 7 | /// An `Output` is a logging destination, for example, standard out or a file. 8 | pub trait Output: Write + Send + Sync {} 9 | 10 | /// A `Drain` serves to receive log messages from a queue and flush them to an 11 | /// `Output`. 12 | pub trait Drain: Send { 13 | /// Flushes log messages from the queue to the `Output` for this `Drain`. 14 | /// This function must be called periodically to ensure there is capacity on 15 | /// the queue for new log messages. It is recommended that this function is 16 | /// called outside of any critical paths. For example, offloading to an 17 | /// admin thread or dedicated logging thread. 18 | fn flush(&mut self) -> Result<(), Error>; 19 | } 20 | -------------------------------------------------------------------------------- /metrics/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-metrics" 3 | version = "0.1.2" 4 | edition = "2021" 5 | authors = ["Sean Lynch "] 6 | license = "Apache-2.0" 7 | 8 | [dependencies] 9 | linkme = "0.3.3" 10 | once_cell = "1.14.0" 11 | parking_lot = "0.12.1" 12 | 13 | rustcommon-metrics-derive = { path = "derive" } 14 | heatmap = { path = "../heatmap" } 15 | rustcommon-time = { path = "../time" } 16 | -------------------------------------------------------------------------------- /metrics/derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-metrics-derive" 3 | version = "0.1.1" 4 | edition = "2018" 5 | authors = ["Sean Lynch "] 6 | license = "Apache-2.0" 7 | 8 | [lib] 9 | proc-macro = true 10 | 11 | [dependencies] 12 | proc-macro2 = "1.0.39" 13 | proc-macro-crate = "1.0.0" 14 | quote = "1.0.9" 15 | syn = { version = "1.0.95", features = ["full", "parsing"] } 16 | -------------------------------------------------------------------------------- /metrics/derive/src/args.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use quote::ToTokens; 6 | use std::fmt::{Display, Formatter, Result}; 7 | use syn::parse::{Parse, ParseStream}; 8 | use syn::{Ident, Token}; 9 | 10 | #[derive(Clone)] 11 | pub(crate) enum ArgName { 12 | Ident(Ident), 13 | Crate(Token![crate]), 14 | } 15 | 16 | impl Parse for ArgName { 17 | fn parse(input: ParseStream) -> syn::Result { 18 | let lookahead = input.lookahead1(); 19 | Ok(match () { 20 | _ if lookahead.peek(Ident) => Self::Ident(input.parse()?), 21 | _ if lookahead.peek(Token![crate]) => Self::Crate(input.parse()?), 22 | _ => return Err(lookahead.error()), 23 | }) 24 | } 25 | } 26 | 27 | impl ToTokens for ArgName { 28 | fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { 29 | use self::ArgName::*; 30 | 31 | match self { 32 | Ident(ident) => ident.to_tokens(tokens), 33 | Crate(krate) => krate.to_tokens(tokens), 34 | } 35 | } 36 | } 37 | 38 | impl Display for ArgName { 39 | fn fmt(&self, f: &mut Formatter<'_>) -> Result { 40 | use self::ArgName::*; 41 | 42 | match self { 43 | Ident(ident) => ident.fmt(f), 44 | Crate(_) => f.write_str("crate"), 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /metrics/derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use proc_macro::TokenStream; 6 | use quote::quote; 7 | use syn::Ident; 8 | 9 | mod args; 10 | mod metric; 11 | 12 | /// Declare a global metric that can be accessed via the `metrics` method. 13 | /// 14 | /// Note that this will change the type of the generated static to be 15 | /// `MetricInstance`. It implements both [`Deref`] and [`DerefMut`] 16 | /// so it can be used much the same as a normal static. 17 | /// 18 | /// # Parameters 19 | /// - (optional) `name`: The string name that the metric should be exposed as. 20 | /// If not specified then the default name is one based on the path to the 21 | /// metric along with its name. 22 | /// - (optional) `crate`: The path to the `rustcommon_metrics` crate. This 23 | /// allows the `metric` macro to be used within other macros that get exported 24 | /// to third-party crates which may not have added `rustcommon_metrics` to 25 | /// their Cargo.toml. 26 | /// - (optional) `description`: A textual description of the metric. If not 27 | /// specified, or specified as a blank string then defaults to None 28 | /// 29 | /// [`Deref`]: std::ops::Deref 30 | /// [`DerefMut`]: std::ops::DerefMut 31 | #[proc_macro_attribute] 32 | pub fn metric(attr: TokenStream, item: TokenStream) -> TokenStream { 33 | match metric::metric(attr, item) { 34 | Ok(tokens) => tokens.into(), 35 | Err(e) => e.to_compile_error().into(), 36 | } 37 | } 38 | 39 | /// This macro statically converts an ident to a lowercased string 40 | /// at compile time. 41 | /// 42 | /// In the future this could be replaced with some const code. However, 43 | /// `std::str::from_utf8_unchecked` is not stably const just yet so we 44 | /// need this macro as a workaround. 45 | #[proc_macro] 46 | pub fn to_lowercase(input: TokenStream) -> TokenStream { 47 | let ident = syn::parse_macro_input!(input as Ident); 48 | let name = ident.to_string().to_ascii_lowercase(); 49 | let literal = syn::LitStr::new(&name, ident.span()); 50 | let tokens = quote! { #literal }; 51 | 52 | tokens.into() 53 | } 54 | -------------------------------------------------------------------------------- /metrics/src/counter.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::Metric; 6 | use std::any::Any; 7 | use std::sync::atomic::{AtomicU64, Ordering}; 8 | 9 | /// A counter. Can be incremented or added to. 10 | /// 11 | /// In case of overflow the counter will wrap around. However, internally it 12 | /// uses an unsigned 64-bit integer so for most use cases this should be 13 | /// unlikely. 14 | /// 15 | /// # Example 16 | /// ``` 17 | /// # use rustcommon_metrics::{metric, Counter}; 18 | /// #[metric(name = "my.custom.metric")] 19 | /// static MY_COUNTER: Counter = Counter::new(); 20 | /// 21 | /// fn a_method() { 22 | /// MY_COUNTER.increment(); 23 | /// // ... 24 | /// } 25 | /// # a_method(); 26 | /// ``` 27 | #[derive(Default, Debug)] 28 | pub struct Counter(AtomicU64); 29 | 30 | impl Counter { 31 | /// Create a counter initialized to 0. 32 | pub const fn new() -> Self { 33 | Self::with_value(0) 34 | } 35 | 36 | /// Create a counter initialized to `value`. 37 | pub const fn with_value(value: u64) -> Self { 38 | Self(AtomicU64::new(value)) 39 | } 40 | 41 | #[inline] 42 | pub fn increment(&self) -> u64 { 43 | self.add(1) 44 | } 45 | 46 | #[inline] 47 | pub fn add(&self, value: u64) -> u64 { 48 | self.0.fetch_add(value, Ordering::Relaxed) 49 | } 50 | 51 | #[inline] 52 | pub fn value(&self) -> u64 { 53 | self.0.load(Ordering::Relaxed) 54 | } 55 | 56 | #[inline] 57 | pub fn set(&self, value: u64) -> u64 { 58 | self.0.swap(value, Ordering::Relaxed) 59 | } 60 | 61 | #[inline] 62 | pub fn reset(&self) -> u64 { 63 | self.set(0) 64 | } 65 | } 66 | 67 | impl Metric for Counter { 68 | fn as_any(&self) -> Option<&dyn Any> { 69 | Some(self) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /metrics/src/gauge.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::Metric; 6 | use std::any::Any; 7 | use std::sync::atomic::{AtomicI64, Ordering}; 8 | 9 | /// A gauge. Indicates the current value of some host parameter. 10 | /// 11 | /// In case of overflow/underflow the gauge will wrap around. However, 12 | /// internally it uses a signed 64-bit integer so for most use cases this should 13 | /// be unlikely. 14 | /// 15 | /// # Example 16 | /// ``` 17 | /// # use rustcommon_metrics::{metric, Gauge}; 18 | /// #[metric(name = "my.gauge")] 19 | /// static A_METHOD_RUNNING: Gauge = Gauge::new(); 20 | /// 21 | /// fn a_method() { 22 | /// A_METHOD_RUNNING.increment(); 23 | /// // ... 24 | /// A_METHOD_RUNNING.decrement(); 25 | /// } 26 | /// # a_method(); 27 | /// ``` 28 | #[derive(Default, Debug)] 29 | pub struct Gauge(AtomicI64); 30 | 31 | impl Gauge { 32 | /// Create a new guage with the default value of 0. 33 | pub const fn new() -> Self { 34 | Self::with_value(0) 35 | } 36 | 37 | /// Create a new guage with the provided initial value. 38 | pub const fn with_value(value: i64) -> Self { 39 | Self(AtomicI64::new(value)) 40 | } 41 | 42 | /// Increment the value of this gauge by 1. 43 | /// 44 | /// Returns the old value of the gauge. 45 | #[inline] 46 | pub fn increment(&self) -> i64 { 47 | self.add(1) 48 | } 49 | 50 | /// Decrement the value of this gauge by 1. 51 | /// 52 | /// Returns the old value of the gauge. 53 | #[inline] 54 | pub fn decrement(&self) -> i64 { 55 | self.sub(1) 56 | } 57 | 58 | /// Increase the value of this gauge by `value`. 59 | /// 60 | /// Returns the od value of the gauge. 61 | #[inline] 62 | pub fn add(&self, value: i64) -> i64 { 63 | self.0.fetch_add(value, Ordering::Relaxed) 64 | } 65 | 66 | /// Decrease the value of this gauge by `value`. 67 | /// 68 | /// Returns the od value of the gauge. 69 | #[inline] 70 | pub fn sub(&self, value: i64) -> i64 { 71 | self.0.fetch_sub(value, Ordering::Relaxed) 72 | } 73 | 74 | #[inline] 75 | pub fn value(&self) -> i64 { 76 | self.0.load(Ordering::Relaxed) 77 | } 78 | 79 | #[inline] 80 | pub fn set(&self, value: i64) -> i64 { 81 | self.0.swap(value, Ordering::Relaxed) 82 | } 83 | 84 | #[inline] 85 | pub fn reset(&self) -> i64 { 86 | self.set(0) 87 | } 88 | } 89 | 90 | impl Metric for Gauge { 91 | fn as_any(&self) -> Option<&dyn Any> { 92 | Some(self) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /metrics/src/heatmap.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::Metric; 6 | 7 | pub use heatmap::Heatmap; 8 | 9 | impl Metric for Heatmap { 10 | fn as_any(&self) -> Option<&dyn std::any::Any> { 11 | Some(self) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /metrics/src/lazy.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::Metric; 6 | use once_cell::sync::OnceCell; 7 | use std::cell::Cell; 8 | use std::ops::{Deref, DerefMut}; 9 | 10 | // Note: This implementation is mostly copied from the Lazy implementation 11 | // within once_cell. It only adds the `get` option to try to access 12 | // the value without initializing the Lazy instance. 13 | // 14 | // This should be replaced with the new primitives in std::lazy once 15 | // those stabilize. 16 | 17 | /// A value which is initialized on the first access. 18 | /// 19 | /// This type is thread-safe and can be used in statics. 20 | /// 21 | /// # Example 22 | /// In this example, [`Heatmap`] does not have a const `new` function so it 23 | /// must be constructed using [`Lazy`]. 24 | /// ``` 25 | /// # #[cfg(feature = "heatmap")] 26 | /// # fn main() { 27 | /// # use rustcommon_metrics::*; 28 | /// #[metric] 29 | /// static HEATMAP: Lazy = Lazy::new(|| { 30 | /// Heatmap::new( 31 | /// 100, 32 | /// 2, 33 | /// Duration::>::from_secs(30), 34 | /// Duration::>::from_secs(1), 35 | /// ) 36 | /// }); 37 | /// # } 38 | /// # #[cfg(not(feature = "heatmap"))] fn main() {} 39 | /// ``` 40 | /// 41 | /// [`Heatmap`]: crate::Heatmap; 42 | pub struct Lazy T> { 43 | cell: OnceCell, 44 | func: Cell>, 45 | } 46 | 47 | unsafe impl Sync for Lazy where OnceCell: Sync {} 48 | 49 | impl Lazy { 50 | /// Create a new lazy value with the given initializing function. 51 | pub const fn new(func: F) -> Self { 52 | Self { 53 | cell: OnceCell::new(), 54 | func: Cell::new(Some(func)), 55 | } 56 | } 57 | 58 | /// If this lazy has been initialized, then return a reference to the 59 | /// contained value. 60 | pub fn get(this: &Self) -> Option<&T> { 61 | this.cell.get() 62 | } 63 | 64 | /// If this lazy has been initialized, then return a reference to the 65 | /// contained value. 66 | pub fn get_mut(this: &mut Self) -> Option<&mut T> { 67 | this.cell.get_mut() 68 | } 69 | } 70 | 71 | impl T> Lazy { 72 | /// Force the evaluation of this lazy value and return a reference to 73 | /// the result. This is equivalent to the `Deref` impl. 74 | pub fn force(this: &Self) -> &T { 75 | this.cell.get_or_init(|| { 76 | let func = this 77 | .func 78 | .take() 79 | .unwrap_or_else(|| panic!("Lazy instance has previously been poisoned")); 80 | 81 | func() 82 | }) 83 | } 84 | } 85 | 86 | impl T> Deref for Lazy { 87 | type Target = T; 88 | 89 | fn deref(&self) -> &Self::Target { 90 | Self::force(self) 91 | } 92 | } 93 | 94 | impl T> DerefMut for Lazy { 95 | fn deref_mut(&mut self) -> &mut Self::Target { 96 | Self::force(self); 97 | self.cell.get_mut().unwrap_or_else(|| unreachable!()) 98 | } 99 | } 100 | 101 | impl Default for Lazy { 102 | /// Create a new lazy value using `default` as the initializing function. 103 | fn default() -> Self { 104 | Self::new(T::default) 105 | } 106 | } 107 | 108 | impl Metric for Lazy { 109 | fn is_enabled(&self) -> bool { 110 | Lazy::get(self).is_some() 111 | } 112 | 113 | fn as_any(&self) -> Option<&dyn std::any::Any> { 114 | match Lazy::get(self) { 115 | Some(metric) => Some(metric), 116 | None => None, 117 | } 118 | } 119 | } 120 | 121 | /// A value which is initialized on the first access. 122 | /// 123 | /// The difference between [`Relaxed`] type and [`Lazy`], however, is that it is 124 | /// also initialized if accessed via the global metrics array. This means that 125 | /// it will always show up in exported metrics whereas [`Lazy`] will not. 126 | pub struct Relaxed T> { 127 | cell: Lazy, 128 | } 129 | 130 | impl Relaxed { 131 | /// Create a new lazy value with the given initializing function. 132 | pub const fn new(func: F) -> Self { 133 | Self { 134 | cell: Lazy::new(func), 135 | } 136 | } 137 | 138 | /// If this cell has been initialized, then return a reference to the 139 | /// contained value. 140 | pub fn get(this: &Self) -> Option<&T> { 141 | Lazy::get(&this.cell) 142 | } 143 | 144 | /// If this cell has been initialized, then return a reference to the 145 | /// contained value. 146 | pub fn get_mut(this: &mut Self) -> Option<&mut T> { 147 | Lazy::get_mut(&mut this.cell) 148 | } 149 | } 150 | 151 | impl T> Relaxed { 152 | /// Force the evaluation of this lazy value and return a reference to 153 | /// the result. This is equivalent to the `Deref` impl. 154 | pub fn force(this: &Self) -> &T { 155 | Lazy::force(&this.cell) 156 | } 157 | } 158 | 159 | impl T> Deref for Relaxed { 160 | type Target = T; 161 | 162 | fn deref(&self) -> &Self::Target { 163 | Self::force(self) 164 | } 165 | } 166 | 167 | impl T> DerefMut for Relaxed { 168 | fn deref_mut(&mut self) -> &mut Self::Target { 169 | Self::force(self); 170 | Lazy::get_mut(&mut self.cell).unwrap_or_else(|| unreachable!()) 171 | } 172 | } 173 | 174 | impl Default for Relaxed { 175 | /// Create a new lazy value using `default` as the initializing function. 176 | fn default() -> Self { 177 | Self::new(T::default) 178 | } 179 | } 180 | 181 | impl Metric for Relaxed 182 | where 183 | T: Metric, 184 | F: (FnOnce() -> T) + Send + 'static, 185 | { 186 | fn as_any(&self) -> Option<&dyn std::any::Any> { 187 | Some(Self::force(self)) 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /metrics/tests/alternate_crate.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | mod bonus { 6 | pub use rustcommon_metrics::*; 7 | } 8 | 9 | use bonus::Counter; 10 | 11 | #[bonus::metric(name = "test", description = "foobar", crate = crate::bonus)] 12 | static METRIC: Counter = Counter::new(); 13 | 14 | macro_rules! metric_in_macro { 15 | () => { 16 | #[$crate::bonus::metric(crate = $crate::bonus)] 17 | static OTHER_METRIC: Counter = Counter::new(); 18 | }; 19 | } 20 | 21 | metric_in_macro!(); 22 | -------------------------------------------------------------------------------- /metrics/tests/described_metrics.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use rustcommon_metrics::*; 6 | 7 | #[metric(description = "some metric with a description")] 8 | static METRIC_WITH_DESCRIPTION_NO_NAME: Counter = Counter::new(); 9 | 10 | #[metric(description = "")] 11 | static METRIC_WITH_BLANK_DESCRIPTION: Counter = Counter::new(); 12 | 13 | #[test] 14 | fn metric_description_as_expected_when_only_description_set() { 15 | let metrics = metrics().static_metrics(); 16 | assert_eq!(metrics.len(), 2); 17 | assert_eq!( 18 | metrics[1].description(), 19 | Some("some metric with a description") 20 | ); 21 | } 22 | 23 | #[test] 24 | fn metric_description_as_expected_when_only_description_set_to_blank() { 25 | let metrics = metrics().static_metrics(); 26 | assert_eq!(metrics.len(), 2); 27 | assert_eq!(metrics[0].description(), None); 28 | } 29 | -------------------------------------------------------------------------------- /metrics/tests/dynmetrics.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use parking_lot::{Mutex, MutexGuard}; 6 | use std::mem::ManuallyDrop; 7 | use std::pin::Pin; 8 | 9 | use rustcommon_metrics::*; 10 | 11 | // All tests manipulate global state. Need a mutex to ensure test execution 12 | // doesn't overlap. 13 | static TEST_MUTEX: Mutex<()> = parking_lot::const_mutex(()); 14 | 15 | /// RAII guard that ensures 16 | /// - All dynamic metrics are removed after each test 17 | /// - No two tests run concurrently 18 | struct TestGuard { 19 | _lock: MutexGuard<'static, ()>, 20 | } 21 | 22 | impl TestGuard { 23 | pub fn new() -> Self { 24 | Self { 25 | _lock: TEST_MUTEX.lock(), 26 | } 27 | } 28 | } 29 | 30 | impl Drop for TestGuard { 31 | fn drop(&mut self) { 32 | let to_unregister = metrics() 33 | .dynamic_metrics() 34 | .iter() 35 | .map(|entry| entry.metric() as *const dyn Metric) 36 | .collect::>(); 37 | 38 | for metric in to_unregister { 39 | dynmetrics::unregister(metric); 40 | } 41 | } 42 | } 43 | 44 | #[test] 45 | fn register_unregister() { 46 | let _guard = TestGuard::new(); 47 | 48 | let metric = Counter::new(); 49 | let entry = unsafe { MetricEntry::new_unchecked(&metric, "register_unregister".into()) }; 50 | 51 | dynmetrics::register(entry); 52 | 53 | assert_eq!(metrics().dynamic_metrics().len(), 1); 54 | dynmetrics::unregister(&metric); 55 | assert_eq!(metrics().dynamic_metrics().len(), 0); 56 | } 57 | 58 | #[test] 59 | fn wrapped_register_unregister() { 60 | let _guard = TestGuard::new(); 61 | 62 | let metric = DynBoxedMetric::new(Counter::new(), "wrapped_register_unregister"); 63 | 64 | assert_eq!(metrics().dynamic_metrics().len(), 1); 65 | drop(metric); 66 | assert_eq!(metrics().dynamic_metrics().len(), 0); 67 | } 68 | 69 | #[test] 70 | fn pinned_register_unregister() { 71 | let _guard = TestGuard::new(); 72 | 73 | let mut metric_ = ManuallyDrop::new(DynPinnedMetric::new(Counter::new())); 74 | let metric = unsafe { Pin::new_unchecked(&*metric_) }; 75 | metric.register("pinned_register_unregister"); 76 | 77 | assert_eq!(metrics().dynamic_metrics().len(), 1); 78 | unsafe { ManuallyDrop::drop(&mut metric_) }; 79 | assert_eq!(metrics().dynamic_metrics().len(), 0); 80 | } 81 | 82 | #[test] 83 | fn pinned_scope() { 84 | let _guard = TestGuard::new(); 85 | 86 | { 87 | let metric = DynPinnedMetric::new(Counter::new()); 88 | let metric = unsafe { Pin::new_unchecked(&metric) }; 89 | metric.register("pinned_scope"); 90 | 91 | assert_eq!(metrics().dynamic_metrics().len(), 1); 92 | } 93 | assert_eq!(metrics().dynamic_metrics().len(), 0); 94 | } 95 | 96 | #[test] 97 | fn pinned_dup_register() { 98 | let _guard = TestGuard::new(); 99 | 100 | { 101 | let metric = DynPinnedMetric::new(Counter::new()); 102 | let metric = unsafe { Pin::new_unchecked(&metric) }; 103 | metric.register("pinned_dup_1"); 104 | metric.register("pinned_dup_2"); 105 | 106 | assert_eq!(metrics().dynamic_metrics().len(), 2); 107 | } 108 | assert_eq!(metrics().dynamic_metrics().len(), 0); 109 | } 110 | 111 | #[test] 112 | fn multi_metric() { 113 | let _guard = TestGuard::new(); 114 | 115 | let m1 = DynBoxedMetric::new(Counter::new(), "multi_metric_1"); 116 | let m2 = DynBoxedMetric::new(Counter::new(), "multi_metric_2"); 117 | 118 | assert_eq!(metrics().dynamic_metrics().len(), 2); 119 | drop(m1); 120 | assert_eq!(metrics().dynamic_metrics().len(), 1); 121 | drop(m2); 122 | assert_eq!(metrics().dynamic_metrics().len(), 0); 123 | } 124 | -------------------------------------------------------------------------------- /metrics/tests/heatmap.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use rustcommon_metrics::{heatmap, metrics}; 6 | 7 | heatmap!(LATENCY, 1_000_000_000); 8 | heatmap!(CARDINALITY, 1_000, "some description"); 9 | 10 | #[test] 11 | fn metric_name_as_expected() { 12 | let metrics = metrics().static_metrics(); 13 | assert_eq!(metrics.len(), 2); 14 | assert_eq!(metrics[1].name(), "latency"); 15 | assert_eq!(metrics[1].description(), None); 16 | } 17 | 18 | #[test] 19 | fn metric_name_and_description_as_expected() { 20 | let metrics = metrics().static_metrics(); 21 | assert_eq!(metrics.len(), 2); 22 | assert_eq!(metrics[0].name(), "cardinality"); 23 | assert_eq!(metrics[0].description(), Some("some description")); 24 | } 25 | -------------------------------------------------------------------------------- /metrics/tests/metric_macros.rs: -------------------------------------------------------------------------------- 1 | use rustcommon_metrics::{counter, gauge, heatmap}; 2 | 3 | counter!(A_COUNTER); 4 | gauge!(A_GAUGE); 5 | heatmap!(A_HEATMAP, 50); 6 | 7 | #[test] 8 | fn metrics_are_present() { 9 | let metrics = rustcommon_metrics::metrics(); 10 | let metrics = metrics.static_metrics(); 11 | 12 | assert_eq!(metrics.len(), 3); 13 | assert!(metrics.iter().any(|metric| metric.name() == "a_counter")); 14 | assert!(metrics.iter().any(|metric| metric.name() == "a_gauge")); 15 | assert!(metrics.iter().any(|metric| metric.name() == "a_heatmap")); 16 | } 17 | -------------------------------------------------------------------------------- /metrics/tests/named_metric.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use rustcommon_metrics::*; 6 | 7 | #[metric(name = "custom-name")] 8 | static METRIC: Counter = Counter::new(); 9 | 10 | #[metric( 11 | name = "custom-name-with-description", 12 | description = "some metric with a description" 13 | )] 14 | static METRIC_WITH_DESCRIPTION: Counter = Counter::new(); 15 | 16 | #[test] 17 | fn metric_name_as_expected() { 18 | let metrics = metrics().static_metrics(); 19 | assert_eq!(metrics.len(), 2); 20 | assert_eq!(metrics[1].name(), "custom-name"); 21 | assert_eq!(metrics[1].description(), None); 22 | } 23 | 24 | #[test] 25 | fn metric_name_and_description_as_expected() { 26 | let metrics = metrics().static_metrics(); 27 | assert_eq!(metrics.len(), 2); 28 | assert_eq!(metrics[0].name(), "custom-name-with-description"); 29 | assert_eq!( 30 | metrics[0].description(), 31 | Some("some metric with a description") 32 | ); 33 | } 34 | -------------------------------------------------------------------------------- /metrics/tests/namespaced_metric.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use rustcommon_metrics::*; 6 | 7 | #[metric(name = "pid")] 8 | static PID: Gauge = Gauge::new(); 9 | 10 | #[metric(name = "composed/response", namespace = "server")] 11 | static COMPOSED_RESPONSE: Counter = Counter::new(); 12 | 13 | #[test] 14 | fn without_namespace() { 15 | let metrics = metrics().static_metrics(); 16 | assert_eq!(metrics.len(), 2); 17 | assert_eq!(metrics[1].name(), "pid"); 18 | assert_eq!(metrics[1].namespace(), None); 19 | } 20 | 21 | #[test] 22 | fn with_namespace() { 23 | let metrics = metrics().static_metrics(); 24 | assert_eq!(metrics.len(), 2); 25 | assert_eq!(metrics[0].name(), "composed/response"); 26 | assert_eq!(metrics[0].namespace(), Some("server")); 27 | } 28 | -------------------------------------------------------------------------------- /metrics/tests/unnamed_metric.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use rustcommon_metrics::*; 6 | 7 | #[metric] 8 | static TEST_METRIC: Counter = Counter::new(); 9 | 10 | #[test] 11 | fn metric_name_as_expected() { 12 | let metrics = metrics().static_metrics(); 13 | 14 | assert_eq!(metrics.len(), 1); 15 | assert_eq!( 16 | metrics[0].name(), 17 | concat!(module_path!(), "::", "TEST_METRIC") 18 | ); 19 | } 20 | -------------------------------------------------------------------------------- /ratelimiter/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Unreleased 2 | 3 | # 1.0.0 - 2019-12-13 4 | 5 | Initial release. 6 | -------------------------------------------------------------------------------- /ratelimiter/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-ratelimiter" 3 | version = "1.1.1" 4 | authors = ["Brian Martin "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | description = "Token bucket ratelimiter" 8 | homepage = "https://github.com/twitter/rustcommon/ratelimiter" 9 | repository = "https://github.com/twitter/rustcommon" 10 | 11 | [dependencies] 12 | rand = "0.8.5" 13 | rand_distr = "0.4.3" 14 | rustcommon-time = { path = "../time" } 15 | -------------------------------------------------------------------------------- /ratelimiter/README.md: -------------------------------------------------------------------------------- 1 | # rustcommon-ratelimiter 2 | 3 | Token bucket ratelimiting with various refill strategies 4 | 5 | ## Overview 6 | 7 | This crate provides token bucket ratelimiting implementations. The typical 8 | use-case would be to control the rate of requests or other actions. 9 | 10 | This particular implementation allows for setting a refill strategy for the 11 | token bucket. This allows for creating noise in the interval between additions 12 | of tokens into the bucket. By doing this, we can create workloads that are 13 | bursty and can more closely mirror production workload characteristics. 14 | 15 | ## Getting Started 16 | 17 | ### Building 18 | 19 | rustcommon is built with the standard Rust toolchain which can be installed and 20 | managed via [rustup](https://rustup.rs) or by following the directions on the 21 | Rust [website](https://www.rust-lang.org/). 22 | 23 | #### View library documentation 24 | ```bash 25 | cargo doc --open 26 | ``` 27 | 28 | ## Support 29 | 30 | Create a [new issue](https://github.com/twitter/rustcommon/issues/new) on GitHub. 31 | 32 | ## Contributing 33 | 34 | We feel that a welcoming community is important and we ask that you follow 35 | Twitter's [Open Source Code of Conduct] in all interactions with the community. 36 | 37 | ## Authors 38 | 39 | * Brian Martin 40 | 41 | A full list of [contributors] can be found on GitHub. 42 | 43 | Follow [@TwitterOSS](https://twitter.com/twitteross) on Twitter for updates. 44 | 45 | ## License 46 | 47 | Copyright 2019-2020 Twitter, Inc. 48 | 49 | Licensed under the Apache License, Version 2.0: 50 | https://www.apache.org/licenses/LICENSE-2.0 51 | 52 | ## Security Issues? 53 | 54 | Please report sensitive security issues via Twitter's bug-bounty program 55 | (https://hackerone.com/twitter) rather than GitHub. 56 | 57 | [contributors]: https://github.com/twitter/rustcommon/graphs/contributors?type=a 58 | [Open Source Code of Conduct]: https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md 59 | -------------------------------------------------------------------------------- /ratelimiter/examples/blastoff.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use rustcommon_ratelimiter::Ratelimiter; 6 | use rustcommon_time::{DateTime, SecondsFormat}; 7 | 8 | fn main() { 9 | let limiter = Ratelimiter::new(1, 1, 1); 10 | for i in 0..10 { 11 | limiter.wait(); 12 | println!( 13 | "{}: T -{}", 14 | DateTime::now().to_rfc3339_opts(SecondsFormat::Millis, false), 15 | 10 - i 16 | ); 17 | } 18 | limiter.wait(); 19 | println!("Ignition"); 20 | } 21 | -------------------------------------------------------------------------------- /ratelimiter/examples/bursty.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use rustcommon_ratelimiter::{Ratelimiter, Refill}; 6 | use rustcommon_time::{DateTime, SecondsFormat}; 7 | 8 | fn main() { 9 | for strategy in &[Refill::Normal, Refill::Uniform] { 10 | println!("strategy: {:?}", strategy); 11 | let limiter = Ratelimiter::new(1, 1, 1); 12 | limiter.set_strategy(*strategy); 13 | for i in 0..10 { 14 | limiter.wait(); 15 | println!( 16 | "{}: T -{}", 17 | DateTime::now().to_rfc3339_opts(SecondsFormat::Millis, false), 18 | 10 - i 19 | ); 20 | } 21 | limiter.wait(); 22 | println!(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /streamstats/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-streamstats" 3 | version = "0.1.2" 4 | authors = ["Brian Martin "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | description = "Statistics calculated for a stream of samples" 8 | homepage = "https://github.com/twitter/rustcommon/streamstats" 9 | repository = "https://github.com/twitter/rustcommon" 10 | 11 | [dependencies] 12 | rustcommon-atomics = { path = "../atomics" } 13 | thiserror = "1.0.34" 14 | -------------------------------------------------------------------------------- /time/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-time" 3 | version = "0.0.13" 4 | authors = ["Brian Martin "] 5 | edition = "2021" 6 | description = "Library for getting current and recent timestamps" 7 | homepage = "https://github.com/twitter/rustcommon" 8 | repository = "https://github.com/twitter/rustcommon" 9 | license = "Apache-2.0" 10 | 11 | [dependencies] 12 | libc = "0.2.132" 13 | time = { version = "0.3.14", features = ["formatting"] } 14 | 15 | [target.'cfg(windows)'.dependencies] 16 | lazy_static = "1.4.0" 17 | winapi = { version = "0.3.9", features = ["profileapi", "sysinfoapi"] } 18 | 19 | [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] 20 | mach = "0.3.2" 21 | 22 | [target.'cfg(all(not(windows), not(unix), not(target_os = "macos"), not(target_os = "ios")))'.dependencies] 23 | lazy_static = "1.4.0" 24 | 25 | [dev-dependencies] 26 | criterion = "0.3.6" 27 | 28 | [[bench]] 29 | name = "benches" 30 | harness = false 31 | -------------------------------------------------------------------------------- /time/benches/benches.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use criterion::Throughput; 6 | use criterion::{criterion_group, criterion_main, Criterion}; 7 | use rustcommon_time::*; 8 | 9 | fn instant_seconds_u32(c: &mut Criterion) { 10 | let mut group = c.benchmark_group("Instant>"); 11 | 12 | group.throughput(Throughput::Elements(1)); 13 | group.bench_function("now", |b| b.iter(UnixInstant::>::now)); 14 | group.bench_function("recent", |b| b.iter(UnixInstant::>::recent)); 15 | } 16 | 17 | fn instant_nanoseconds_u64(c: &mut Criterion) { 18 | let mut group = c.benchmark_group("Instant>"); 19 | 20 | group.throughput(Throughput::Elements(1)); 21 | group.bench_function("now", |b| b.iter(UnixInstant::>::now)); 22 | group.bench_function("recent", |b| { 23 | b.iter(UnixInstant::>::recent) 24 | }); 25 | } 26 | 27 | fn datetime(c: &mut Criterion) { 28 | let mut group = c.benchmark_group("DateTime"); 29 | 30 | group.throughput(Throughput::Elements(1)); 31 | group.bench_function("now", |b| b.iter(DateTime::now)); 32 | group.bench_function("recent", |b| b.iter(DateTime::recent)); 33 | } 34 | 35 | fn refresh(c: &mut Criterion) { 36 | let mut group = c.benchmark_group("Clock"); 37 | 38 | group.throughput(Throughput::Elements(1)); 39 | group.bench_function("refresh", |b| b.iter(refresh_clock)); 40 | } 41 | 42 | criterion_group!( 43 | benches, 44 | instant_seconds_u32, 45 | instant_nanoseconds_u64, 46 | datetime, 47 | refresh 48 | ); 49 | criterion_main!(benches); 50 | -------------------------------------------------------------------------------- /time/examples/demo.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use rustcommon_time::*; 6 | 7 | type PreciseInstant = Instant>; 8 | type CoarseInstant = Instant>; 9 | type PreciseUnix = UnixInstant>; 10 | type CoarseUnix = UnixInstant>; 11 | 12 | pub fn main() { 13 | println!("precise: {:?}", PreciseInstant::recent()); 14 | println!("coarse: {:?}", CoarseInstant::recent()); 15 | println!("unix precise: {:?}", PreciseUnix::recent()); 16 | println!("unix coarse: {:?}", CoarseUnix::recent()); 17 | println!("utc: {}", DateTime::recent()); 18 | std::thread::sleep(core::time::Duration::from_millis(50)); 19 | refresh_clock(); 20 | println!("precise: {:?}", PreciseInstant::recent()); 21 | println!("coarse: {:?}", CoarseInstant::recent()); 22 | println!("unix precise: {:?}", PreciseUnix::recent()); 23 | println!("unix coarse: {:?}", CoarseUnix::recent()); 24 | println!("utc: {}", DateTime::recent()); 25 | } 26 | -------------------------------------------------------------------------------- /time/src/datetime.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | use time::OffsetDateTime; 8 | 9 | pub enum SecondsFormat { 10 | Secs, 11 | Millis, 12 | Micros, 13 | Nanos, 14 | } 15 | 16 | #[derive(Copy, Clone)] 17 | /// Represents a fixed moment in time in a format that has a human 18 | /// representation. 19 | /// 20 | /// It is important to note that the underlying clock is subject to phase and 21 | /// frequency adjustments. This means that it is not guaranteed to be stable or 22 | /// monotonically non-decreasing. 23 | pub struct DateTime { 24 | pub(crate) inner: OffsetDateTime, 25 | } 26 | 27 | impl From>> for DateTime { 28 | fn from(other: UnixInstant>) -> Self { 29 | let seconds = other.inner.inner / NANOS_PER_SEC; 30 | let nanoseconds = other.inner.inner % NANOS_PER_SEC; 31 | DateTime { 32 | inner: OffsetDateTime::from_unix_timestamp(seconds as i64).unwrap() 33 | + time::Duration::nanoseconds(nanoseconds as i64), 34 | } 35 | } 36 | } 37 | 38 | impl DateTime { 39 | pub fn now() -> Self { 40 | Self::from(UnixInstant::>::now()) 41 | } 42 | 43 | pub fn recent() -> Self { 44 | Self::from(UnixInstant::>::recent()) 45 | } 46 | 47 | pub fn to_rfc3339_opts(&self, seconds_format: SecondsFormat, use_z: bool) -> String { 48 | let date = self.inner.date(); 49 | let time = self.inner.time(); 50 | let tz = if use_z { "Z" } else { "+00:00" }; 51 | let seconds = match seconds_format { 52 | SecondsFormat::Secs => { 53 | format!("{:02}", time.second()) 54 | } 55 | SecondsFormat::Millis => { 56 | format!("{:02}.{:03}", time.second(), time.millisecond()) 57 | } 58 | SecondsFormat::Micros => { 59 | format!("{:02}.{:06}", time.second(), time.microsecond()) 60 | } 61 | SecondsFormat::Nanos => { 62 | format!("{:02}.{:09}", time.second(), time.nanosecond()) 63 | } 64 | }; 65 | format!( 66 | "{:04}-{:02}-{:02}T{:02}:{:02}:{}{}", 67 | date.year(), 68 | date.month() as u8, 69 | date.day(), 70 | time.hour(), 71 | time.minute(), 72 | seconds, 73 | tz 74 | ) 75 | } 76 | } 77 | 78 | impl core::ops::Add for DateTime { 79 | type Output = DateTime; 80 | fn add( 81 | self, 82 | rhs: core::time::Duration, 83 | ) -> >::Output { 84 | DateTime { 85 | inner: self.inner + rhs, 86 | } 87 | } 88 | } 89 | 90 | impl core::ops::Sub for DateTime { 91 | type Output = DateTime; 92 | fn sub( 93 | self, 94 | rhs: core::time::Duration, 95 | ) -> >::Output { 96 | DateTime { 97 | inner: self.inner - rhs, 98 | } 99 | } 100 | } 101 | 102 | impl core::fmt::Display for DateTime { 103 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { 104 | let date = self.inner.date(); 105 | let time = self.inner.time(); 106 | 107 | write!( 108 | f, 109 | "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", 110 | date.year(), 111 | date.month() as u8, 112 | date.day(), 113 | time.hour(), 114 | time.minute(), 115 | time.second(), 116 | time.millisecond() 117 | ) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /time/src/duration.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICEN 4 | 5 | use crate::*; 6 | use core::ops::AddAssign; 7 | 8 | #[repr(transparent)] 9 | pub struct Duration { 10 | pub(crate) inner: T, 11 | } 12 | 13 | impl Eq for Duration where T: Eq {} 14 | 15 | impl PartialEq for Duration 16 | where 17 | T: PartialEq, 18 | { 19 | fn eq(&self, rhs: &Self) -> bool { 20 | self.inner.eq(&rhs.inner) 21 | } 22 | } 23 | 24 | impl Ord for Duration 25 | where 26 | T: Ord, 27 | { 28 | fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { 29 | self.inner.cmp(&rhs.inner) 30 | } 31 | } 32 | 33 | impl PartialOrd for Duration 34 | where 35 | T: PartialOrd, 36 | { 37 | fn partial_cmp(&self, rhs: &Self) -> Option { 38 | self.inner.partial_cmp(&rhs.inner) 39 | } 40 | } 41 | 42 | impl AddAssign for Duration 43 | where 44 | T: AddAssign, 45 | { 46 | fn add_assign(&mut self, other: Self) { 47 | self.inner += other.inner; 48 | } 49 | } 50 | 51 | impl Clone for Duration 52 | where 53 | T: Clone, 54 | { 55 | fn clone(&self) -> Self { 56 | Self { 57 | inner: self.inner.clone(), 58 | } 59 | } 60 | } 61 | 62 | impl Copy for Duration where T: Copy {} 63 | 64 | impl Duration> { 65 | pub const SECOND: Self = Self { 66 | inner: Seconds { inner: 1 }, 67 | }; 68 | pub const ZERO: Self = Self { 69 | inner: Seconds { inner: 0 }, 70 | }; 71 | pub const MAX: Self = Self { 72 | inner: Seconds { inner: u32::MAX }, 73 | }; 74 | 75 | pub const fn from_secs(seconds: u32) -> Self { 76 | Self { 77 | inner: Seconds { inner: seconds }, 78 | } 79 | } 80 | 81 | pub fn as_secs_f64(&self) -> f64 { 82 | self.inner.inner as f64 83 | } 84 | 85 | pub fn as_nanos(&self) -> u64 { 86 | self.inner.inner as u64 * NANOS_PER_SEC 87 | } 88 | 89 | pub fn as_secs(&self) -> u32 { 90 | self.inner.inner 91 | } 92 | } 93 | 94 | impl core::fmt::Debug for Duration> { 95 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 96 | f.debug_struct("Duration>") 97 | .field("secs", &self.inner.inner) 98 | .finish() 99 | } 100 | } 101 | 102 | impl Duration> { 103 | pub const fn from_secs(seconds: u32) -> Self { 104 | Self { 105 | inner: Seconds { 106 | inner: AtomicU32::new(seconds), 107 | }, 108 | } 109 | } 110 | } 111 | 112 | atomic!(Duration>, Seconds); 113 | atomic_arithmetic!(Duration>, Duration>); 114 | 115 | impl Duration> { 116 | pub const SECOND: Self = Self { 117 | inner: Nanoseconds { 118 | inner: NANOS_PER_SEC, 119 | }, 120 | }; 121 | pub const MILLISECOND: Self = Self { 122 | inner: Nanoseconds { 123 | inner: NANOS_PER_MILLI, 124 | }, 125 | }; 126 | pub const MICROSECOND: Self = Self { 127 | inner: Nanoseconds { 128 | inner: NANOS_PER_MICRO, 129 | }, 130 | }; 131 | pub const NANOSECOND: Self = Self { 132 | inner: Nanoseconds { inner: 1 }, 133 | }; 134 | pub const ZERO: Self = Self { 135 | inner: Nanoseconds { inner: 0 }, 136 | }; 137 | pub const MAX: Self = Self { 138 | inner: Nanoseconds { inner: u64::MAX }, 139 | }; 140 | 141 | pub const fn from_nanos(nanoseconds: u64) -> Self { 142 | Self { 143 | inner: Nanoseconds { inner: nanoseconds }, 144 | } 145 | } 146 | 147 | pub fn from_micros(microseconds: u64) -> Self { 148 | Self { 149 | inner: Nanoseconds { 150 | inner: microseconds 151 | .checked_mul(NANOS_PER_MICRO) 152 | .expect("the specified duration could not be represented with this type"), 153 | }, 154 | } 155 | } 156 | 157 | pub fn from_millis(milliseconds: u64) -> Self { 158 | Self { 159 | inner: Nanoseconds { 160 | inner: milliseconds 161 | .checked_mul(NANOS_PER_MILLI) 162 | .expect("the specified duration could not be represented with this type"), 163 | }, 164 | } 165 | } 166 | 167 | pub fn from_secs(seconds: u64) -> Self { 168 | Self { 169 | inner: Nanoseconds { 170 | inner: seconds 171 | .checked_mul(NANOS_PER_SEC) 172 | .expect("the specified duration could not be represented with this type"), 173 | }, 174 | } 175 | } 176 | 177 | pub fn as_secs_f64(&self) -> f64 { 178 | self.inner.inner as f64 / NANOS_PER_SEC as f64 179 | } 180 | 181 | pub const fn as_nanos(&self) -> u64 { 182 | self.inner.inner 183 | } 184 | 185 | pub const fn as_secs(&self) -> u64 { 186 | self.inner.inner / NANOS_PER_SEC 187 | } 188 | 189 | pub const fn subsec_nanos(&self) -> u64 { 190 | self.inner.inner % NANOS_PER_SEC 191 | } 192 | 193 | pub const fn as_millis(&self) -> u64 { 194 | self.inner.inner / NANOS_PER_MILLI 195 | } 196 | 197 | pub const fn as_micros(&self) -> u64 { 198 | self.inner.inner / NANOS_PER_MICRO 199 | } 200 | 201 | pub fn mul_f64(self, rhs: f64) -> Self { 202 | Self { 203 | inner: Nanoseconds { 204 | inner: (self.inner.inner as f64 * rhs) as u64, 205 | }, 206 | } 207 | } 208 | } 209 | 210 | impl core::fmt::Debug for Duration> { 211 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 212 | f.debug_struct("Duration>") 213 | .field("nanos", &self.inner.inner) 214 | .finish() 215 | } 216 | } 217 | 218 | impl Duration> { 219 | pub const fn from_nanos(nanoseconds: u64) -> Self { 220 | Self { 221 | inner: Nanoseconds { 222 | inner: AtomicU64::new(nanoseconds), 223 | }, 224 | } 225 | } 226 | } 227 | 228 | atomic!(Duration>, Nanoseconds); 229 | atomic_arithmetic!(Duration>, Duration>); 230 | -------------------------------------------------------------------------------- /time/src/instant.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use crate::*; 6 | 7 | /// The measurement of a monotonically nondecreasing clock. The internal 8 | /// representation is the duration since an arbitrary epoch. Opaque and only 9 | /// useful with other `Instant`s and the `Duration` types. 10 | /// 11 | /// It is important to note that the underlying clock is not guaranteed to be 12 | /// steady. It is subject only to frequency corrections. 13 | #[repr(transparent)] 14 | pub struct Instant { 15 | pub(crate) inner: T, 16 | } 17 | 18 | impl Eq for Instant where T: Eq {} 19 | 20 | impl PartialEq for Instant 21 | where 22 | T: PartialEq, 23 | { 24 | fn eq(&self, rhs: &Self) -> bool { 25 | self.inner.eq(&rhs.inner) 26 | } 27 | } 28 | 29 | impl Ord for Instant 30 | where 31 | T: Ord, 32 | { 33 | fn cmp(&self, rhs: &Self) -> core::cmp::Ordering { 34 | self.inner.cmp(&rhs.inner) 35 | } 36 | } 37 | 38 | impl PartialOrd for Instant 39 | where 40 | T: PartialOrd, 41 | { 42 | fn partial_cmp(&self, rhs: &Self) -> Option { 43 | self.inner.partial_cmp(&rhs.inner) 44 | } 45 | } 46 | 47 | impl core::hash::Hash for Instant 48 | where 49 | T: core::hash::Hash, 50 | { 51 | fn hash(&self, h: &mut H) 52 | where 53 | H: core::hash::Hasher, 54 | { 55 | self.inner.hash(h) 56 | } 57 | } 58 | 59 | impl Clone for Instant 60 | where 61 | T: Clone, 62 | { 63 | fn clone(&self) -> Self { 64 | Self { 65 | inner: self.inner.clone(), 66 | } 67 | } 68 | } 69 | 70 | impl Copy for Instant where T: Copy {} 71 | 72 | impl Instant> { 73 | pub fn now() -> Self { 74 | let mut ts = libc::timespec { 75 | tv_sec: 0, 76 | tv_nsec: 0, 77 | }; 78 | unsafe { 79 | libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts); 80 | } 81 | 82 | Self { 83 | inner: Seconds::from(ts), 84 | } 85 | } 86 | 87 | pub fn recent() -> Self { 88 | CLOCK.initialize(); 89 | CLOCK.coarse.load(Ordering::Relaxed) 90 | } 91 | } 92 | 93 | impl core::fmt::Debug for Instant> { 94 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 95 | f.debug_struct("Instant>") 96 | .field("secs", &self.inner.inner) 97 | .finish() 98 | } 99 | } 100 | 101 | instant!(Instant>); 102 | 103 | impl Instant> { 104 | pub fn now() -> Self { 105 | Self::new(Instant::>::now()) 106 | } 107 | 108 | pub fn recent() -> Self { 109 | Self::new(Instant::>::recent()) 110 | } 111 | } 112 | 113 | atomic!(Instant>, Seconds); 114 | 115 | impl Instant> { 116 | pub fn now() -> Self { 117 | let mut ts = libc::timespec { 118 | tv_sec: 0, 119 | tv_nsec: 0, 120 | }; 121 | unsafe { 122 | libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts); 123 | } 124 | 125 | Self { 126 | inner: Nanoseconds::from(ts), 127 | } 128 | } 129 | 130 | pub fn recent() -> Self { 131 | CLOCK.initialize(); 132 | CLOCK.precise.load(Ordering::Relaxed) 133 | } 134 | } 135 | 136 | impl core::fmt::Debug for Instant> { 137 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 138 | f.debug_struct("Instant>") 139 | .field("nanos", &self.inner.inner) 140 | .finish() 141 | } 142 | } 143 | 144 | instant!(Instant>); 145 | 146 | impl Instant> { 147 | pub fn now() -> Self { 148 | Self::new(Instant::>::now()) 149 | } 150 | 151 | pub fn recent() -> Self { 152 | Self::new(Instant::>::recent()) 153 | } 154 | } 155 | 156 | atomic!(Instant>, Nanoseconds); 157 | atomic_arithmetic!(Instant>, Duration>); 158 | -------------------------------------------------------------------------------- /time/src/units.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICEN 4 | 5 | use crate::*; 6 | use core::hash::Hash; 7 | 8 | /// A container for time types that stores seconds. 9 | #[repr(transparent)] 10 | pub struct Seconds { 11 | pub(crate) inner: T, 12 | } 13 | 14 | unit!(Seconds); 15 | atomic!(Seconds, u32); 16 | atomic_arithmetic!(Seconds, Seconds); 17 | 18 | impl Eq for Seconds where T: Eq {} 19 | 20 | impl PartialEq for Seconds 21 | where 22 | T: PartialEq, 23 | { 24 | fn eq(&self, rhs: &Self) -> bool { 25 | self.inner.eq(&rhs.inner) 26 | } 27 | } 28 | 29 | impl Ord for Seconds 30 | where 31 | T: Ord, 32 | { 33 | fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { 34 | self.inner.cmp(&rhs.inner) 35 | } 36 | } 37 | 38 | impl PartialOrd for Seconds 39 | where 40 | T: PartialOrd, 41 | { 42 | fn partial_cmp(&self, rhs: &Self) -> Option { 43 | self.inner.partial_cmp(&rhs.inner) 44 | } 45 | } 46 | 47 | impl Hash for Seconds 48 | where 49 | T: Hash, 50 | { 51 | fn hash(&self, h: &mut H) 52 | where 53 | H: std::hash::Hasher, 54 | { 55 | self.inner.hash(h) 56 | } 57 | } 58 | 59 | impl Clone for Seconds 60 | where 61 | T: Clone, 62 | { 63 | fn clone(&self) -> Self { 64 | Self { 65 | inner: self.inner.clone(), 66 | } 67 | } 68 | } 69 | 70 | impl Copy for Seconds where T: Copy {} 71 | 72 | /// A container for time types that stores nanoseconds. 73 | #[repr(transparent)] 74 | pub struct Nanoseconds { 75 | pub(crate) inner: T, 76 | } 77 | 78 | unit!(Nanoseconds); 79 | atomic!(Nanoseconds, u64); 80 | atomic_arithmetic!(Nanoseconds, Nanoseconds); 81 | 82 | impl Eq for Nanoseconds where T: Eq {} 83 | 84 | impl PartialEq for Nanoseconds 85 | where 86 | T: PartialEq, 87 | { 88 | fn eq(&self, rhs: &Self) -> bool { 89 | self.inner.eq(&rhs.inner) 90 | } 91 | } 92 | 93 | impl Ord for Nanoseconds 94 | where 95 | T: Ord, 96 | { 97 | fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { 98 | self.inner.cmp(&rhs.inner) 99 | } 100 | } 101 | 102 | impl PartialOrd for Nanoseconds 103 | where 104 | T: PartialOrd, 105 | { 106 | fn partial_cmp(&self, rhs: &Self) -> Option { 107 | self.inner.partial_cmp(&rhs.inner) 108 | } 109 | } 110 | 111 | impl Hash for Nanoseconds 112 | where 113 | T: Hash, 114 | { 115 | fn hash(&self, h: &mut H) 116 | where 117 | H: std::hash::Hasher, 118 | { 119 | self.inner.hash(h) 120 | } 121 | } 122 | 123 | impl Clone for Nanoseconds 124 | where 125 | T: Clone, 126 | { 127 | fn clone(&self) -> Self { 128 | Self { 129 | inner: self.inner.clone(), 130 | } 131 | } 132 | } 133 | 134 | impl Copy for Nanoseconds where T: Copy {} 135 | 136 | impl From for Seconds { 137 | fn from(ts: libc::timespec) -> Self { 138 | Self { 139 | inner: ts.tv_sec as u32, 140 | } 141 | } 142 | } 143 | 144 | impl From for Seconds { 145 | fn from(ts: libc::timespec) -> Self { 146 | Self { 147 | inner: AtomicU32::new(ts.tv_sec as u32), 148 | } 149 | } 150 | } 151 | 152 | impl From for Nanoseconds { 153 | fn from(ts: libc::timespec) -> Self { 154 | Self { 155 | inner: ts.tv_sec as u64 * NANOS_PER_SEC + ts.tv_nsec as u64, 156 | } 157 | } 158 | } 159 | 160 | impl From for Nanoseconds { 161 | fn from(ts: libc::timespec) -> Self { 162 | Self { 163 | inner: AtomicU64::new(ts.tv_sec as u64 * NANOS_PER_SEC + ts.tv_nsec as u64), 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /time/src/unix.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICEN 4 | 5 | use crate::*; 6 | 7 | /// An instant in wall-clock time. The internal representation is a duration 8 | /// since the Unix Epoch. Opaque and only useful with other `UnixInstant`s and 9 | /// the `Duration` types. 10 | /// 11 | /// It is important to note that the underlying clock is not guaranteed to be 12 | /// steady or monotonically non-decreasing. It is subject to both phase and 13 | /// frequency corrections. 14 | #[repr(transparent)] 15 | pub struct UnixInstant { 16 | pub(crate) inner: T, 17 | } 18 | 19 | impl Eq for UnixInstant where T: Eq {} 20 | 21 | impl PartialEq for UnixInstant 22 | where 23 | T: PartialEq, 24 | { 25 | fn eq(&self, rhs: &Self) -> bool { 26 | self.inner.eq(&rhs.inner) 27 | } 28 | } 29 | 30 | impl Ord for UnixInstant 31 | where 32 | T: Ord, 33 | { 34 | fn cmp(&self, rhs: &Self) -> core::cmp::Ordering { 35 | self.inner.cmp(&rhs.inner) 36 | } 37 | } 38 | 39 | impl core::hash::Hash for UnixInstant 40 | where 41 | T: core::hash::Hash, 42 | { 43 | fn hash(&self, h: &mut H) 44 | where 45 | H: core::hash::Hasher, 46 | { 47 | self.inner.hash(h) 48 | } 49 | } 50 | 51 | impl PartialOrd for UnixInstant 52 | where 53 | T: PartialOrd, 54 | { 55 | fn partial_cmp(&self, rhs: &Self) -> Option { 56 | self.inner.partial_cmp(&rhs.inner) 57 | } 58 | } 59 | 60 | impl Clone for UnixInstant 61 | where 62 | T: Clone, 63 | { 64 | fn clone(&self) -> Self { 65 | Self { 66 | inner: self.inner.clone(), 67 | } 68 | } 69 | } 70 | 71 | impl Copy for UnixInstant where T: Copy {} 72 | 73 | impl UnixInstant> { 74 | pub fn now() -> Self { 75 | let mut ts = libc::timespec { 76 | tv_sec: 0, 77 | tv_nsec: 0, 78 | }; 79 | unsafe { 80 | libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts); 81 | } 82 | 83 | UnixInstant { 84 | inner: Seconds::from(ts), 85 | } 86 | } 87 | 88 | pub fn recent() -> Self { 89 | CLOCK.initialize(); 90 | CLOCK.coarse_unix.load(Ordering::Relaxed) 91 | } 92 | 93 | pub fn from_secs(secs: u32) -> Self { 94 | UnixInstant { 95 | inner: Seconds { inner: secs }, 96 | } 97 | } 98 | } 99 | 100 | impl core::fmt::Debug for UnixInstant> { 101 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 102 | f.debug_struct("UnixInstant>") 103 | .field("secs", &self.inner.inner) 104 | .finish() 105 | } 106 | } 107 | 108 | instant!(UnixInstant>); 109 | atomic!(UnixInstant>, Seconds); 110 | 111 | impl UnixInstant> { 112 | pub fn now() -> Self { 113 | let mut ts = libc::timespec { 114 | tv_sec: 0, 115 | tv_nsec: 0, 116 | }; 117 | unsafe { 118 | libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts); 119 | } 120 | 121 | UnixInstant { 122 | inner: Nanoseconds::from(ts), 123 | } 124 | } 125 | 126 | pub fn recent() -> Self { 127 | CLOCK.initialize(); 128 | CLOCK.precise_unix.load(Ordering::Relaxed) 129 | } 130 | 131 | pub fn from_nanos(nanos: u64) -> Self { 132 | UnixInstant { 133 | inner: Nanoseconds { inner: nanos }, 134 | } 135 | } 136 | } 137 | 138 | impl core::fmt::Debug for UnixInstant> { 139 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 140 | f.debug_struct("UnixInstant>") 141 | .field("nanos", &self.inner.inner) 142 | .finish() 143 | } 144 | } 145 | 146 | instant!(UnixInstant>); 147 | atomic!(UnixInstant>, Nanoseconds); 148 | -------------------------------------------------------------------------------- /timer/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Unreleased 2 | 3 | # 1.0.0 - 2019-12-13 4 | 5 | Initial release. 6 | -------------------------------------------------------------------------------- /timer/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-timer" 3 | version = "1.0.1" 4 | authors = ["Brian Martin "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | description = "Timer wheel" 8 | homepage = "https://github.com/twitter/rustcommon/timer" 9 | repository = "https://github.com/twitter/rustcommon" 10 | 11 | [dependencies] 12 | log = "0.4.17" 13 | -------------------------------------------------------------------------------- /timer/README.md: -------------------------------------------------------------------------------- 1 | # rustcommon-timer 2 | 3 | A hash wheel timer implementation focused on low cost addition, cancellation, 4 | and expiration of timers 5 | 6 | ## Overview 7 | 8 | This crate provides a hash wheel timer implementation which can be used to hold 9 | many timers with short timeouts. It is designed to be used for use in providing 10 | timeouts for network requests and as such tries to minimize the cost of adding 11 | and canceling timers 12 | 13 | ## Getting Started 14 | 15 | ### Building 16 | 17 | rustcommon is built with the standard Rust toolchain which can be installed and 18 | managed via [rustup](https://rustup.rs) or by following the directions on the 19 | Rust [website](https://www.rust-lang.org/). 20 | 21 | #### View library documentation 22 | ```bash 23 | cargo doc --open 24 | ``` 25 | 26 | ## Support 27 | 28 | Create a [new issue](https://github.com/twitter/rustcommon/issues/new) on GitHub. 29 | 30 | ## Contributing 31 | 32 | We feel that a welcoming community is important and we ask that you follow 33 | Twitter's [Open Source Code of Conduct] in all interactions with the community. 34 | 35 | ## Authors 36 | 37 | * Brian Martin 38 | 39 | A full list of [contributors] can be found on GitHub. 40 | 41 | Follow [@TwitterOSS](https://twitter.com/twitteross) on Twitter for updates. 42 | 43 | ## License 44 | 45 | Copyright 2019-2020 Twitter, Inc. 46 | 47 | Licensed under the Apache License, Version 2.0: 48 | https://www.apache.org/licenses/LICENSE-2.0 49 | 50 | ## Security Issues? 51 | 52 | Please report sensitive security issues via Twitter's bug-bounty program 53 | (https://hackerone.com/twitter) rather than GitHub. 54 | 55 | [contributors]: https://github.com/twitter/rustcommon/graphs/contributors?type=a 56 | [Open Source Code of Conduct]: https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md 57 | -------------------------------------------------------------------------------- /waterfall/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Unreleased 2 | 3 | # 1.0.0 - 2019-12-13 4 | 5 | Initial release. 6 | -------------------------------------------------------------------------------- /waterfall/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustcommon-waterfall" 3 | version = "1.0.2" 4 | authors = ["Brian Martin "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | description = "Generates waterfalls from heatmaps" 8 | homepage = "https://github.com/twitter/rustcommon/waterfall" 9 | repository = "https://github.com/twitter/rustcommon" 10 | 11 | [dependencies] 12 | dejavu = "2.37.0" 13 | image = "0.24.3" 14 | log = "0.4.17" 15 | heatmap = { path = "../heatmap" } 16 | histogram = { path = "../histogram" } 17 | rustcommon-time = { path = "../time" } 18 | rusttype = "0.9.2" 19 | 20 | [dev-dependencies] 21 | rand = "0.8.5" 22 | rand_distr = "0.4.3" 23 | rustcommon-logger = { path = "../logger" } -------------------------------------------------------------------------------- /waterfall/README.md: -------------------------------------------------------------------------------- 1 | # rustcommon-waterfall 2 | 3 | Waterfall visualization from heatmap data 4 | 5 | ## Overview 6 | 7 | This library is used to render waterfall visualizations from heatmap data. This 8 | style of visualization represents time moving downwards with values increasing 9 | from left to right. The color represents the density of samples of the same 10 | value within the heatmap. 11 | 12 | You can generate some examples with `cargo run --example simulator` which will 13 | produce several example waterfalls from synthetic data. 14 | 15 | ## Getting Started 16 | 17 | ### Building 18 | 19 | rustcommon is built with the standard Rust toolchain which can be installed and 20 | managed via [rustup](https://rustup.rs) or by following the directions on the 21 | Rust [website](https://www.rust-lang.org/). 22 | 23 | #### View library documentation 24 | ```bash 25 | cargo doc --open 26 | ``` 27 | 28 | ## Support 29 | 30 | Create a [new issue](https://github.com/twitter/rustcommon/issues/new) on GitHub. 31 | 32 | ## Contributing 33 | 34 | We feel that a welcoming community is important and we ask that you follow 35 | Twitter's [Open Source Code of Conduct] in all interactions with the community. 36 | 37 | ## Authors 38 | 39 | * Brian Martin 40 | 41 | A full list of [contributors] can be found on GitHub. 42 | 43 | Follow [@TwitterOSS](https://twitter.com/twitteross) on Twitter for updates. 44 | 45 | ## License 46 | 47 | Copyright 2019-2020 Twitter, Inc. 48 | 49 | Licensed under the Apache License, Version 2.0: 50 | https://www.apache.org/licenses/LICENSE-2.0 51 | 52 | ## Security Issues? 53 | 54 | Please report sensitive security issues via Twitter's bug-bounty program 55 | (https://hackerone.com/twitter) rather than GitHub. 56 | 57 | [contributors]: https://github.com/twitter/rustcommon/graphs/contributors?type=a 58 | [Open Source Code of Conduct]: https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md 59 | -------------------------------------------------------------------------------- /waterfall/examples/simulator.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Twitter, Inc. 2 | // Licensed under the Apache License, Version 2.0 3 | // http://www.apache.org/licenses/LICENSE-2.0 4 | 5 | use heatmap::*; 6 | use rand::thread_rng; 7 | use rand_distr::*; 8 | use rustcommon_logger::*; 9 | use rustcommon_waterfall::*; 10 | 11 | fn main() { 12 | let log = LogBuilder::new() 13 | .output(Box::new(Stdout::new())) 14 | .build() 15 | .expect("failed to initialize log"); 16 | 17 | let mut drain = log.start(); 18 | 19 | std::thread::spawn(move || loop { 20 | let _ = drain.flush(); 21 | std::thread::sleep(core::time::Duration::from_millis(100)); 22 | }); 23 | 24 | info!("Welcome to the simulator!"); 25 | 26 | for shape in &[ 27 | Shape::Cauchy, 28 | Shape::Normal, 29 | Shape::Uniform, 30 | Shape::Triangular, 31 | Shape::Gamma, 32 | ] { 33 | simulate(*shape); 34 | } 35 | } 36 | 37 | #[derive(Copy, Clone, Debug)] 38 | pub enum Shape { 39 | Cauchy, 40 | Normal, 41 | Uniform, 42 | Triangular, 43 | Gamma, 44 | } 45 | 46 | pub fn simulate(shape: Shape) { 47 | info!("Simulating for {:?} distribution", shape); 48 | let duration = Duration::from_secs(120); 49 | 50 | let heatmap = Heatmap::new( 51 | 0, 52 | 10, 53 | 20, 54 | Duration::from_secs(120), 55 | Duration::from_millis(250), 56 | ) 57 | .unwrap(); 58 | 59 | let cauchy = Cauchy::new(500_000.0, 2_000.00).unwrap(); 60 | let normal = Normal::new(200_000.0, 100_000.0).unwrap(); 61 | let uniform = Uniform::new_inclusive(10_000.0, 200_000.0); 62 | let triangular = Triangular::new(1.0, 200_000.0, 50_000.0).unwrap(); 63 | let gamma = Gamma::new(2.0, 2.0).unwrap(); 64 | 65 | let mut rng = thread_rng(); 66 | let start = Instant::now(); 67 | loop { 68 | if start.elapsed() >= duration { 69 | break; 70 | } 71 | let value: f64 = match shape { 72 | Shape::Cauchy => cauchy.sample(&mut rng), 73 | Shape::Normal => normal.sample(&mut rng), 74 | Shape::Uniform => uniform.sample(&mut rng), 75 | Shape::Triangular => triangular.sample(&mut rng), 76 | Shape::Gamma => gamma.sample(&mut rng) * 100_000.0, 77 | }; 78 | let value = value.floor() as u64; 79 | if value != 0 { 80 | heatmap.increment(Instant::now(), value, 1); 81 | } 82 | } 83 | 84 | let shape_name = match shape { 85 | Shape::Cauchy => "cauchy", 86 | Shape::Normal => "normal", 87 | Shape::Uniform => "uniform", 88 | Shape::Triangular => "triangular", 89 | Shape::Gamma => "gamma", 90 | }; 91 | 92 | for scale in [Scale::Linear, Scale::Logarithmic].iter() { 93 | for palette in [Palette::Classic, Palette::Ironbow].iter() { 94 | let scale_name = match scale { 95 | Scale::Linear => "linear", 96 | Scale::Logarithmic => "logarithmic", 97 | }; 98 | 99 | let palette_name = match palette { 100 | Palette::Classic => "classic", 101 | Palette::Ironbow => "ironbow", 102 | }; 103 | 104 | let filename = format!("{}_{}_{}.png", shape_name, palette_name, scale_name); 105 | 106 | WaterfallBuilder::new(&filename) 107 | .label(100, "100") 108 | .label(1000, "1000") 109 | .label(10000, "10000") 110 | .label(100000, "100000") 111 | .scale(*scale) 112 | .palette(*palette) 113 | .build(&heatmap); 114 | 115 | let filename = format!("{}_{}_{}_smooth.png", shape_name, palette_name, scale_name); 116 | 117 | WaterfallBuilder::new(&filename) 118 | .label(100, "100") 119 | .label(1000, "1000") 120 | .label(10000, "10000") 121 | .label(100000, "100000") 122 | .scale(*scale) 123 | .palette(*palette) 124 | .smooth(Some(1.0)) 125 | .build(&heatmap); 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /waterfall/src/palettes/mod.rs: -------------------------------------------------------------------------------- 1 | mod classic; 2 | mod ironbow; 3 | 4 | pub(crate) use classic::CLASSIC; 5 | pub(crate) use ironbow::IRONBOW; 6 | 7 | #[derive(Copy, Clone)] 8 | pub enum Palette { 9 | Classic, 10 | Ironbow, 11 | } 12 | --------------------------------------------------------------------------------