├── AUTHORS ├── .gitignore ├── .github ├── dependabot.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── ci.yml ├── rustfmt.toml ├── scripts ├── install-hook.sh └── linkify_changelog.yml ├── LICENSE-MIT ├── .hooks └── pre-commit ├── src ├── iterable │ ├── rev.rs │ └── mod.rs ├── error.rs ├── rand_helper.rs ├── lib.rs ├── perf_trace.rs └── io │ ├── error.rs │ └── mod.rs ├── CHANGELOG.md ├── Cargo.toml ├── README.md └── LICENSE-APACHE /AUTHORS: -------------------------------------------------------------------------------- 1 | Sean Bowe 2 | Alessandro Chiesa 3 | Matthew Green 4 | Ian Miers 5 | Pratyush Mishra 6 | Howard Wu 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .DS_Store 4 | .idea 5 | *.iml 6 | *.ipynb_checkpoints 7 | *.pyc 8 | *.sage.py 9 | params 10 | *.swp 11 | *.swo 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | reorder_imports = true 2 | wrap_comments = true 3 | normalize_comments = true 4 | use_try_shorthand = true 5 | match_block_trailing_comma = true 6 | use_field_init_shorthand = true 7 | edition = "2018" 8 | condense_wildcard_suffixes = true 9 | merge_imports = true 10 | -------------------------------------------------------------------------------- /scripts/install-hook.sh: -------------------------------------------------------------------------------- 1 | #!/bin/env bash 2 | # This script will install the provided directory ../.hooks as the hook 3 | # directory for the present repo. See there for hooks, including a pre-commit 4 | # hook that runs rustfmt on files before a commit. 5 | 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | HOOKS_DIR="${DIR}/../.hooks" 8 | 9 | git config core.hooksPath "$HOOKS_DIR" 10 | -------------------------------------------------------------------------------- /scripts/linkify_changelog.yml: -------------------------------------------------------------------------------- 1 | name: Linkify Changelog 2 | 3 | on: 4 | workflow_dispatch 5 | 6 | jobs: 7 | linkify: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout 11 | uses: actions/checkout@v2 12 | - name: Add links 13 | run: python3 scripts/linkify_changelog.py CHANGELOG.md 14 | - name: Commit 15 | run: | 16 | git config user.name github-actions 17 | git config user.email github-actions@github.com 18 | git add . 19 | git commit -m "Linkify Changelog" 20 | git push -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us squash bugs! 4 | 5 | --- 6 | 7 | ∂ 12 | 13 | ## Summary of Bug 14 | 15 | 16 | 17 | ## Version 18 | 19 | 20 | 21 | ## Steps to Reproduce 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Create a proposal to request a feature 4 | 5 | --- 6 | 7 | 13 | 14 | ## Summary 15 | 16 | 17 | 18 | ## Problem Definition 19 | 20 | 23 | 24 | ## Proposal 25 | 26 | 27 | 28 | ____ 29 | 30 | #### For Admin Use 31 | 32 | - [ ] Not duplicate issue 33 | - [ ] Appropriate labels applied 34 | - [ ] Appropriate contributors tagged 35 | - [ ] Contributor assigned/self-assigned 36 | -------------------------------------------------------------------------------- /.hooks/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rustfmt --version &>/dev/null 4 | if [ $? != 0 ]; then 5 | printf "[pre_commit] \033[0;31merror\033[0m: \"rustfmt\" not available. \n" 6 | printf "[pre_commit] \033[0;31merror\033[0m: rustfmt can be installed via - \n" 7 | printf "[pre_commit] $ rustup component add rustfmt \n" 8 | exit 1 9 | fi 10 | 11 | problem_files=() 12 | 13 | # collect ill-formatted files 14 | for file in $(git diff --name-only --cached); do 15 | if [ ${file: -3} == ".rs" ]; then 16 | rustfmt +stable --check $file &>/dev/null 17 | if [ $? != 0 ]; then 18 | problem_files+=($file) 19 | fi 20 | fi 21 | done 22 | 23 | if [ ${#problem_files[@]} == 0 ]; then 24 | # done 25 | printf "[pre_commit] rustfmt \033[0;32mok\033[0m \n" 26 | else 27 | # reformat the files that need it and re-stage them. 28 | printf "[pre_commit] the following files were rustfmt'd before commit: \n" 29 | for file in ${problem_files[@]}; do 30 | rustfmt +stable $file 31 | git add $file 32 | printf "\033[0;32m $file\033[0m \n" 33 | done 34 | fi 35 | 36 | exit 0 37 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | ## Description 8 | 9 | 12 | 13 | closes: #XXXX 14 | 15 | --- 16 | 17 | Before we can merge this PR, please make sure that all the following items have been 18 | checked off. If any of the checklist items are not applicable, please leave them but 19 | write a little note why. 20 | 21 | - [ ] Targeted PR against correct branch (master) 22 | - [ ] Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work. 23 | - [ ] Wrote unit tests 24 | - [ ] Updated relevant documentation in the code 25 | - [ ] Added a relevant changelog entry to the `Pending` section in `CHANGELOG.md` 26 | - [ ] Re-reviewed `Files changed` in the Github PR explorer 27 | -------------------------------------------------------------------------------- /src/iterable/rev.rs: -------------------------------------------------------------------------------- 1 | use super::Iterable; 2 | use crate::iter::Rev; 3 | 4 | /// Stream that goes over an `[ExactSizeIterator]` in reverse order. 5 | /// 6 | /// This stream allows to switch fast from little endian ordering used in 7 | /// time-efficient algorithms, e.g. in slices `&[T]` into big endia ordering 8 | /// (used in space-efficient algorithms. 9 | /// 10 | /// # Examples 11 | /// ``` 12 | /// use ark_std::iterable::{Iterable, Reverse}; 13 | /// 14 | /// let le_v = &[1, 2, 3]; 15 | /// let be_v = Reverse(le_v); 16 | /// let mut be_v_iter = be_v.iter(); 17 | /// assert_eq!(be_v_iter.next(), Some(&3)); 18 | /// assert_eq!(be_v_iter.next(), Some(&2)); 19 | /// assert_eq!(be_v_iter.next(), Some(&1)); 20 | /// ``` 21 | #[derive(Clone, Copy)] 22 | pub struct Reverse(pub I) 23 | where 24 | I: Iterable, 25 | I::Iter: DoubleEndedIterator; 26 | 27 | impl Iterable for Reverse 28 | where 29 | I: Iterable, 30 | I::Iter: DoubleEndedIterator, 31 | { 32 | type Item = I::Item; 33 | type Iter = Rev; 34 | 35 | #[inline] 36 | fn iter(&self) -> Self::Iter { 37 | self.0.iter().rev() 38 | } 39 | 40 | #[inline] 41 | fn len(&self) -> usize { 42 | self.0.len() 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Pending 2 | 3 | ### Breaking changes 4 | 5 | ### Features 6 | 7 | ### Improvements 8 | - [\#65](https://github.com/arkworks-rs/std/pull/65) Add the `cfg_join` macro for executing two closures (potentially in parallel). 9 | 10 | ### Bug fixes 11 | 12 | ## v0.5.0 13 | 14 | ### Breaking changes 15 | 16 | ### Features 17 | 18 | ### Improvements 19 | 20 | ### Bug fixes 21 | - [\#47](https://github.com/arkworks-rs/std/pull/47) Fix incorrect use of atomic variable in `src/perf_trace.rs` 22 | 23 | ## v0.4.0 24 | 25 | ### Breaking changes 26 | 27 | - [\#35](https://github.com/arkworks-rs/utils/pull/35) Change `test_rng` to return `impl Rng`, and make the output randomized by default when the `std` feature is set. Introduces a `DETERMINISTIC_TEST_RNG` environment variable that forces the old deterministic behavior when `DETERMINISTIC_TEST_RNG=1` is set. 28 | 29 | ### Features 30 | 31 | ### Improvements 32 | 33 | ### Bug fixes 34 | 35 | ## v0.3.0 36 | 37 | ### Breaking changes 38 | 39 | - [\#32](https://github.com/arkworks-rs/utils/pull/32) Bump `rand` to 0.8 and remove the use of `rand_xorshift`. 40 | 41 | ### Features 42 | 43 | - [\#34](https://github.com/arkworks-rs/utils/pull/34) Re-export `num_traits::{One, Zero}` from `ark-std`. 44 | 45 | ### Improvements 46 | 47 | ### Bug fixes 48 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ark-std" 3 | version = "0.5.0" 4 | authors = [ "arkworks contributors" ] 5 | description = "A library for no_std compatibility" 6 | homepage = "https://arkworks.rs" 7 | repository = "https://github.com/arkworks-rs/std" 8 | documentation = "https://docs.rs/ark-std/" 9 | keywords = [ "no_std" ] 10 | categories = ["cryptography"] 11 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 12 | license = "MIT/Apache-2.0" 13 | edition = "2021" 14 | 15 | [dependencies] 16 | rand = { version = "0.8", default-features = false, features = ["std_rng"]} 17 | rayon = { version = "1", optional = true } 18 | colored = { version = "2", optional = true } 19 | num-traits = { version = "0.2", default-features = false } 20 | 21 | [dev-dependencies] 22 | rand = { version = "0.8", features = ["std"]} 23 | 24 | 25 | [features] 26 | default = [ "std" ] 27 | std = [] 28 | parallel = [ "rayon", "std" ] 29 | print-trace = [ "std", "colored" ] 30 | getrandom = ["rand/std"] 31 | 32 | [profile.bench] 33 | opt-level = 3 34 | debug = false 35 | rpath = false 36 | lto = "thin" 37 | incremental = true 38 | debug-assertions = false 39 | 40 | [profile.dev] 41 | opt-level = 0 42 | 43 | [profile.test] 44 | opt-level = 3 45 | lto = "thin" 46 | incremental = true 47 | debug-assertions = true 48 | debug = true 49 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use crate::boxed::Box; 2 | use crate::fmt::{self, Debug, Display}; 3 | use crate::string::String; 4 | 5 | pub trait Error: core::fmt::Debug + core::fmt::Display { 6 | fn source(&self) -> Option<&(dyn Error + 'static)> { 7 | None 8 | } 9 | } 10 | 11 | impl<'a, E: Error + 'a> From for Box { 12 | fn from(err: E) -> Self { 13 | Box::new(err) 14 | } 15 | } 16 | 17 | impl<'a, E: Error + Send + Sync + 'a> From for Box { 18 | fn from(err: E) -> Box { 19 | Box::new(err) 20 | } 21 | } 22 | 23 | impl Error for Box {} 24 | 25 | impl From for Box { 26 | #[inline] 27 | fn from(err: String) -> Box { 28 | struct StringError(String); 29 | 30 | impl Error for StringError {} 31 | 32 | impl Display for StringError { 33 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 34 | Display::fmt(&self.0, f) 35 | } 36 | } 37 | 38 | // Purposefully skip printing "StringError(..)" 39 | impl Debug for StringError { 40 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 41 | Debug::fmt(&self.0, f) 42 | } 43 | } 44 | 45 | Box::new(StringError(err)) 46 | } 47 | } 48 | 49 | impl<'a> From<&'a str> for Box { 50 | #[inline] 51 | fn from(err: &'a str) -> Box { 52 | From::from(String::from(err)) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

