arrayref-0.3.9/.cargo_vcs_info.json0000644000000001360000000000100126600ustar { "git": { "sha1": "f8d0299d863922db6c409d08098941e833b70d69" }, "path_in_vcs": "" }arrayref-0.3.9/.github/workflows/rust.yml000064400000000000000000000003301046102023000165610ustar 00000000000000name: Rust on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Build run: cargo build --verbose - name: Run tests run: cargo test --verbose arrayref-0.3.9/.gitignore000064400000000000000000000000251046102023000134350ustar 00000000000000target Cargo.lock *~ arrayref-0.3.9/.travis.yml000064400000000000000000000023361046102023000135650ustar 00000000000000language: rust addons: apt: packages: - libcurl4-openssl-dev - libelf-dev - libdw-dev rust: - nightly - beta - stable matrix: allow_failures: - rust: nightly before_script: - | pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH script: - | travis-cargo build && travis-cargo test && travis-cargo bench && travis-cargo --only stable doc after_success: - travis-cargo --only stable doc-upload - travis-cargo coveralls --no-sudo env: global: - TRAVIS_CARGO_NIGHTLY_FEATURE=nightly - secure: 8dzqJGkV5184c0sV9BiMjjs5lxQjK2CvfGAU6ab2YFWN3roN/u37wBkoyqeSIzR3Uv0EXUOIM/BwuaeIwDHrZtTQMNnRw8Aa9A0mIeVCz1zlOFRK18NVGKoxBkkzlAvQn51D9X7sF9g9xLoDB7zyH63qhrerz6vjUivXaXkKZKAUZeBZMQ5riUxaHkt2LJtQhngXPS3Ar+ajSjIGkhg9x8gkqgkQCewbyoR9S9BwiyIUdYyYRSTgUgFtp3tuzMhQ8qykj53PqrbcCfiYC3O3lsGfQ0nqerT7cxPIHIg25+dZYJjLFk1908+GZFVqia9JFT8bbep7IkICDtfRQswAcxKTV6TvExfkEh8/vapzCueXuFMbszUDXxFkE+QWEO9RcDCQZjVAXuKx/iacok4XFXr/yE3QKVB+up7bKcEpAMMxjPd2+Z3EHVKZ53DtlzuzxM6ByjPy+0hRHkLWq3ZyzxyF3PAHq1tWlJ8B37eOqJIk4n+OBBpPOg1WF6nFq/7UV44SRkBbfC69wk8ANb46gWlIiB4+VKAsxEkRMYURtsPqTpgGqSdB2aNm8xpzke9d3d7Z+Zy8ma6tykqN9TlY7ke5fxJhaeNdTpdUykc0MHcKF8RvZbi170UmMqLRQMsMusXGP6QnhpVQhQB/bTRNZWJwKCTZ54jtEKImShInhTk= arrayref-0.3.9/Cargo.lock0000644000000063160000000000100106410ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "arrayref" version = "0.3.9" dependencies = [ "quickcheck", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "env_logger" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" dependencies = [ "log", "regex", ] [[package]] name = "getrandom" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "libc" version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "quickcheck" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6" dependencies = [ "env_logger", "log", "rand", ] [[package]] name = "rand" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "rand_core", ] [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ "getrandom", ] [[package]] name = "regex" version = "1.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" arrayref-0.3.9/Cargo.toml0000644000000014630000000000100106620ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "arrayref" version = "0.3.9" authors = ["David Roundy "] description = "Macros to take array references of slices" documentation = "https://docs.rs/arrayref" readme = "README.md" license = "BSD-2-Clause" repository = "https://github.com/droundy/arrayref" [dev-dependencies.quickcheck] version = "1.0" arrayref-0.3.9/Cargo.toml.orig000064400000000000000000000005031046102023000143350ustar 00000000000000[package] name = "arrayref" version = "0.3.9" authors = ["David Roundy "] description = "Macros to take array references of slices" license = "BSD-2-Clause" repository = "https://github.com/droundy/arrayref" documentation = "https://docs.rs/arrayref" [dev-dependencies] quickcheck = "1.0" arrayref-0.3.9/LICENSE000064400000000000000000000024701046102023000124600ustar 00000000000000Copyright (c) 2015 David Roundy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. arrayref-0.3.9/README.md000064400000000000000000000105231046102023000127300ustar 00000000000000# arrayref [![Build Status](https://travis-ci.org/droundy/arrayref.svg?branch=master)](https://travis-ci.org/droundy/arrayref) [![Coverage Status](https://coveralls.io/repos/droundy/arrayref/badge.svg?branch=master&service=github)](https://coveralls.io/github/droundy/arrayref?branch=master) [Documentation](https://docs.rs/arrayref) This is a very small rust module, which contains just four macros, for the taking of array references to slices of... sliceable things. These macros (which are awkwardly named) should be perfectly safe, and have seen just a tad of code review. ## Why would I want this? The goal of arrayref is to enable the effective use of APIs that involve array references rather than slices, for situations where parameters must have a given size. As an example, consider the `byteorder` crate. This is a very nice crate with a simple API containing functions that look like: ```rust fn read_u16(buf: &[u8]) -> u16; fn write_u16(buf: &mut [u8], n: u16); ``` Looking at this, you might wonder why they accept a slice reference as input. After all, they always want just two bytes. These functions must panic if given a slice that is too small, which means that unless they are inlined, then a runtime bounds-check is forced, even if it may be statically known that the input is the right size. Wouldn't it be nicer if we had functions more like ```rust fn read_u16_array(buf: &[u8; 2]) -> u16; fn write_u16_array(buf: &mut [u8; 2], n: u16); ``` The type signature would tell users precisely what size of input is required, and the compiler could check at compile time that the input is of the appropriate size: this sounds like the zero-cost abstractions rust is famous for! However, there is a catch, which arises when you try to *use* these nicer functions, which is that usually you are looking at two bytes in a stream. So, e.g. consider that we are working with a hypothetical (and simplified) ipv6 address. Doing this with our array version (which looks so beautiful in terms of accurately describing what we want!) looks terrible: ```rust let addr: &[u8; 16] = ...; let mut segments = [0u16; 8]; // array-based API for i in 0 .. 8 { let mut two_bytes = [addr[2*i], addr[2*i+1]]; segments[i] = read_u16_array(&two_bytes); } // slice-based API for i in 0 .. 8 { segments[i] = read_u16(&addr[2*i..]); } ``` The array-based approach looks way worse. We need to create a fresh copy of the bytes, just so it will be in an array of the proper size! Thus the whole "zero-cost abstraction" argument for using array references fails. The trouble is that there is no (safe) way (until [RFC 495][1] lands) to obtain an array reference to a portion of a larger array or slice. Doing so is the equivalent of taking a slice with a size known at compile time, and ought to be built into the language. [1]: https://github.com/rust-lang/rfcs/blob/master/text/0495-array-pattern-changes.md The arrayref crate allows you to do this kind of slicing. So the above (very contrived) example can be implemented with array references as: ```rust let addr: &[u8; 16] = ...; let mut segments = [0u16; 8]; // array-based API with arrayref for i in 0 .. 8 { segments[i] = read_u16_array(array_ref![addr,2*i,2]); } ``` Here the `array_ref![addr,2*i,2]` macro allows us to take an array reference to a slice consisting of two bytes starting at `2*i`. Apart from the syntax (less nice than slicing), it is essentially the same as the slice approach. However, this code makes explicit the need for precisely *two* bytes both in the caller, and in the function signature. This module provides three other macros providing related functionality, which you can read about in the [documentation](https://droundy.github.io/arrayref). For an example of how these macros can be used in an actual program, see [my rust translation of tweetnacl][2], which uses `arrayref` to almost exclusively accept array references in functions, with the only exception being those which truly expect data of arbitrary length. In my opinion, the result is code that is far more legible than the original C code, since the size of each argument is explicit. Moreover (although I have not tested this), the use of array references rather than slices *should* result in far fewer bounds checks, since almost all sizes are known at compile time. [2]: https://github.com/droundy/onionsalt/blob/master/src/crypto/mod.rs arrayref-0.3.9/examples/array_refs.rs000064400000000000000000000005011046102023000157650ustar 00000000000000#[macro_use] extern crate arrayref; fn main() { let x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let (a, b, c) = array_refs!(&x, 2, 3, 5); assert_eq!(2, a.len()); assert_eq!(3, b.len()); assert_eq!(5, c.len()); assert_eq!(*a, [0, 1]); assert_eq!(*b, [2, 3, 4]); assert_eq!(*c, [5, 6, 7, 8, 9]); } arrayref-0.3.9/examples/array_refs_with_const.rs000064400000000000000000000007171046102023000202370ustar 00000000000000#[macro_use] extern crate arrayref; const SIZE: usize = 10; const SIZE_A: usize = 2; const SIZE_B: usize = 3; const SIZE_C: usize = 5; fn main() { let x: [u8; SIZE] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let (a, b, c) = array_refs!(&x, SIZE_A, SIZE_B, SIZE_C); assert_eq!(SIZE_A, a.len()); assert_eq!(SIZE_B, b.len()); assert_eq!(SIZE_C, c.len()); assert_eq!(*a, [0, 1]); assert_eq!(*b, [2, 3, 4]); assert_eq!(*c, [5, 6, 7, 8, 9]); } arrayref-0.3.9/examples/simple-case.rs000064400000000000000000000004001046102023000160300ustar 00000000000000#[macro_use] extern crate arrayref; fn add_three(a: &[u8; 3]) -> u8 { a[0] + a[1] + a[2] } fn main() { let mut x = [0u8; 30]; x[20] = 1; x[21] = 4; x[24] = 3; x[0] = add_three(array_mut_ref![x, 20, 3]); assert_eq!(x[0], 8); } arrayref-0.3.9/src/lib.rs000064400000000000000000000414571046102023000133660ustar 00000000000000//! This package contains just four macros, which enable the creation //! of array references to portions of arrays or slices (or things //! that can be sliced). //! //! # Examples //! //! Here is a simple example of slicing and dicing a slice into array //! references with these macros. Here we implement a simple //! little-endian conversion from bytes to `u16`, and demonstrate code //! that uses `array_ref!` to extract an array reference from a larger //! array. Note that the documentation for each macro also has an //! example of its use. //! //! ``` //! #[macro_use] //! extern crate arrayref; //! //! fn read_u16(bytes: &[u8; 2]) -> u16 { //! bytes[0] as u16 + ((bytes[1] as u16) << 8) //! } //! // ... //! # fn main() { //! let data = [0,1,2,3,4,0,6,7,8,9]; //! assert_eq!(256, read_u16(array_ref![data,0,2])); //! assert_eq!(4, read_u16(array_ref![data,4,2])); //! # } //! ``` #![deny(warnings)] #![no_std] #[cfg(test)] #[macro_use] extern crate std; /// You can use `array_ref` to generate an array reference to a subset /// of a sliceable bit of data (which could be an array, or a slice, /// or a Vec). /// /// **Panics** if the slice is out of bounds. /// /// ``` /// #[macro_use] /// extern crate arrayref; /// /// fn read_u16(bytes: &[u8; 2]) -> u16 { /// bytes[0] as u16 + ((bytes[1] as u16) << 8) /// } /// // ... /// # fn main() { /// let data = [0,1,2,3,4,0,6,7,8,9]; /// assert_eq!(256, read_u16(array_ref![data,0,2])); /// assert_eq!(4, read_u16(array_ref![data,4,2])); /// # } /// ``` #[macro_export] macro_rules! array_ref { ($arr:expr, $offset:expr, $len:expr) => {{ { #[inline] const unsafe fn as_array(slice: &[T]) -> &[T; $len] { &*(slice.as_ptr() as *const [_; $len]) } let offset = $offset; let slice = &$arr[offset..offset + $len]; #[allow(unused_unsafe)] unsafe { as_array(slice) } } }}; } /// You can use `array_refs` to generate a series of array references /// to an input array reference. The idea is if you want to break an /// array into a series of contiguous and non-overlapping arrays. /// `array_refs` is a bit funny in that it insists on slicing up the /// *entire* array. This is intentional, as I find it handy to make /// me ensure that my sub-arrays add up to the entire array. This /// macro will *never* panic, since the sizes are all checked at /// compile time. /// /// Note that unlike `array_ref!`, `array_refs` *requires* that the /// first argument be an array reference. The following arguments are /// the lengths of each subarray you wish a reference to. The total /// of these arguments *must* equal the size of the array itself. /// /// ``` /// #[macro_use] /// extern crate arrayref; /// /// fn read_u16(bytes: &[u8; 2]) -> u16 { /// bytes[0] as u16 + ((bytes[1] as u16) << 8) /// } /// // ... /// # fn main() { /// let data = [0,1,2,3,4,0,6,7]; /// let (a,b,c) = array_refs![&data,2,2,4]; /// assert_eq!(read_u16(a), 256); /// assert_eq!(read_u16(b), 3*256+2); /// assert_eq!(*c, [4,0,6,7]); /// # } /// ``` #[macro_export] macro_rules! array_refs { ( $arr:expr, $( $pre:expr ),* ; .. ; $( $post:expr ),* ) => {{ { use core::slice; #[inline] #[allow(unused_assignments)] #[allow(clippy::eval_order_dependence)] const unsafe fn as_arrays(a: &[T]) -> ( $( &[T; $pre], )* &[T], $( &[T; $post], )*) { const MIN_LEN: usize = 0usize $( .saturating_add($pre) )* $( .saturating_add($post) )*; assert!(MIN_LEN < usize::MAX, "Your arrays are too big, are you trying to hack yourself?!"); let var_len = a.len() - MIN_LEN; assert!(a.len() >= MIN_LEN); let mut p = a.as_ptr(); ( $( { let aref = & *(p as *const [T; $pre]); p = p.add($pre); aref }, )* { let sl = slice::from_raw_parts(p as *const T, var_len); p = p.add(var_len); sl }, $( { let aref = & *(p as *const [T; $post]); p = p.add($post); aref }, )*) } let input = $arr; #[allow(unused_unsafe)] unsafe { as_arrays(input) } } }}; ( $arr:expr, $( $len:expr ),* ) => {{ { #[inline] #[allow(unused_assignments)] #[allow(clippy::eval_order_dependence)] const unsafe fn as_arrays(a: &[T; $( $len + )* 0 ]) -> ( $( &[T; $len], )* ) { let mut p = a.as_ptr(); ( $( { let aref = &*(p as *const [T; $len]); p = p.offset($len as isize); aref }, )* ) } let input = $arr; #[allow(unused_unsafe)] unsafe { as_arrays(input) } } }} } /// You can use `mut_array_refs` to generate a series of mutable array /// references to an input mutable array reference. The idea is if /// you want to break an array into a series of contiguous and /// non-overlapping mutable array references. Like `array_refs!`, /// `mut_array_refs!` is a bit funny in that it insists on slicing up /// the *entire* array. This is intentional, as I find it handy to /// make me ensure that my sub-arrays add up to the entire array. /// This macro will *never* panic, since the sizes are all checked at /// compile time. /// /// Note that unlike `array_mut_ref!`, `mut_array_refs` *requires* /// that the first argument be a mutable array reference. The /// following arguments are the lengths of each subarray you wish a /// reference to. The total of these arguments *must* equal the size /// of the array itself. Also note that this macro allows you to take /// out multiple mutable references to a single object, which is both /// weird and powerful. /// /// ``` /// #[macro_use] /// extern crate arrayref; /// /// fn write_u16(bytes: &mut [u8; 2], num: u16) { /// bytes[0] = num as u8; /// bytes[1] = (num >> 8) as u8; /// } /// fn write_u32(bytes: &mut [u8; 4], num: u32) { /// bytes[0] = num as u8; /// bytes[1] = (num >> 8) as u8; // this is buggy to save space... /// } /// // ... /// # fn main() { /// let mut data = [0,1,2,3,4,0,6,7]; /// let (a,b,c) = mut_array_refs![&mut data,2,2,4]; /// // let's write out some nice prime numbers! /// write_u16(a, 37); /// write_u16(b, 73); /// write_u32(c, 137); // approximate inverse of the fine structure constant! /// # } /// ``` #[macro_export] macro_rules! mut_array_refs { ( $arr:expr, $( $pre:expr ),* ; .. ; $( $post:expr ),* ) => {{ { use core::slice; #[inline] #[allow(unused_assignments)] #[allow(clippy::eval_order_dependence)] unsafe fn as_arrays(a: &mut [T]) -> ( $( &mut [T; $pre], )* &mut [T], $( &mut [T; $post], )*) { const MIN_LEN: usize = 0usize $( .saturating_add($pre) )* $( .saturating_add($post) )*; assert!(MIN_LEN < usize::MAX, "Your arrays are too big, are you trying to hack yourself?!"); let var_len = a.len() - MIN_LEN; assert!(a.len() >= MIN_LEN); let mut p = a.as_mut_ptr(); ( $( { let aref = &mut *(p as *mut [T; $pre]); p = p.add($pre); aref }, )* { let sl = slice::from_raw_parts_mut(p as *mut T, var_len); p = p.add(var_len); sl }, $( { let aref = &mut *(p as *mut [T; $post]); p = p.add($post); aref }, )*) } let input = $arr; #[allow(unused_unsafe)] unsafe { as_arrays(input) } } }}; ( $arr:expr, $( $len:expr ),* ) => {{ { #[inline] #[allow(unused_assignments)] #[allow(clippy::eval_order_dependence)] unsafe fn as_arrays(a: &mut [T; $( $len + )* 0 ]) -> ( $( &mut [T; $len], )* ) { let mut p = a.as_mut_ptr(); ( $( { let aref = &mut *(p as *mut [T; $len]); p = p.add($len); aref }, )* ) } let input = $arr; #[allow(unused_unsafe)] unsafe { as_arrays(input) } } }}; } /// You can use `array_mut_ref` to generate a mutable array reference /// to a subset of a sliceable bit of data (which could be an array, /// or a slice, or a Vec). /// /// **Panics** if the slice is out of bounds. /// /// ``` /// #[macro_use] /// extern crate arrayref; /// /// fn write_u16(bytes: &mut [u8; 2], num: u16) { /// bytes[0] = num as u8; /// bytes[1] = (num >> 8) as u8; /// } /// // ... /// # fn main() { /// let mut data = [0,1,2,3,4,0,6,7,8,9]; /// write_u16(array_mut_ref![data,0,2], 1); /// write_u16(array_mut_ref![data,2,2], 5); /// assert_eq!(*array_ref![data,0,4], [1,0,5,0]); /// *array_mut_ref![data,4,5] = [4,3,2,1,0]; /// assert_eq!(data, [1,0,5,0,4,3,2,1,0,9]); /// # } /// ``` #[macro_export] macro_rules! array_mut_ref { ($arr:expr, $offset:expr, $len:expr) => {{ { #[inline] unsafe fn as_array(slice: &mut [T]) -> &mut [T; $len] { &mut *(slice.as_mut_ptr() as *mut [_; $len]) } let offset = $offset; let slice = &mut $arr[offset..offset + $len]; #[allow(unused_unsafe)] unsafe { as_array(slice) } } }}; } #[allow(clippy::all)] #[cfg(test)] mod test { extern crate quickcheck; use std::vec::Vec; // use super::*; #[test] #[should_panic] fn checks_bounds() { let foo: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let bar = array_ref!(foo, 1, 11); println!("I am checking that I can dereference bar[0] = {}", bar[0]); } #[test] fn simple_case_works() { fn check(expected: [u8; 3], actual: &[u8; 3]) { for (e, a) in (&expected).iter().zip(actual.iter()) { assert_eq!(e, a) } } let mut foo: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; { let bar = array_ref!(foo, 2, 3); check([2, 3, 4], bar); } check([0, 1, 2], array_ref!(foo, 0, 3)); fn zero2(x: &mut [u8; 2]) { x[0] = 0; x[1] = 0; } zero2(array_mut_ref!(foo, 8, 2)); check([0, 0, 10], array_ref!(foo, 8, 3)); } #[test] fn check_array_ref_5() { fn f(data: Vec, offset: usize) -> quickcheck::TestResult { // Compute the following, with correct results even if the sum would overflow: // if data.len() < offset + 5 if data.len() < 5 || data.len() - 5 < offset { return quickcheck::TestResult::discard(); } let out = array_ref!(data, offset, 5); quickcheck::TestResult::from_bool(out.len() == 5) } quickcheck::quickcheck(f as fn(Vec, usize) -> quickcheck::TestResult); } #[test] fn check_array_ref_out_of_bounds_5() { fn f(data: Vec, offset: usize) -> quickcheck::TestResult { // Compute the following, with correct results even if the sum would overflow: // if data.len() >= offset + 5 if data.len() >= 5 && data.len() - 5 >= offset { return quickcheck::TestResult::discard(); } quickcheck::TestResult::must_fail(move || { array_ref!(data, offset, 5); }) } quickcheck::quickcheck(f as fn(Vec, usize) -> quickcheck::TestResult); } #[test] fn check_array_mut_ref_7() { fn f(mut data: Vec, offset: usize) -> quickcheck::TestResult { // Compute the following, with correct results even if the sum would overflow: // if data.len() < offset + 7 if data.len() < 7 || data.len() - 7 < offset { return quickcheck::TestResult::discard(); } let out = array_mut_ref!(data, offset, 7); out[6] = 3; quickcheck::TestResult::from_bool(out.len() == 7) } quickcheck::quickcheck(f as fn(Vec, usize) -> quickcheck::TestResult); } #[test] fn check_array_mut_ref_out_of_bounds_32() { fn f(mut data: Vec, offset: usize) -> quickcheck::TestResult { // Compute the following, with correct results even if the sum would overflow: // if data.len() >= offset + 32 if data.len() >= 32 && data.len() - 32 >= offset { return quickcheck::TestResult::discard(); } quickcheck::TestResult::must_fail(move || { array_mut_ref!(data, offset, 32); }) } quickcheck::quickcheck(f as fn(Vec, usize) -> quickcheck::TestResult); } #[test] fn test_5_array_refs() { let mut data: [usize; 128] = [0; 128]; for i in 0..128 { data[i] = i; } let data = data; let (a, b, c, d, e) = array_refs!(&data, 1, 14, 3, 100, 10); assert_eq!(a.len(), 1 as usize); assert_eq!(b.len(), 14 as usize); assert_eq!(c.len(), 3 as usize); assert_eq!(d.len(), 100 as usize); assert_eq!(e.len(), 10 as usize); assert_eq!(a, array_ref![data, 0, 1]); assert_eq!(b, array_ref![data, 1, 14]); assert_eq!(c, array_ref![data, 15, 3]); assert_eq!(e, array_ref![data, 118, 10]); } #[test] fn test_5_array_refs_dotdot() { let mut data: [usize; 128] = [0; 128]; for i in 0..128 { data[i] = i; } let data = data; let (a, b, c, d, e) = array_refs!(&data, 1, 14, 3; ..; 10); assert_eq!(a.len(), 1 as usize); assert_eq!(b.len(), 14 as usize); assert_eq!(c.len(), 3 as usize); assert_eq!(d.len(), 100 as usize); assert_eq!(e.len(), 10 as usize); assert_eq!(a, array_ref![data, 0, 1]); assert_eq!(b, array_ref![data, 1, 14]); assert_eq!(c, array_ref![data, 15, 3]); assert_eq!(e, array_ref![data, 118, 10]); } #[test] fn test_5_mut_xarray_refs() { let mut data: [usize; 128] = [0; 128]; { // temporarily borrow the data to modify it. let (a, b, c, d, e) = mut_array_refs!(&mut data, 1, 14, 3, 100, 10); assert_eq!(a.len(), 1 as usize); assert_eq!(b.len(), 14 as usize); assert_eq!(c.len(), 3 as usize); assert_eq!(d.len(), 100 as usize); assert_eq!(e.len(), 10 as usize); *a = [1; 1]; *b = [14; 14]; *c = [3; 3]; *d = [100; 100]; *e = [10; 10]; } assert_eq!(&[1; 1], array_ref![data, 0, 1]); assert_eq!(&[14; 14], array_ref![data, 1, 14]); assert_eq!(&[3; 3], array_ref![data, 15, 3]); assert_eq!(&[10; 10], array_ref![data, 118, 10]); } #[test] fn test_5_mut_xarray_refs_with_dotdot() { let mut data: [usize; 128] = [0; 128]; { // temporarily borrow the data to modify it. let (a, b, c, d, e) = mut_array_refs!(&mut data, 1, 14, 3; ..; 10); assert_eq!(a.len(), 1 as usize); assert_eq!(b.len(), 14 as usize); assert_eq!(c.len(), 3 as usize); assert_eq!(d.len(), 100 as usize); assert_eq!(e.len(), 10 as usize); *a = [1; 1]; *b = [14; 14]; *c = [3; 3]; *e = [10; 10]; } assert_eq!(&[1; 1], array_ref![data, 0, 1]); assert_eq!(&[14; 14], array_ref![data, 1, 14]); assert_eq!(&[3; 3], array_ref![data, 15, 3]); assert_eq!(&[10; 10], array_ref![data, 118, 10]); } #[forbid(clippy::ptr_offset_with_cast)] #[test] fn forbidden_clippy_lints_do_not_fire() { let mut data = [0u8; 32]; let _ = array_refs![&data, 8; .. ;]; let _ = mut_array_refs![&mut data, 8; .. ; 10]; } #[test] fn single_arg_refs() { let mut data = [0u8; 8]; let (_,) = array_refs![&data, 8]; let (_,) = mut_array_refs![&mut data, 8]; let (_, _) = array_refs![&data, 4; ..;]; let (_, _) = mut_array_refs![&mut data, 4; ..;]; let (_, _) = array_refs![&data,; ..; 4]; let (_, _) = mut_array_refs![&mut data,; ..; 4]; let (_,) = array_refs![&data,; ..;]; let (_,) = mut_array_refs![&mut data,; ..;]; } } // mod test