arkworks::std

2 | 3 |

4 | 5 | 6 | 7 | 8 |

9 | 10 | The arkworks ecosystem consists of Rust libraries for designing and working with __zero knowledge succinct non-interactive arguments (zkSNARKs)__. This repository contains `ark-std`, a library that serves as a compatibility layer for `no_std` use cases, and also contains useful methods and types used by the rest of the `arkworks` ecosystem. 11 | 12 | This library is released under the MIT License and the Apache v2 License (see [License](#license)). 13 | 14 | **WARNING:** This is an academic proof-of-concept prototype, and in particular has not received careful code review. This implementation is NOT ready for production use. 15 | 16 | ## Build guide 17 | 18 | The library compiles on the `stable` toolchain of the Rust compiler. To install the latest version of Rust, first install `rustup` by following the instructions [here](https://rustup.rs/), or via your platform's package manager. Once `rustup` is installed, install the Rust toolchain by invoking: 19 | ```bash 20 | rustup install stable 21 | ``` 22 | 23 | After that, use `cargo`, the standard Rust build tool, to build the libraries: 24 | ```bash 25 | git clone https://github.com/arkworks-rs/utils.git 26 | cd utils 27 | cargo build --release 28 | ``` 29 | 30 | ## Tests 31 | This library comes with comprehensive unit and integration tests for each of the provided crates. Run the tests with: 32 | ```bash 33 | cargo test --all 34 | ``` 35 | 36 | ## Benchmarks 37 | 38 | To run the benchmarks, install the nightly Rust toolchain, via `rustup install nightly`, and then run the following command: 39 | ```bash 40 | cargo +nightly bench 41 | ``` 42 | 43 | ## License 44 | 45 | The crates in this repository are licensed under either of the following licenses, at your discretion. 46 | 47 | * Apache License Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 48 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 49 | 50 | Unless you explicitly state otherwise, any contribution submitted for inclusion in this library by you shall be dual licensed as above (as defined in the Apache v2 License), without any additional terms or conditions. 51 | 52 | [zexe]: https://ia.cr/2018/962 53 | 54 | ## Acknowledgements 55 | 56 | This work was supported by: 57 | a Google Faculty Award; 58 | the National Science Foundation; 59 | the UC Berkeley Center for Long-Term Cybersecurity; 60 | and donations from the Ethereum Foundation, the Interchain Foundation, and Qtum. 61 | 62 | An earlier version of this library was developed as part of the paper *"[ZEXE: Enabling Decentralized Private Computation][zexe]"*. 63 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - master 7 | env: 8 | RUST_BACKTRACE: 1 9 | 10 | jobs: 11 | style: 12 | name: Check Style 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v2 17 | - name: Install Rust 18 | uses: actions-rs/toolchain@v1 19 | with: 20 | profile: minimal 21 | toolchain: stable 22 | override: true 23 | components: rustfmt 24 | 25 | - name: cargo fmt --check 26 | uses: actions-rs/cargo@v1 27 | with: 28 | command: fmt 29 | args: --all -- --check 30 | 31 | test: 32 | name: Test 33 | runs-on: ubuntu-latest 34 | env: 35 | RUSTFLAGS: -Dwarnings 36 | strategy: 37 | matrix: 38 | rust: 39 | - stable 40 | - nightly 41 | steps: 42 | - name: Checkout 43 | uses: actions/checkout@v2 44 | 45 | - name: Install Rust (${{ matrix.rust }}) 46 | uses: actions-rs/toolchain@v1 47 | with: 48 | profile: minimal 49 | toolchain: ${{ matrix.rust }} 50 | override: true 51 | 52 | - uses: actions/cache@v4 53 | with: 54 | path: | 55 | ~/.cargo/registry 56 | ~/.cargo/git 57 | target 58 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 59 | 60 | - name: Check examples 61 | uses: actions-rs/cargo@v1 62 | with: 63 | command: check 64 | args: --examples --all 65 | 66 | - name: Check examples with all features on stable 67 | uses: actions-rs/cargo@v1 68 | with: 69 | command: check 70 | args: --examples --all-features --all 71 | if: matrix.rust == 'stable' 72 | 73 | - name: Check benchmarks on nightly 74 | uses: actions-rs/cargo@v1 75 | with: 76 | command: check 77 | args: --all-features --examples --all --benches 78 | if: matrix.rust == 'nightly' 79 | 80 | - name: Test 81 | uses: actions-rs/cargo@v1 82 | with: 83 | command: test 84 | args: "--all \ 85 | --all-features" 86 | 87 | check_no_std: 88 | name: Check no_std 89 | runs-on: ubuntu-latest 90 | steps: 91 | - name: Checkout 92 | uses: actions/checkout@v2 93 | 94 | - name: Install Rust (${{ matrix.rust }}) 95 | uses: actions-rs/toolchain@v1 96 | with: 97 | toolchain: stable 98 | target: thumbv6m-none-eabi 99 | override: true 100 | 101 | - name: Install Rust ARM64 (${{ matrix.rust }}) 102 | uses: actions-rs/toolchain@v1 103 | with: 104 | toolchain: stable 105 | target: aarch64-unknown-none 106 | override: true 107 | 108 | - uses: actions/cache@v4 109 | with: 110 | path: | 111 | ~/.cargo/registry 112 | ~/.cargo/git 113 | target 114 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 115 | 116 | - name: ark-std 117 | run: | 118 | cargo build -p ark-std --no-default-features --target thumbv6m-none-eabi 119 | cargo check --examples -p ark-std --no-default-features --target thumbv6m-none-eabi 120 | -------------------------------------------------------------------------------- /src/rand_helper.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "std")] 2 | use rand::RngCore; 3 | use rand::{ 4 | distributions::{Distribution, Standard}, 5 | prelude::StdRng, 6 | Rng, 7 | }; 8 | 9 | pub use rand; 10 | 11 | pub trait UniformRand: Sized { 12 | fn rand(rng: &mut R) -> Self; 13 | } 14 | 15 | impl UniformRand for T 16 | where 17 | Standard: Distribution, 18 | { 19 | #[inline] 20 | fn rand(rng: &mut R) -> Self { 21 | rng.sample(Standard) 22 | } 23 | } 24 | 25 | fn test_rng_helper() -> StdRng { 26 | use rand::SeedableRng; 27 | // arbitrary seed 28 | let seed = [ 29 | 1, 0, 0, 0, 23, 0, 0, 0, 200, 1, 0, 0, 210, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30 | 0, 0, 0, 0, 31 | ]; 32 | rand::rngs::StdRng::from_seed(seed) 33 | } 34 | 35 | /// Should be used only for tests, not for any real world usage. 36 | #[cfg(not(feature = "std"))] 37 | pub fn test_rng() -> impl rand::Rng { 38 | test_rng_helper() 39 | } 40 | 41 | /// Should be used only for tests, not for any real world usage. 42 | #[cfg(feature = "std")] 43 | pub fn test_rng() -> impl rand::Rng { 44 | #[cfg(any(feature = "getrandom", test))] 45 | { 46 | let is_deterministic = 47 | std::env::vars().any(|(key, val)| key == "DETERMINISTIC_TEST_RNG" && val == "1"); 48 | if is_deterministic { 49 | RngWrapper::Deterministic(test_rng_helper()) 50 | } else { 51 | RngWrapper::Randomized(rand::thread_rng()) 52 | } 53 | } 54 | #[cfg(not(any(feature = "getrandom", test)))] 55 | { 56 | RngWrapper::Deterministic(test_rng_helper()) 57 | } 58 | } 59 | 60 | /// Helper wrapper to enable `test_rng` to return `impl::Rng`. 61 | #[cfg(feature = "std")] 62 | enum RngWrapper { 63 | Deterministic(StdRng), 64 | #[cfg(any(feature = "getrandom", test))] 65 | Randomized(rand::rngs::ThreadRng), 66 | } 67 | 68 | #[cfg(feature = "std")] 69 | impl RngCore for RngWrapper { 70 | #[inline(always)] 71 | fn next_u32(&mut self) -> u32 { 72 | match self { 73 | Self::Deterministic(rng) => rng.next_u32(), 74 | #[cfg(any(feature = "getrandom", test))] 75 | Self::Randomized(rng) => rng.next_u32(), 76 | } 77 | } 78 | 79 | #[inline(always)] 80 | fn next_u64(&mut self) -> u64 { 81 | match self { 82 | Self::Deterministic(rng) => rng.next_u64(), 83 | #[cfg(any(feature = "getrandom", test))] 84 | Self::Randomized(rng) => rng.next_u64(), 85 | } 86 | } 87 | 88 | #[inline(always)] 89 | fn fill_bytes(&mut self, dest: &mut [u8]) { 90 | match self { 91 | Self::Deterministic(rng) => rng.fill_bytes(dest), 92 | #[cfg(any(feature = "getrandom", test))] 93 | Self::Randomized(rng) => rng.fill_bytes(dest), 94 | } 95 | } 96 | 97 | #[inline(always)] 98 | fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { 99 | match self { 100 | Self::Deterministic(rng) => rng.try_fill_bytes(dest), 101 | #[cfg(any(feature = "getrandom", test))] 102 | Self::Randomized(rng) => rng.try_fill_bytes(dest), 103 | } 104 | } 105 | } 106 | 107 | #[cfg(all(test, feature = "std"))] 108 | mod test { 109 | #[test] 110 | fn test_deterministic_rng() { 111 | use super::*; 112 | 113 | let mut rng = super::test_rng(); 114 | let a = u128::rand(&mut rng); 115 | 116 | // Reset the rng by sampling a new one. 117 | let mut rng = super::test_rng(); 118 | let b = u128::rand(&mut rng); 119 | assert_ne!(a, b); // should be unequal with high probability. 120 | 121 | // Let's make the rng deterministic. 122 | std::env::set_var("DETERMINISTIC_TEST_RNG", "1"); 123 | let mut rng = super::test_rng(); 124 | let a = u128::rand(&mut rng); 125 | 126 | // Reset the rng by sampling a new one. 127 | let mut rng = super::test_rng(); 128 | let b = u128::rand(&mut rng); 129 | assert_eq!(a, b); // should be equal with high probability. 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/iterable/mod.rs: -------------------------------------------------------------------------------- 1 | //! A base library for interfacing with streams of vectors and matrices. 2 | //! 3 | //! This library presents the abstraction layer for the _streaming model_. 4 | //! Essentially, it provides a set of handy utilities as a wrapper around 5 | //! iterators. 6 | 7 | mod rev; 8 | pub use rev::Reverse; 9 | 10 | /// The trait [`Iterable`] represents a streamable object that can produce 11 | /// an arbitrary number of streams of length [`Iterable::len`](Iterable::len). 12 | /// 13 | /// An Iterable is pretty much like an [`IntoIterator`] that can be copied over 14 | /// and over, and has an hint of the length. Copies are meant to be shared 15 | /// across threads safely. 16 | /// 17 | /// # Examples 18 | /// 19 | /// ``` 20 | /// use ark_std::borrow::Borrow; 21 | /// use ark_std::iterable::Iterable; 22 | /// 23 | /// // Relying only on standard library 24 | /// fn f(xs: impl IntoIterator> + Clone) -> u32 { 25 | /// xs.clone().into_iter().fold(1, |x, y| x.borrow() * y.borrow()) + 26 | /// xs.clone().into_iter().fold(0, |x, y| x.borrow() + y.borrow()) + 27 | /// xs.into_iter().size_hint().0 as u32 28 | /// } 29 | /// 30 | /// // Relying on the trait below 31 | /// fn g(xs: impl Iterable>) -> u32 { 32 | /// xs.iter().fold(1, |x, y| x.borrow() * y.borrow()) + 33 | /// xs.iter().fold(0, |x, y| x.borrow() + y.borrow()) + 34 | /// xs.len() as u32 35 | /// } 36 | /// 37 | /// // Test over a slice (which implements both traits). 38 | /// let xs = &[1, 2, 3, 4]; 39 | /// assert_eq!(f(xs), g(xs)); 40 | /// ``` 41 | /// 42 | /// # Efficency 43 | /// 44 | /// For efficiency, functions using iterables are often times relying on 45 | /// [`Borrow`](std::borrow::Borrow) in order to avoid copying the contents of 46 | /// the iterator.. 47 | /// 48 | /// The `Iter` associated type has a lifetime that is independent from that of 49 | /// the [`Iterable`] object. This means that implicitly a copy of the relevant 50 | /// contents of the object will happen whenever 51 | /// [`Iterable::iter`](crate::iterable::Iterable::iter) is called. This might 52 | /// change in the future as associated type constructors 53 | /// [[RFC1598](https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md#declaring--assigning-an-associated-type-constructor)] 54 | /// stabilize. 55 | /// 56 | /// # Future implementation 57 | /// 58 | /// A lot of stream operations must be performed symbolically. 59 | /// We expect that, in the future, this trait will accommodate for additional 60 | /// streaming function, e.g. `Iterable::hadamard(&self, other: &Iterable)` to 61 | /// perform the Hadamard product of two streams, or `Iterable::add(&self, other: 62 | /// &Iterable)` to perform the addition of two streams. 63 | pub trait Iterable: Send + Sync { 64 | /// The type of the element being streamed. 65 | type Item; 66 | /// The type of the iterator being generated. 67 | type Iter: Iterator; 68 | 69 | /// Return the iterator associated to the current instance. 70 | /// 71 | /// In the so-called _streaming model_ [BCHO22], this is equivalent to 72 | /// instantiating a new stream tape. 73 | /// For base types, this acts in the same way as the `.iter()` method. 74 | /// 75 | /// ``` 76 | /// use ark_std::iterable::Iterable; 77 | /// 78 | /// let x = &[1, 2, 4]; 79 | /// let mut iterator = x.iter(); 80 | /// ``` 81 | fn iter(&self) -> Self::Iter; 82 | 83 | /// Return a hint on the length of the stream. 84 | /// 85 | /// Careful: different objects might have different indications of what 86 | /// _length_ means; this might not be the actual size in terms of 87 | /// elements. 88 | fn len(&self) -> usize; 89 | 90 | /// Return `true` if the stream is empty, else `false`. 91 | fn is_empty(&self) -> bool { 92 | self.len() == 0 93 | } 94 | } 95 | 96 | impl Iterable for I 97 | where 98 | I: IntoIterator + Copy + Send + Sync, 99 | I::IntoIter: ExactSizeIterator, 100 | { 101 | type Item = ::Item; 102 | type Iter = ::IntoIter; 103 | 104 | fn iter(&self) -> Self::Iter { 105 | self.into_iter() 106 | } 107 | 108 | fn len(&self) -> usize { 109 | self.into_iter().len() 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | 3 | #[cfg(not(feature = "std"))] 4 | #[doc(hidden)] 5 | extern crate alloc; 6 | 7 | #[cfg(not(feature = "std"))] 8 | pub use alloc::*; 9 | 10 | #[cfg(not(feature = "std"))] 11 | pub use core::*; 12 | 13 | #[cfg(not(feature = "std"))] 14 | pub mod fmt { 15 | pub use alloc::fmt::*; 16 | pub use core::fmt::*; 17 | } 18 | 19 | #[cfg(not(feature = "std"))] 20 | pub mod borrow { 21 | pub use alloc::borrow::*; 22 | pub use core::borrow::*; 23 | } 24 | 25 | #[cfg(not(feature = "std"))] 26 | pub mod slice { 27 | pub use alloc::slice::*; 28 | pub use core::slice::*; 29 | } 30 | 31 | #[cfg(not(feature = "std"))] 32 | pub mod str { 33 | pub use alloc::str::*; 34 | pub use core::str::*; 35 | } 36 | 37 | #[cfg(not(feature = "std"))] 38 | pub mod io; 39 | 40 | #[cfg(feature = "std")] 41 | #[doc(hidden)] 42 | pub use std::*; 43 | 44 | #[cfg(target_has_atomic = "ptr")] 45 | #[doc(hidden)] 46 | pub mod sync { 47 | #[cfg(not(feature = "std"))] 48 | pub use alloc::sync::*; 49 | #[cfg(feature = "std")] 50 | pub use std::sync::*; 51 | } 52 | 53 | mod rand_helper; 54 | pub use rand_helper::*; 55 | 56 | pub mod perf_trace; 57 | 58 | pub mod iterable; 59 | 60 | pub use num_traits::{One, Zero}; 61 | 62 | /// Returns the ceiling of the base-2 logarithm of `x`. 63 | /// 64 | /// ``` 65 | /// use ark_std::log2; 66 | /// 67 | /// assert_eq!(log2(16), 4); 68 | /// assert_eq!(log2(17), 5); 69 | /// assert_eq!(log2(1), 0); 70 | /// assert_eq!(log2(0), 0); 71 | /// assert_eq!(log2(usize::MAX), (core::mem::size_of::() * 8) as u32); 72 | /// assert_eq!(log2(1 << 15), 15); 73 | /// assert_eq!(log2(2usize.pow(18)), 18); 74 | /// ``` 75 | #[inline(always)] 76 | pub const fn log2(x: usize) -> u32 { 77 | if x == 0 { 78 | 0 79 | } else if x.is_power_of_two() { 80 | 1usize.leading_zeros() - x.leading_zeros() 81 | } else { 82 | 0usize.leading_zeros() - x.leading_zeros() 83 | } 84 | } 85 | 86 | /// Creates parallel iterator over refs if `parallel` feature is enabled. 87 | /// Additionally, if the object being iterated implements 88 | /// `IndexedParallelIterator`, then one can specify a minimum size for 89 | /// iteration. 90 | #[macro_export] 91 | macro_rules! cfg_iter { 92 | ($e: expr, $min_len: expr) => {{ 93 | #[cfg(feature = "parallel")] 94 | let result = $e.par_iter().with_min_len($min_len); 95 | 96 | #[cfg(not(feature = "parallel"))] 97 | let result = $e.iter(); 98 | 99 | result 100 | }}; 101 | ($e: expr) => {{ 102 | #[cfg(feature = "parallel")] 103 | let result = $e.par_iter(); 104 | 105 | #[cfg(not(feature = "parallel"))] 106 | let result = $e.iter(); 107 | 108 | result 109 | }}; 110 | } 111 | 112 | /// Creates parallel iterator over mut refs if `parallel` feature is enabled. 113 | /// Additionally, if the object being iterated implements 114 | /// `IndexedParallelIterator`, then one can specify a minimum size for 115 | /// iteration. 116 | #[macro_export] 117 | macro_rules! cfg_iter_mut { 118 | ($e: expr, $min_len: expr) => {{ 119 | #[cfg(feature = "parallel")] 120 | let result = $e.par_iter_mut().with_min_len($min_len); 121 | 122 | #[cfg(not(feature = "parallel"))] 123 | let result = $e.iter_mut(); 124 | 125 | result 126 | }}; 127 | ($e: expr) => {{ 128 | #[cfg(feature = "parallel")] 129 | let result = $e.par_iter_mut(); 130 | 131 | #[cfg(not(feature = "parallel"))] 132 | let result = $e.iter_mut(); 133 | 134 | result 135 | }}; 136 | } 137 | 138 | /// Creates parallel iterator if `parallel` feature is enabled. 139 | /// Additionally, if the object being iterated implements 140 | /// `IndexedParallelIterator`, then one can specify a minimum size for 141 | /// iteration. 142 | #[macro_export] 143 | macro_rules! cfg_into_iter { 144 | ($e: expr, $min_len: expr) => {{ 145 | #[cfg(feature = "parallel")] 146 | let result = $e.into_par_iter().with_min_len($min_len); 147 | 148 | #[cfg(not(feature = "parallel"))] 149 | let result = $e.into_iter(); 150 | 151 | result 152 | }}; 153 | ($e: expr) => {{ 154 | #[cfg(feature = "parallel")] 155 | let result = $e.into_par_iter(); 156 | 157 | #[cfg(not(feature = "parallel"))] 158 | let result = $e.into_iter(); 159 | 160 | result 161 | }}; 162 | } 163 | 164 | /// Returns an iterator over `chunk_size` elements of the slice at a 165 | /// time. 166 | #[macro_export] 167 | macro_rules! cfg_chunks { 168 | ($e: expr, $size: expr) => {{ 169 | #[cfg(feature = "parallel")] 170 | let result = $e.par_chunks($size); 171 | 172 | #[cfg(not(feature = "parallel"))] 173 | let result = $e.chunks($size); 174 | 175 | result 176 | }}; 177 | } 178 | 179 | /// Returns an iterator over `chunk_size` mutable elements of the slice at a 180 | /// time. 181 | #[macro_export] 182 | macro_rules! cfg_chunks_mut { 183 | ($e: expr, $size: expr) => {{ 184 | #[cfg(feature = "parallel")] 185 | let result = $e.par_chunks_mut($size); 186 | 187 | #[cfg(not(feature = "parallel"))] 188 | let result = $e.chunks_mut($size); 189 | 190 | result 191 | }}; 192 | } 193 | 194 | /// Executes two closures. If `parallel` feature is enabled, the closures 195 | /// are executed in parallel using `rayon::join`. Otherwise, they are 196 | /// executed sequentially. The result is returned as a tuple. 197 | /// 198 | /// ```rust 199 | /// # use ark_std::cfg_join; 200 | /// let (two, five) = cfg_join!(|| { 1 + 1 }, || { 2 + 3 }); 201 | /// # assert_eq!(two, 2); 202 | /// # assert_eq!(five, 5); 203 | /// ``` 204 | /// 205 | /// The macro can also be nested to join more than two closures: 206 | /// ``` 207 | /// # use ark_std::cfg_join; 208 | /// 209 | /// let (two, (five, seven)) = 210 | /// cfg_join!(|| { 1 + 1 }, || cfg_join!(|| { 2 + 3 }, || { 1 + 6 })); 211 | /// # assert_eq!(two, 2); 212 | /// # assert_eq!(five, 5); 213 | /// # assert_eq!(seven, 7); 214 | /// ``` 215 | #[macro_export] 216 | macro_rules! cfg_join { 217 | ($e1: expr, $e2: expr) => {{ 218 | #[cfg(feature = "parallel")] 219 | let result = rayon::join($e1, $e2); 220 | 221 | #[cfg(not(feature = "parallel"))] 222 | let result = ($e1(), $e2()); 223 | 224 | result 225 | }}; 226 | } 227 | 228 | #[cfg(test)] 229 | mod test { 230 | use super::*; 231 | #[cfg(feature = "parallel")] 232 | use rayon::prelude::*; 233 | 234 | #[test] 235 | fn test_cfg_macros() { 236 | #[cfg(feature = "parallel")] 237 | println!("In parallel mode"); 238 | 239 | let mut thing = crate::vec![1, 2, 3, 4, 5u64]; 240 | println!("Iterating"); 241 | cfg_iter!(&thing).for_each(|i| println!("{:?}", i)); 242 | println!("Iterating Mut"); 243 | cfg_iter_mut!(&mut thing).for_each(|i| *i += 1); 244 | println!("Iterating By Value"); 245 | cfg_into_iter!(thing.clone()).for_each(|i| println!("{:?}", i)); 246 | println!("Chunks"); 247 | cfg_chunks!(&thing, 2).for_each(|chunk| println!("{:?}", chunk)); 248 | println!("Chunks Mut"); 249 | cfg_chunks_mut!(&mut thing, 2).for_each(|chunk| println!("{:?}", chunk)); 250 | 251 | println!("Iterating"); 252 | cfg_iter!(&thing, 3).for_each(|i| println!("{:?}", i)); 253 | println!("Iterating Mut"); 254 | cfg_iter_mut!(&mut thing, 3).for_each(|i| *i += 1); 255 | println!("Iterating By Value"); 256 | cfg_into_iter!(thing, 3).for_each(|i| println!("{:?}", i)); 257 | 258 | println!("Joining"); 259 | cfg_join!( 260 | || { 261 | println!("In first"); 262 | }, 263 | || { 264 | println!("In second"); 265 | } 266 | ); 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /src/perf_trace.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports)] 2 | //! This module contains macros for logging to stdout a trace of wall-clock time 3 | //! required to execute annotated code. One can use this code as follows: 4 | //! ``` 5 | //! use ark_std::{start_timer, end_timer}; 6 | //! let start = start_timer!(|| "Addition of two integers"); 7 | //! let c = 5 + 7; 8 | //! end_timer!(start); 9 | //! ``` 10 | //! The foregoing code should log the following to stdout. 11 | //! ```text 12 | //! Start: Addition of two integers 13 | //! End: Addition of two integers... 1ns 14 | //! ``` 15 | //! 16 | //! These macros can be arbitrarily nested, and the nested nature is made 17 | //! apparent in the output. For example, the following snippet: 18 | //! ``` 19 | //! use ark_std::{start_timer, end_timer}; 20 | //! let start = start_timer!(|| "Addition of two integers"); 21 | //! let start2 = start_timer!(|| "Inner"); 22 | //! let c = 5 + 7; 23 | //! end_timer!(start2); 24 | //! end_timer!(start); 25 | //! ``` 26 | //! should print out the following: 27 | //! ```text 28 | //! Start: Addition of two integers 29 | //! Start: Inner 30 | //! End: Inner ... 1ns 31 | //! End: Addition of two integers... 1ns 32 | //! ``` 33 | //! 34 | //! Additionally, one can use the `add_to_trace` macro to log additional context 35 | //! in the output. 36 | pub use self::inner::*; 37 | 38 | #[macro_use] 39 | #[cfg(feature = "print-trace")] 40 | pub mod inner { 41 | pub use colored::Colorize; 42 | 43 | // print-trace requires std, so these imports are well-defined 44 | pub use std::{ 45 | format, println, 46 | string::{String, ToString}, 47 | sync::atomic::{AtomicUsize, Ordering}, 48 | time::Instant, 49 | }; 50 | 51 | pub static NUM_INDENT: AtomicUsize = AtomicUsize::new(0); 52 | pub const PAD_CHAR: &str = "·"; 53 | 54 | pub struct TimerInfo { 55 | pub msg: String, 56 | pub time: Instant, 57 | } 58 | 59 | #[macro_export] 60 | macro_rules! start_timer { 61 | ($msg:expr) => {{ 62 | use $crate::perf_trace::inner::{ 63 | compute_indent, AtomicUsize, Colorize, Instant, Ordering, ToString, NUM_INDENT, 64 | PAD_CHAR, 65 | }; 66 | 67 | let msg = $msg(); 68 | let start_info = "Start:".yellow().bold(); 69 | let indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed); 70 | let indent = compute_indent(indent_amount); 71 | 72 | $crate::perf_trace::println!("{}{:8} {}", indent, start_info, msg); 73 | NUM_INDENT.fetch_add(1, Ordering::Relaxed); 74 | $crate::perf_trace::TimerInfo { 75 | msg: msg.to_string(), 76 | time: Instant::now(), 77 | } 78 | }}; 79 | } 80 | 81 | #[macro_export] 82 | macro_rules! end_timer { 83 | ($time:expr) => {{ 84 | end_timer!($time, || ""); 85 | }}; 86 | ($time:expr, $msg:expr) => {{ 87 | use $crate::perf_trace::inner::{ 88 | compute_indent, format, AtomicUsize, Colorize, Instant, Ordering, ToString, 89 | NUM_INDENT, PAD_CHAR, 90 | }; 91 | 92 | let time = $time.time; 93 | let final_time = time.elapsed(); 94 | let final_time = { 95 | let secs = final_time.as_secs(); 96 | let millis = final_time.subsec_millis(); 97 | let micros = final_time.subsec_micros() % 1000; 98 | let nanos = final_time.subsec_nanos() % 1000; 99 | if secs != 0 { 100 | format!("{}.{:03}s", secs, millis).bold() 101 | } else if millis > 0 { 102 | format!("{}.{:03}ms", millis, micros).bold() 103 | } else if micros > 0 { 104 | format!("{}.{:03}µs", micros, nanos).bold() 105 | } else { 106 | format!("{}ns", final_time.subsec_nanos()).bold() 107 | } 108 | }; 109 | 110 | let end_info = "End:".green().bold(); 111 | let message = format!("{} {}", $time.msg, $msg()); 112 | 113 | NUM_INDENT.fetch_sub(1, Ordering::Relaxed); 114 | let indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed); 115 | let indent = compute_indent(indent_amount); 116 | 117 | // Todo: Recursively ensure that *entire* string is of appropriate 118 | // width (not just message). 119 | $crate::perf_trace::println!( 120 | "{}{:8} {:. {{ 133 | use $crate::perf_trace::{ 134 | compute_indent, compute_indent_whitespace, format, AtomicUsize, Colorize, Instant, 135 | Ordering, ToString, NUM_INDENT, PAD_CHAR, 136 | }; 137 | 138 | let start_msg = "StartMsg".yellow().bold(); 139 | let end_msg = "EndMsg".green().bold(); 140 | let title = $title(); 141 | let start_msg = format!("{}: {}", start_msg, title); 142 | let end_msg = format!("{}: {}", end_msg, title); 143 | 144 | let start_indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed); 145 | let start_indent = compute_indent(start_indent_amount); 146 | 147 | let msg_indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed) + 2; 148 | let msg_indent = compute_indent_whitespace(msg_indent_amount); 149 | let mut final_message = "\n".to_string(); 150 | for line in $msg().lines() { 151 | final_message += &format!("{}{}\n", msg_indent, line,); 152 | } 153 | 154 | // Todo: Recursively ensure that *entire* string is of appropriate 155 | // width (not just message). 156 | $crate::perf_trace::println!("{}{}", start_indent, start_msg); 157 | $crate::perf_trace::println!("{}{}", msg_indent, final_message,); 158 | $crate::perf_trace::println!("{}{}", start_indent, end_msg); 159 | }}; 160 | } 161 | 162 | #[macro_export] 163 | macro_rules! add_single_trace { 164 | ($title:expr) => {{ 165 | use $crate::perf_trace::{ 166 | compute_indent, compute_indent_whitespace, format, AtomicUsize, Colorize, Instant, 167 | Ordering, ToString, NUM_INDENT, PAD_CHAR, 168 | }; 169 | 170 | let start_msg = "Trace".blue().bold(); 171 | let title = $title(); 172 | let start_msg = format!("{}: {}", start_msg, title); 173 | 174 | let indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed); 175 | let indent = compute_indent(indent_amount); 176 | 177 | // Todo: Recursively ensure that *entire* string is of appropriate 178 | // width (not just message). 179 | $crate::perf_trace::println!("{}{}", indent, start_msg); 180 | }}; 181 | } 182 | 183 | pub fn compute_indent_whitespace(indent_amount: usize) -> String { 184 | let mut indent = String::new(); 185 | for _ in 0..indent_amount { 186 | indent.push_str(" "); 187 | } 188 | indent 189 | } 190 | 191 | pub fn compute_indent(indent_amount: usize) -> String { 192 | let mut indent = String::new(); 193 | for _ in 0..indent_amount { 194 | indent.push_str(&PAD_CHAR.white()); 195 | } 196 | indent 197 | } 198 | } 199 | 200 | #[macro_use] 201 | #[cfg(not(feature = "print-trace"))] 202 | mod inner { 203 | pub struct TimerInfo; 204 | 205 | #[macro_export] 206 | macro_rules! start_timer { 207 | ($msg:expr) => {{ 208 | let _ = $msg; 209 | $crate::perf_trace::TimerInfo 210 | }}; 211 | } 212 | #[macro_export] 213 | macro_rules! add_to_trace { 214 | ($title:expr, $msg:expr) => { 215 | let _ = $msg; 216 | let _ = $title; 217 | }; 218 | } 219 | #[macro_export] 220 | macro_rules! add_single_trace { 221 | ($msg:expr) => {{ 222 | let _ = $msg; 223 | $crate::perf_trace::TimerInfo 224 | }}; 225 | } 226 | #[macro_export] 227 | macro_rules! end_timer { 228 | ($time:expr, $msg:expr) => { 229 | let _ = $msg; 230 | let _ = $time; 231 | }; 232 | ($time:expr) => { 233 | let _ = $time; 234 | }; 235 | } 236 | } 237 | 238 | mod tests { 239 | use super::*; 240 | 241 | #[test] 242 | fn print_start_end() { 243 | let start = start_timer!(|| "Hello"); 244 | end_timer!(start); 245 | } 246 | 247 | #[test] 248 | fn print_add() { 249 | add_single_trace!(|| "Hello"); 250 | let start = start_timer!(|| "Hello"); 251 | add_single_trace!(|| "HelloWorld"); 252 | add_to_trace!(|| "HelloMsg", || "Hello, I\nAm\nA\nMessage"); 253 | end_timer!(start); 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /src/io/error.rs: -------------------------------------------------------------------------------- 1 | use crate::boxed::Box; 2 | use crate::convert::From; 3 | use crate::error; 4 | use crate::fmt; 5 | 6 | /// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and 7 | /// associated traits. 8 | /// 9 | /// Errors mostly originate from the underlying OS, but custom instances of 10 | /// `Error` can be created with crafted error messages and a particular value of 11 | /// [`ErrorKind`]. 12 | /// 13 | /// [`Read`]: crate::io::Read 14 | /// [`Write`]: crate::io::Write 15 | /// [`Seek`]: crate::io::Seek 16 | pub struct Error { 17 | repr: Repr, 18 | } 19 | 20 | pub type Result = core::result::Result; 21 | 22 | impl fmt::Debug for Error { 23 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 24 | fmt::Debug::fmt(&self.repr, f) 25 | } 26 | } 27 | 28 | enum Repr { 29 | Simple(ErrorKind), 30 | Custom(Box), 31 | } 32 | 33 | #[derive(Debug)] 34 | struct Custom { 35 | kind: ErrorKind, 36 | error: Box, 37 | } 38 | 39 | /// A list specifying general categories of I/O error. 40 | /// 41 | /// This list is intended to grow over time and it is not recommended to 42 | /// exhaustively match against it. 43 | /// 44 | /// It is used with the [`io::Error`] type. 45 | /// 46 | /// [`io::Error`]: Error 47 | #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 48 | #[allow(deprecated)] 49 | #[non_exhaustive] 50 | pub enum ErrorKind { 51 | /// An entity was not found, often a file. 52 | NotFound, 53 | /// The operation lacked the necessary privileges to complete. 54 | PermissionDenied, 55 | /// The connection was refused by the remote server. 56 | ConnectionRefused, 57 | /// The connection was reset by the remote server. 58 | ConnectionReset, 59 | /// The connection was aborted (terminated) by the remote server. 60 | ConnectionAborted, 61 | /// The network operation failed because it was not connected yet. 62 | NotConnected, 63 | /// A socket address could not be bound because the address is already in 64 | /// use elsewhere. 65 | AddrInUse, 66 | /// A nonexistent interface was requested or the requested address was not 67 | /// local. 68 | AddrNotAvailable, 69 | /// The operation failed because a pipe was closed. 70 | BrokenPipe, 71 | /// An entity already exists, often a file. 72 | AlreadyExists, 73 | /// The operation needs to block to complete, but the blocking operation was 74 | /// requested to not occur. 75 | WouldBlock, 76 | /// A parameter was incorrect. 77 | InvalidInput, 78 | /// Data not valid for the operation were encountered. 79 | /// 80 | /// Unlike [`InvalidInput`], this typically means that the operation 81 | /// parameters were valid, however the error was caused by malformed 82 | /// input data. 83 | /// 84 | /// For example, a function that reads a file into a string will error with 85 | /// `InvalidData` if the file's contents are not valid UTF-8. 86 | /// 87 | /// [`InvalidInput`]: ErrorKind::InvalidInput 88 | InvalidData, 89 | /// The I/O operation's timeout expired, causing it to be canceled. 90 | TimedOut, 91 | /// An error returned when an operation could not be completed because a 92 | /// call to [`write`] returned [`Ok(0)`]. 93 | /// 94 | /// This typically means that an operation could only succeed if it wrote a 95 | /// particular number of bytes but only a smaller number of bytes could be 96 | /// written. 97 | /// 98 | /// [`write`]: crate::io::Write::write 99 | /// [`Ok(0)`]: Ok 100 | WriteZero, 101 | /// This operation was interrupted. 102 | /// 103 | /// Interrupted operations can typically be retried. 104 | Interrupted, 105 | /// Any I/O error not part of this list. 106 | /// 107 | /// Errors that are `Other` now may move to a different or a new 108 | /// [`ErrorKind`] variant in the future. It is not recommended to match 109 | /// an error against `Other` and to expect any additional characteristics, 110 | /// e.g., a specific [`Error::raw_os_error`] return value. 111 | Other, 112 | 113 | /// An error returned when an operation could not be completed because an 114 | /// "end of file" was reached prematurely. 115 | /// 116 | /// This typically means that an operation could only succeed if it read a 117 | /// particular number of bytes but only a smaller number of bytes could be 118 | /// read. 119 | UnexpectedEof, 120 | } 121 | 122 | impl ErrorKind { 123 | pub(crate) fn as_str(&self) -> &'static str { 124 | match *self { 125 | ErrorKind::NotFound => "entity not found", 126 | ErrorKind::PermissionDenied => "permission denied", 127 | ErrorKind::ConnectionRefused => "connection refused", 128 | ErrorKind::ConnectionReset => "connection reset", 129 | ErrorKind::ConnectionAborted => "connection aborted", 130 | ErrorKind::NotConnected => "not connected", 131 | ErrorKind::AddrInUse => "address in use", 132 | ErrorKind::AddrNotAvailable => "address not available", 133 | ErrorKind::BrokenPipe => "broken pipe", 134 | ErrorKind::AlreadyExists => "entity already exists", 135 | ErrorKind::WouldBlock => "operation would block", 136 | ErrorKind::InvalidInput => "invalid input parameter", 137 | ErrorKind::InvalidData => "invalid data", 138 | ErrorKind::TimedOut => "timed out", 139 | ErrorKind::WriteZero => "write zero", 140 | ErrorKind::Interrupted => "operation interrupted", 141 | ErrorKind::Other => "other os error", 142 | ErrorKind::UnexpectedEof => "unexpected end of file", 143 | } 144 | } 145 | } 146 | 147 | /// Intended for use for errors not exposed to the user, where allocating onto 148 | /// the heap (for normal construction via Error::new) is too costly. 149 | impl From for Error { 150 | /// Converts an [`ErrorKind`] into an [`Error`]. 151 | /// 152 | /// This conversion allocates a new error with a simple representation of error kind. 153 | /// 154 | /// # Examples 155 | /// 156 | /// ``` 157 | /// use ark_std::io::{Error, ErrorKind}; 158 | /// 159 | /// let not_found = ErrorKind::NotFound; 160 | /// let error = Error::from(not_found); 161 | /// assert_eq!("entity not found", format!("{}", error)); 162 | /// ``` 163 | #[inline] 164 | fn from(kind: ErrorKind) -> Error { 165 | Error { 166 | repr: Repr::Simple(kind), 167 | } 168 | } 169 | } 170 | 171 | impl Error { 172 | /// Creates a new I/O error from a known kind of error as well as an 173 | /// arbitrary error payload. 174 | /// 175 | /// This function is used to generically create I/O errors which do not 176 | /// originate from the OS itself. The `error` argument is an arbitrary 177 | /// payload which will be contained in this [`Error`]. 178 | /// 179 | /// # Examples 180 | /// 181 | /// ``` 182 | /// use ark_std::io::{Error, ErrorKind}; 183 | /// 184 | /// // errors can be created from strings 185 | /// let custom_error = Error::new(ErrorKind::Other, "oh no!"); 186 | /// 187 | /// // errors can also be created from other errors 188 | /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error); 189 | /// ``` 190 | pub fn new(kind: ErrorKind, error: E) -> Error 191 | where 192 | E: Into>, 193 | { 194 | Self::_new(kind, error.into()) 195 | } 196 | 197 | fn _new(kind: ErrorKind, error: Box) -> Error { 198 | Error { 199 | repr: Repr::Custom(Box::new(Custom { kind, error })), 200 | } 201 | } 202 | 203 | pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> { 204 | match self.repr { 205 | Repr::Simple(..) => None, 206 | Repr::Custom(ref c) => Some(&*c.error), 207 | } 208 | } 209 | 210 | pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> { 211 | match self.repr { 212 | Repr::Simple(..) => None, 213 | Repr::Custom(ref mut c) => Some(&mut *c.error), 214 | } 215 | } 216 | 217 | /// Consumes the `Error`, returning its inner error (if any). 218 | /// 219 | /// If this [`Error`] was constructed via [`new`] then this function will 220 | /// return [`Some`], otherwise it will return [`None`]. 221 | /// 222 | /// [`new`]: Error::new 223 | pub fn into_inner(self) -> Option> { 224 | match self.repr { 225 | Repr::Simple(..) => None, 226 | Repr::Custom(c) => Some(c.error), 227 | } 228 | } 229 | 230 | /// Returns the corresponding [`ErrorKind`] for this error. 231 | pub fn kind(&self) -> ErrorKind { 232 | match self.repr { 233 | Repr::Custom(ref c) => c.kind, 234 | Repr::Simple(kind) => kind, 235 | } 236 | } 237 | } 238 | 239 | impl fmt::Debug for Repr { 240 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { 241 | match *self { 242 | Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt), 243 | Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(), 244 | } 245 | } 246 | } 247 | 248 | impl fmt::Display for Error { 249 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { 250 | match self.repr { 251 | Repr::Custom(ref c) => c.error.fmt(fmt), 252 | Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()), 253 | } 254 | } 255 | } 256 | 257 | impl error::Error for Error { 258 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { 259 | match self.repr { 260 | Repr::Simple(..) => None, 261 | Repr::Custom(ref c) => c.error.source(), 262 | } 263 | } 264 | } 265 | 266 | fn _assert_error_is_sync_send() { 267 | fn _is_sync_send() {} 268 | _is_sync_send::(); 269 | } 270 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/io/mod.rs: -------------------------------------------------------------------------------- 1 | //! no-std io replacement 2 | use crate::{cmp, convert::TryInto, mem, vec::Vec}; 3 | 4 | mod error; 5 | pub use error::*; 6 | 7 | pub mod prelude { 8 | pub use super::{Read, Result, Write}; 9 | } 10 | 11 | /// The `Read` trait allows for reading bytes from a source. 12 | /// 13 | /// Implementors of the `Read` trait are called 'readers'. 14 | /// 15 | /// Readers are defined by one required method, [`read()`]. Each call to [`read()`] 16 | /// will attempt to pull bytes from this source into a provided buffer. A 17 | /// number of other methods are implemented in terms of [`read()`], giving 18 | /// implementors a number of ways to read bytes while only needing to implement 19 | /// a single method. 20 | /// 21 | /// Readers are intended to be composable with one another. Many implementors 22 | /// throughout [`ark_std::io`] take and provide types which implement the `Read` 23 | /// trait. 24 | /// 25 | /// Please note that each call to [`read()`] may involve a system call, and 26 | /// therefore, using something that implements [`BufRead`], such as 27 | /// [`BufReader`], will be more efficient. 28 | /// 29 | /// 30 | /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`: 31 | /// 32 | /// ```no_run 33 | /// # use ark_std::io; 34 | /// use ark_std::io::prelude::*; 35 | /// 36 | /// fn main() -> Result<()> { 37 | /// let mut b = "This string will be read".as_bytes(); 38 | /// let mut buffer = [0; 10]; 39 | /// 40 | /// // read up to 10 bytes 41 | /// b.read(&mut buffer)?; 42 | /// 43 | /// Ok(()) 44 | /// } 45 | /// ``` 46 | /// 47 | /// [`read()`]: trait.Read.html#tymethod.read 48 | /// [`ark_std::io`]: ../../std/io/index.html 49 | /// [`BufRead`]: trait.BufRead.html 50 | /// [`BufReader`]: struct.BufReader.html 51 | /// [`&str`]: ../../std/primitive.str.html 52 | /// [slice]: ../../std/primitive.slice.html 53 | pub trait Read { 54 | /// Pull some bytes from this source into the specified buffer, returning 55 | /// how many bytes were read. 56 | /// 57 | /// This function does not provide any guarantees about whether it blocks 58 | /// waiting for data, but if an object needs to block for a read but cannot 59 | /// it will typically signal this via an [`Err`] return value. 60 | /// 61 | /// If the return value of this method is [`Ok(n)`], then it must be 62 | /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates 63 | /// that the buffer `buf` has been filled in with `n` bytes of data from this 64 | /// source. If `n` is `0`, then it can indicate that the the buffer 65 | /// specified was 0 bytes in length. 66 | /// 67 | /// No guarantees are provided about the contents of `buf` when this 68 | /// function is called, implementations cannot rely on any property of the 69 | /// contents of `buf` being true. It is recommended that implementations 70 | /// only write data to `buf` instead of reading its contents. 71 | /// 72 | /// # Errors 73 | /// 74 | /// If this function encounters any form of I/O or other error, an error 75 | /// variant will be returned. If an error is returned then it must be 76 | /// guaranteed that no bytes were read. 77 | /// 78 | /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read 79 | /// operation should be retried if there is nothing else to do. 80 | /// 81 | fn read(&mut self, buf: &mut [u8]) -> Result; 82 | 83 | /// Read the exact number of bytes required to fill `buf`. 84 | /// 85 | /// This function reads as many bytes as necessary to completely fill the 86 | /// specified buffer `buf`. 87 | /// 88 | /// No guarantees are provided about the contents of `buf` when this 89 | /// function is called, implementations cannot rely on any property of the 90 | /// contents of `buf` being true. It is recommended that implementations 91 | /// only write data to `buf` instead of reading its contents. 92 | /// 93 | /// # Errors 94 | /// 95 | /// If this function encounters an error of the kind 96 | /// [`ErrorKind::Interrupted`] then the error is ignored and the operation 97 | /// will continue. 98 | /// 99 | /// If any other read error is encountered then this function immediately 100 | /// returns. The contents of `buf` are unspecified in this case. 101 | /// 102 | /// If this function returns an error, it is unspecified how many bytes it 103 | /// has read, but it will never read more than would be necessary to 104 | /// completely fill the buffer. 105 | fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> { 106 | while !buf.is_empty() { 107 | match self.read(buf) { 108 | Ok(0) => break, 109 | Ok(n) => { 110 | let tmp = buf; 111 | buf = &mut tmp[n..]; 112 | }, 113 | Err(ref e) if e.kind() == ErrorKind::Interrupted => {}, 114 | Err(e) => return Err(e), 115 | } 116 | } 117 | if !buf.is_empty() { 118 | Err(Error::new( 119 | ErrorKind::UnexpectedEof, 120 | "failed to fill whole buffer", 121 | )) 122 | } else { 123 | Ok(()) 124 | } 125 | } 126 | 127 | /// Creates a "by reference" adaptor for this instance of `Read`. 128 | /// 129 | /// The returned adaptor also implements `Read` and will simply borrow this 130 | /// current reader. 131 | fn by_ref(&mut self) -> &mut Self 132 | where 133 | Self: Sized, 134 | { 135 | self 136 | } 137 | } 138 | 139 | pub trait Write { 140 | /// Write a buffer into this writer, returning how many bytes were written. 141 | /// 142 | /// This function will attempt to write the entire contents of `buf`, but 143 | /// the entire write may not succeed, or the write may also generate an 144 | /// error. A call to `write` represents *at most one* attempt to write to 145 | /// any wrapped object. 146 | /// 147 | /// Calls to `write` are not guaranteed to block waiting for data to be 148 | /// written, and a write which would otherwise block can be indicated through 149 | /// an [`Err`] variant. 150 | /// 151 | /// If the return value is [`Ok(n)`] then it must be guaranteed that 152 | /// `0 <= n <= buf.len()`. A return value of `0` typically means that the 153 | /// underlying object is no longer able to accept bytes and will likely not 154 | /// be able to in the future as well, or that the buffer provided is empty. 155 | /// 156 | /// # Errors 157 | /// 158 | /// Each call to `write` may generate an I/O error indicating that the 159 | /// operation could not be completed. If an error is returned then no bytes 160 | /// in the buffer were written to this writer. 161 | /// 162 | /// It is **not** considered an error if the entire buffer could not be 163 | /// written to this writer. 164 | /// 165 | /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the 166 | /// write operation should be retried if there is nothing else to do. 167 | /// 168 | /// [`Err`]: ../../std/result/enum.Result.html#variant.Err 169 | /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok 170 | /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted 171 | fn write(&mut self, buf: &[u8]) -> Result; 172 | 173 | /// Flush this output stream, ensuring that all intermediately buffered 174 | /// contents reach their destination. 175 | /// 176 | /// # Errors 177 | /// 178 | /// It is considered an error if not all bytes could be written due to 179 | /// I/O errors or EOF being reached. 180 | /// 181 | fn flush(&mut self) -> Result<()>; 182 | 183 | /// Attempts to write an entire buffer into this writer. 184 | /// 185 | /// This method will continuously call [`write`] until there is no more data 186 | /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is 187 | /// returned. This method will not return until the entire buffer has been 188 | /// successfully written or such an error occurs. The first error that is 189 | /// not of [`ErrorKind::Interrupted`] kind generated from this method will be 190 | /// returned. 191 | /// 192 | /// # Errors 193 | /// 194 | /// This function will return the first error of 195 | /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns. 196 | /// 197 | /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted 198 | /// [`write`]: #tymethod.write 199 | fn write_all(&mut self, mut buf: &[u8]) -> Result<()> { 200 | while !buf.is_empty() { 201 | match self.write(buf) { 202 | Ok(0) => { 203 | return Err(Error::new( 204 | ErrorKind::WriteZero, 205 | "failed to write whole buffer", 206 | )) 207 | }, 208 | Ok(n) => buf = &buf[n..], 209 | Err(ref e) if e.kind() == ErrorKind::Interrupted => {}, 210 | Err(e) => return Err(e), 211 | } 212 | } 213 | Ok(()) 214 | } 215 | 216 | /// Creates a "by reference" adaptor for this instance of `Write`. 217 | /// 218 | /// The returned adaptor also implements `Write` and will simply borrow this 219 | /// current writer. 220 | fn by_ref(&mut self) -> &mut Self 221 | where 222 | Self: Sized, 223 | { 224 | self 225 | } 226 | } 227 | 228 | impl Read for &mut R { 229 | #[inline] 230 | fn read(&mut self, buf: &mut [u8]) -> Result { 231 | (**self).read(buf) 232 | } 233 | 234 | #[inline] 235 | fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { 236 | (**self).read_exact(buf) 237 | } 238 | } 239 | 240 | impl Read for &[u8] { 241 | #[inline] 242 | fn read(&mut self, buf: &mut [u8]) -> Result { 243 | let amt = cmp::min(buf.len(), self.len()); 244 | let (a, b) = self.split_at(amt); 245 | 246 | // First check if the amount of bytes we want to read is small: 247 | // `copy_from_slice` will generally expand to a call to `memcpy`, and 248 | // for a single byte the overhead is significant. 249 | if amt == 1 { 250 | buf[0] = a[0]; 251 | } else { 252 | buf[..amt].copy_from_slice(a); 253 | } 254 | 255 | *self = b; 256 | Ok(amt) 257 | } 258 | 259 | #[inline] 260 | fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { 261 | if buf.len() > self.len() { 262 | return Err(Error::new( 263 | ErrorKind::UnexpectedEof, 264 | "failed to fill whole buffer", 265 | )); 266 | } 267 | let (a, b) = self.split_at(buf.len()); 268 | 269 | // First check if the amount of bytes we want to read is small: 270 | // `copy_from_slice` will generally expand to a call to `memcpy`, and 271 | // for a single byte the overhead is significant. 272 | if buf.len() == 1 { 273 | buf[0] = a[0]; 274 | } else { 275 | buf.copy_from_slice(a); 276 | } 277 | 278 | *self = b; 279 | Ok(()) 280 | } 281 | } 282 | 283 | impl Write for &mut W { 284 | #[inline] 285 | fn write(&mut self, buf: &[u8]) -> Result { 286 | (**self).write(buf) 287 | } 288 | 289 | #[inline] 290 | fn flush(&mut self) -> Result<()> { 291 | (**self).flush() 292 | } 293 | 294 | #[inline] 295 | fn write_all(&mut self, buf: &[u8]) -> Result<()> { 296 | (**self).write_all(buf) 297 | } 298 | } 299 | 300 | impl Write for &mut [u8] { 301 | fn write(&mut self, data: &[u8]) -> Result { 302 | let amt = cmp::min(data.len(), self.len()); 303 | let (a, b) = mem::replace(self, &mut []).split_at_mut(amt); 304 | a.copy_from_slice(&data[..amt]); 305 | *self = b; 306 | Ok(amt) 307 | } 308 | 309 | #[inline] 310 | fn write_all(&mut self, data: &[u8]) -> Result<()> { 311 | if self.write(data)? == data.len() { 312 | Ok(()) 313 | } else { 314 | Err(Error::new( 315 | ErrorKind::WriteZero, 316 | "failed to write whole buffer", 317 | )) 318 | } 319 | } 320 | 321 | #[inline] 322 | fn flush(&mut self) -> Result<()> { 323 | Ok(()) 324 | } 325 | } 326 | 327 | impl Write for Vec { 328 | #[inline] 329 | fn write(&mut self, buf: &[u8]) -> Result { 330 | self.extend_from_slice(buf); 331 | Ok(buf.len()) 332 | } 333 | 334 | #[inline] 335 | fn write_all(&mut self, buf: &[u8]) -> Result<()> { 336 | self.extend_from_slice(buf); 337 | Ok(()) 338 | } 339 | 340 | #[inline] 341 | fn flush(&mut self) -> Result<()> { 342 | Ok(()) 343 | } 344 | } 345 | 346 | ///////////////////////////////////////////////////////////////////////////////// 347 | ///////////////////////////////////////////////////////////////////////////////// 348 | ///////////////////////////////////////////////////////////////////////////////// 349 | 350 | /// This data structure is used as a workaround for current design of `ToBytes` 351 | /// which does not allow multiple writes to `&mut [u8]`. 352 | pub struct Cursor { 353 | inner: T, 354 | pos: u64, 355 | } 356 | 357 | impl Cursor { 358 | /// Creates a new cursor wrapping the provided underlying in-memory buffer. 359 | /// 360 | /// Cursor initial position is `0` even if underlying buffer (e.g., `Vec`) 361 | /// is not empty. So writing to cursor starts with overwriting `Vec` 362 | /// content, not with appending to it. 363 | /// 364 | /// # Examples 365 | /// 366 | /// ``` 367 | /// use ark_std::io::Cursor; 368 | /// 369 | /// let buff = Cursor::new(Vec::new()); 370 | /// # fn force_inference(_: &Cursor>) {} 371 | /// # force_inference(&buff); 372 | /// ``` 373 | pub fn new(inner: T) -> Self { 374 | Cursor { inner, pos: 0 } 375 | } 376 | 377 | /// Consumes this cursor, returning the underlying value. 378 | /// 379 | /// # Examples 380 | /// 381 | /// ``` 382 | /// use ark_std::io::Cursor; 383 | /// 384 | /// let buff = Cursor::new(Vec::new()); 385 | /// # fn force_inference(_: &Cursor>) {} 386 | /// # force_inference(&buff); 387 | /// 388 | /// let vec = buff.into_inner(); 389 | /// ``` 390 | pub fn into_inner(self) -> T { 391 | self.inner 392 | } 393 | 394 | /// Gets a reference to the underlying value in this cursor. 395 | /// 396 | /// # Examples 397 | /// 398 | /// ``` 399 | /// use ark_std::io::Cursor; 400 | /// 401 | /// let buff = Cursor::new(Vec::new()); 402 | /// # fn force_inference(_: &Cursor>) {} 403 | /// # force_inference(&buff); 404 | /// 405 | /// let reference = buff.get_ref(); 406 | /// ``` 407 | pub fn get_ref(&self) -> &T { 408 | &self.inner 409 | } 410 | 411 | /// Gets a mutable reference to the underlying value in this cursor. 412 | /// 413 | /// Care should be taken to avoid modifying the internal I/O state of the 414 | /// underlying value as it may corrupt this cursor's position. 415 | /// 416 | /// # Examples 417 | /// 418 | /// ``` 419 | /// use ark_std::io::Cursor; 420 | /// 421 | /// let mut buff = Cursor::new(Vec::new()); 422 | /// # fn force_inference(_: &Cursor>) {} 423 | /// # force_inference(&buff); 424 | /// 425 | /// let reference = buff.get_mut(); 426 | /// ``` 427 | pub fn get_mut(&mut self) -> &mut T { 428 | &mut self.inner 429 | } 430 | 431 | /// Returns the current position of this cursor. 432 | pub fn position(&self) -> u64 { 433 | self.pos 434 | } 435 | 436 | /// Sets the position of this cursor. 437 | /// 438 | /// # Examples 439 | /// 440 | /// ``` 441 | /// use ark_std::io::Cursor; 442 | /// 443 | /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); 444 | /// 445 | /// assert_eq!(buff.position(), 0); 446 | /// 447 | /// buff.set_position(2); 448 | /// assert_eq!(buff.position(), 2); 449 | /// 450 | /// buff.set_position(4); 451 | /// assert_eq!(buff.position(), 4); 452 | /// ``` 453 | pub fn set_position(&mut self, pos: u64) { 454 | self.pos = pos; 455 | } 456 | } 457 | 458 | impl Read for Cursor 459 | where 460 | T: AsRef<[u8]>, 461 | { 462 | fn read(&mut self, buf: &mut [u8]) -> Result { 463 | let n = Read::read(&mut self.get_buf()?, buf)?; 464 | self.pos += n as u64; 465 | Ok(n) 466 | } 467 | 468 | fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { 469 | let n = buf.len(); 470 | Read::read_exact(&mut self.get_buf()?, buf)?; 471 | self.pos += n as u64; 472 | Ok(()) 473 | } 474 | } 475 | 476 | impl Cursor 477 | where 478 | T: AsRef<[u8]>, 479 | { 480 | fn get_buf(&mut self) -> Result<&[u8]> { 481 | let amt = cmp::min(self.pos, self.inner.as_ref().len() as u64); 482 | Ok(&self.inner.as_ref()[(amt as usize)..]) 483 | } 484 | } 485 | 486 | impl Write for Cursor<&mut [u8]> { 487 | #[inline] 488 | fn write(&mut self, buf: &[u8]) -> Result { 489 | slice_write(&mut self.pos, self.inner, buf) 490 | } 491 | 492 | #[inline] 493 | fn flush(&mut self) -> Result<()> { 494 | Ok(()) 495 | } 496 | } 497 | 498 | impl Write for Cursor> { 499 | fn write(&mut self, buf: &[u8]) -> Result { 500 | vec_write(&mut self.pos, &mut self.inner, buf) 501 | } 502 | 503 | #[inline] 504 | fn flush(&mut self) -> Result<()> { 505 | Ok(()) 506 | } 507 | } 508 | 509 | // Non-resizing write implementation 510 | #[inline] 511 | fn slice_write(pos_mut: &mut u64, slice: &mut [u8], buf: &[u8]) -> Result { 512 | let pos = cmp::min(*pos_mut, slice.len() as u64); 513 | let amt = (&mut slice[(pos as usize)..]).write(buf)?; 514 | *pos_mut += amt as u64; 515 | Ok(amt) 516 | } 517 | 518 | fn vec_write(pos_mut: &mut u64, vec: &mut Vec, buf: &[u8]) -> Result { 519 | let pos: usize = (*pos_mut).try_into().map_err(|_| { 520 | Error::new( 521 | ErrorKind::InvalidInput, 522 | "cursor position exceeds maximum possible vector length", 523 | ) 524 | })?; 525 | // Make sure the internal buffer is as least as big as where we 526 | // currently are 527 | let len = vec.len(); 528 | if len < pos { 529 | // use `resize` so that the zero filling is as efficient as possible 530 | vec.resize(pos, 0); 531 | } 532 | // Figure out what bytes will be used to overwrite what's currently 533 | // there (left), and what will be appended on the end (right) 534 | { 535 | let space = vec.len() - pos; 536 | let (left, right) = buf.split_at(cmp::min(space, buf.len())); 537 | vec[pos..pos + left.len()].copy_from_slice(left); 538 | vec.extend_from_slice(right); 539 | } 540 | 541 | // Bump us forward 542 | *pos_mut = (pos + buf.len()) as u64; 543 | Ok(buf.len()) 544 | } 545 | --------------------------------------------------------------------------------