зеркало из https://github.com/mozilla/gecko-dev.git
No bug - Revendor rust dependencies
This commit is contained in:
Родитель
dfae784318
Коммит
0e51b95a04
|
@ -0,0 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"68f3e6e5b2053041188a3369506f7bff80e72f2451686820cba41fc9b969e169",".travis.yml":"23504e7dd0d6950739f589a435d468150b0d622bc8a88d5081d82117763422c5","Cargo.toml":"2cf7ac51721bf5180a63e87bed7a8f2ec9303523230efdfb95cdc5b51da502f3","LICENSE":"c3f6a6243c9101744bc87de3376336ca55dcbfc4b3c62c70c4e7b735b792266c","Makefile":"2130e4879c185e1ef8e40e0f9d54e1a1cbc8160e2957076b947e79e4df84fd73","README.rst":"cc9b7337e517729f7a12f2639feb60cb49534fd0ccefd60bf039f26b3fb64b70","custom.css":"e6f2cd299392337b4e2959c52f422e5b7be11920ea98d10db44d10ddef5ed47c","src/array.rs":"10b95a278d0e83ed26bb7ed5b84babb03e77436404e6215e11eb9a252e05287e","src/array_string.rs":"261a55a20007fbec6008151fce2fa380af6ade95008ab71b4f0f0bc9625000c2","src/lib.rs":"2ba25ccca0fc5fc935092fa2930f74b650ce9cdc01ac2243cbebf11d376715f5","tests/generic_array.rs":"f1b56aab333f74bd3d7db90f03bbb6bb7495206fc3461a0d25a03f75f4988041","tests/tests.rs":"a143113a7f1db16bd75e8c6b540ae826114fb17213e2415cf75d133015951934"},"package":"699e63a93b79d717e8c3b5eb1b28b7780d0d6d9e59a72eb769291c83b0c8dc67"}
|
|
@ -0,0 +1,11 @@
|
|||
# Compiled files
|
||||
*.o
|
||||
*.so
|
||||
*.rlib
|
||||
*.dll
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
|
||||
# Generated by Cargo
|
||||
/target/
|
|
@ -0,0 +1,35 @@
|
|||
language: rust
|
||||
sudo: false
|
||||
matrix:
|
||||
include:
|
||||
- rust: 1.2.0
|
||||
- rust: stable
|
||||
env:
|
||||
- FEATURES="use_generic_array"
|
||||
- NODEFAULT=1
|
||||
- rust: beta
|
||||
- rust: nightly
|
||||
env:
|
||||
- NODEFAULT=1
|
||||
- rust: nightly
|
||||
env:
|
||||
- NODROP_FEATURES='use_needs_drop'
|
||||
- rust: nightly
|
||||
env:
|
||||
- FEATURES='use_union use_generic_array'
|
||||
- NODROP_FEATURES='use_union'
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- 0.3
|
||||
script:
|
||||
- |
|
||||
([ ! -z "$NODROP_FEATURES" ] || cargo build --verbose --features "$FEATURES") &&
|
||||
([ "$NODEFAULT" != 1 ] || cargo build --verbose --no-default-features) &&
|
||||
([ ! -z "$NODROP_FEATURES" ] || cargo test --verbose --features "$FEATURES") &&
|
||||
([ ! -z "$NODROP_FEATURES" ] || cargo test --release --verbose --features "$FEATURES") &&
|
||||
([ ! -z "$NODROP_FEATURES" ] || cargo bench --verbose --features "$FEATURES" -- --test) &&
|
||||
([ ! -z "$NODROP_FEATURES" ] || cargo doc --verbose --features "$FEATURES") &&
|
||||
([ "$NODEFAULT" != 1 ] || cargo build --verbose --manifest-path=nodrop/Cargo.toml --no-default-features) &&
|
||||
cargo test --verbose --manifest-path=nodrop/Cargo.toml --features "$NODROP_FEATURES" &&
|
||||
cargo bench --verbose --manifest-path=nodrop/Cargo.toml --features "$NODROP_FEATURES" -- --test
|
|
@ -0,0 +1,30 @@
|
|||
[package]
|
||||
name = "arrayvec"
|
||||
version = "0.3.23"
|
||||
authors = ["bluss"]
|
||||
license = "MIT/Apache-2.0"
|
||||
|
||||
description = "A vector with a fixed capacity, it can be stored on the stack too. Implements fixed capacity ArrayVec and ArrayString."
|
||||
documentation = "https://docs.rs/arrayvec/"
|
||||
repository = "https://github.com/bluss/arrayvec"
|
||||
|
||||
keywords = ["stack", "vector", "array", "data-structure", "no_std"]
|
||||
|
||||
[dependencies.odds]
|
||||
version = "0.2.23"
|
||||
default-features = false
|
||||
|
||||
[dependencies.nodrop]
|
||||
version = "0.1.8"
|
||||
path = "nodrop"
|
||||
default-features = false
|
||||
|
||||
[dependencies.generic-array]
|
||||
version = "0.5.1"
|
||||
optional = true
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = ["odds/std", "nodrop/std"]
|
||||
use_union = ["nodrop/use_union"]
|
||||
use_generic_array = ["generic-array"]
|
|
@ -0,0 +1,22 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 bluss
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
DOCCRATES = arrayvec nodrop nodrop_union odds
|
||||
|
||||
# deps to delete the generated docs
|
||||
RMDOCS =
|
||||
|
||||
FEATURES = "odds/unstable"
|
||||
|
||||
VERSIONS = $(patsubst %,target/VERS/%,$(DOCCRATES))
|
||||
|
||||
docs: mkdocs subst $(RMDOCS)
|
||||
|
||||
# https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html
|
||||
$(VERSIONS): Cargo.toml
|
||||
mkdir -p $(@D)
|
||||
cargo pkgid $(@F) | sed -e "s/.*#\(\|.*:\)//" > "$@"
|
||||
|
||||
$(DOCCRATES): %: target/VERS/%
|
||||
# Put in the crate version into the docs
|
||||
find ./doc/$@ -name "*.html" -exec sed -i -e "s/<title>\(.*\) - Rust/<title>$@ $(shell cat $<) - \1 - Rust/g" {} \;
|
||||
|
||||
subst: $(DOCCRATES)
|
||||
|
||||
mkdocs: Cargo.toml
|
||||
cargo doc --features=$(FEATURES)
|
||||
cargo doc --features=use_union -p nodrop-union
|
||||
rm -rf ./doc
|
||||
cp -r ./target/doc ./doc
|
||||
-cat ./custom.css >> doc/main.css
|
||||
|
||||
$(RMDOCS): mkdocs
|
||||
rm -r ./doc/$@
|
||||
sed -i "/searchIndex\['$@'\]/d" doc/search-index.js
|
||||
|
||||
|
||||
.PHONY: docs mkdocs subst $(DOCCRATES) $(RMDOCS)
|
|
@ -0,0 +1,157 @@
|
|||
|
||||
arrayvec
|
||||
========
|
||||
|
||||
A vector with fixed capacity. Requires Rust 1.2+.
|
||||
|
||||
Please read the `API documentation here`__
|
||||
|
||||
__ https://bluss.github.io/arrayvec
|
||||
|
||||
|build_status|_ |crates|_ |crates2|_
|
||||
|
||||
.. |build_status| image:: https://travis-ci.org/bluss/arrayvec.svg
|
||||
.. _build_status: https://travis-ci.org/bluss/arrayvec
|
||||
|
||||
.. |crates| image:: http://meritbadge.herokuapp.com/arrayvec
|
||||
.. _crates: https://crates.io/crates/arrayvec
|
||||
|
||||
.. |crates2| image:: http://meritbadge.herokuapp.com/nodrop
|
||||
.. _crates2: https://crates.io/crates/nodrop
|
||||
|
||||
Recent Changes (arrayvec)
|
||||
-------------------------
|
||||
|
||||
- 0.3.23
|
||||
|
||||
- Implement ``PartialOrd, Ord`` as well as ``PartialOrd<str>`` for
|
||||
``ArrayString``.
|
||||
|
||||
- 0.3.22
|
||||
|
||||
- Implement ``Array`` for the 65536 size
|
||||
|
||||
- 0.3.21
|
||||
|
||||
- Use ``encode_utf8`` from crate odds
|
||||
- Add constructor ``ArrayString::from_byte_string``
|
||||
|
||||
- 0.3.20
|
||||
|
||||
- Simplify and speed up ``ArrayString``’s ``.push(char)``-
|
||||
|
||||
- 0.3.19
|
||||
|
||||
- Add new crate feature ``use_generic_array`` which allows using their
|
||||
``GenericArray`` just like a regular fixed size array for the storage
|
||||
of an ``ArrayVec``.
|
||||
|
||||
- 0.3.18
|
||||
|
||||
- Fix bounds check in ``ArrayVec::insert``!
|
||||
It would be buggy if ``self.len() < index < self.capacity()``. Take note of
|
||||
the push out behavior specified in the docs.
|
||||
|
||||
- 0.3.17
|
||||
|
||||
- Added crate feature ``use_union`` which forwards to the nodrop crate feature
|
||||
- Added methods ``.is_full()`` to ``ArrayVec`` and ``ArrayString``.
|
||||
|
||||
- 0.3.16
|
||||
|
||||
- Added method ``.retain()`` to ``ArrayVec``.
|
||||
- Added methods ``.as_slice(), .as_mut_slice()`` to ``ArrayVec`` and ``.as_str()``
|
||||
to ``ArrayString``.
|
||||
|
||||
- 0.3.15
|
||||
|
||||
- Add feature std, which you can opt out of to use ``no_std`` (requires Rust 1.6
|
||||
to opt out).
|
||||
- Implement ``Clone::clone_from`` for ArrayVec and ArrayString
|
||||
|
||||
- 0.3.14
|
||||
|
||||
- Add ``ArrayString::from(&str)``
|
||||
|
||||
- 0.3.13
|
||||
|
||||
- Added ``DerefMut`` impl for ``ArrayString``.
|
||||
- Added method ``.simplify()`` to drop the element for ``CapacityError``.
|
||||
- Added method ``.dispose()`` to ``ArrayVec``
|
||||
|
||||
- 0.3.12
|
||||
|
||||
- Added ArrayString, a fixed capacity analogy of String
|
||||
|
||||
- 0.3.11
|
||||
|
||||
- Added trait impls Default, PartialOrd, Ord, Write for ArrayVec
|
||||
|
||||
- 0.3.10
|
||||
|
||||
- Go back to using external NoDrop, fixing a panic safety bug (issue #3)
|
||||
|
||||
- 0.3.8
|
||||
|
||||
- Inline the non-dropping logic to remove one drop flag in the
|
||||
ArrayVec representation.
|
||||
|
||||
- 0.3.7
|
||||
|
||||
- Added method .into_inner()
|
||||
- Added unsafe method .set_len()
|
||||
|
||||
Recent Changes (nodrop)
|
||||
-----------------------
|
||||
|
||||
- 0.1.9
|
||||
|
||||
- Fix issue in recent nightly where ``repr(u8)`` did not work. Use
|
||||
a better way to get rid of the enum layout optimization.
|
||||
|
||||
- 0.1.8
|
||||
|
||||
- Add crate feature ``use_union`` that uses untagged unions to implement NoDrop.
|
||||
Finally we have an implementation without hacks, without a runtime flag,
|
||||
and without an actual ``Drop`` impl (which was needed to suppress drop).
|
||||
The crate feature requires nightly and is unstable.
|
||||
|
||||
- 0.1.7
|
||||
|
||||
- Remove crate feature ``no_drop_flag``, because it doesn't compile on nightly
|
||||
anymore. Drop flags are gone anyway!
|
||||
|
||||
- 0.1.6
|
||||
|
||||
- Add feature std, which you can opt out of to use ``no_std``.
|
||||
|
||||
- 0.1.5
|
||||
|
||||
- Added crate feature ``use_needs_drop`` which is a nightly-only
|
||||
optimization, which skips overwriting if the inner value does not need
|
||||
drop.
|
||||
|
||||
Recent Changes (nodrop-union)
|
||||
-----------------------
|
||||
|
||||
- 0.1.9
|
||||
|
||||
- Add ``Copy, Clone`` implementations
|
||||
|
||||
- 0.1.8
|
||||
|
||||
- Initial release
|
||||
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
Dual-licensed to be compatible with the Rust project.
|
||||
|
||||
Licensed under the Apache License, Version 2.0
|
||||
http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
|
||||
http://opensource.org/licenses/MIT, at your
|
||||
option. This file may not be copied, modified, or distributed
|
||||
except according to those terms.
|
||||
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
|
||||
.docblock pre.rust { background: #eeeeff; }
|
||||
pre.trait, pre.fn, pre.struct, pre.enum, pre.typedef { background: #fcfefc; }
|
||||
|
||||
/* Small “example” label for doc examples */
|
||||
.docblock pre.rust::before {
|
||||
content: "example";
|
||||
float: right;
|
||||
font-style: italic;
|
||||
font-size: 0.8em;
|
||||
margin-top: -10px;
|
||||
margin-right: -5px;
|
||||
}
|
||||
|
||||
|
||||
/* Fixup where display in trait listing */
|
||||
pre.trait .where::before {
|
||||
content: '\a ';
|
||||
}
|
||||
|
||||
.docblock code {
|
||||
background-color: inherit;
|
||||
font-weight: bold;
|
||||
padding: 0 0.1em;
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
|
||||
/// Trait for fixed size arrays.
|
||||
pub unsafe trait Array {
|
||||
/// The array's element type
|
||||
type Item;
|
||||
#[doc(hidden)]
|
||||
/// The smallest index type that indexes the array.
|
||||
type Index: Index;
|
||||
#[doc(hidden)]
|
||||
fn as_ptr(&self) -> *const Self::Item;
|
||||
#[doc(hidden)]
|
||||
fn as_mut_ptr(&mut self) -> *mut Self::Item;
|
||||
#[doc(hidden)]
|
||||
fn capacity() -> usize;
|
||||
}
|
||||
|
||||
pub trait Index : PartialEq + Copy {
|
||||
fn to_usize(self) -> usize;
|
||||
fn from(usize) -> Self;
|
||||
}
|
||||
|
||||
use std::slice::{from_raw_parts};
|
||||
|
||||
pub trait ArrayExt : Array {
|
||||
#[inline(always)]
|
||||
fn as_slice(&self) -> &[Self::Item] {
|
||||
unsafe {
|
||||
from_raw_parts(self.as_ptr(), Self::capacity())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A> ArrayExt for A where A: Array { }
|
||||
|
||||
#[cfg(feature = "use_generic_array")]
|
||||
unsafe impl<T, U> Array for ::generic_array::GenericArray<T, U>
|
||||
where U: ::generic_array::ArrayLength<T>
|
||||
{
|
||||
type Item = T;
|
||||
type Index = usize;
|
||||
fn as_ptr(&self) -> *const Self::Item {
|
||||
(**self).as_ptr()
|
||||
}
|
||||
fn as_mut_ptr(&mut self) -> *mut Self::Item {
|
||||
(**self).as_mut_ptr()
|
||||
}
|
||||
fn capacity() -> usize {
|
||||
U::to_usize()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Index for u8 {
|
||||
#[inline(always)]
|
||||
fn to_usize(self) -> usize { self as usize }
|
||||
#[inline(always)]
|
||||
fn from(ix: usize) -> Self { ix as u8 }
|
||||
}
|
||||
|
||||
impl Index for u16 {
|
||||
#[inline(always)]
|
||||
fn to_usize(self) -> usize { self as usize }
|
||||
#[inline(always)]
|
||||
fn from(ix: usize) -> Self { ix as u16 }
|
||||
}
|
||||
|
||||
impl Index for u32 {
|
||||
#[inline(always)]
|
||||
fn to_usize(self) -> usize { self as usize }
|
||||
#[inline(always)]
|
||||
fn from(ix: usize) -> Self { ix as u32 }
|
||||
}
|
||||
|
||||
impl Index for usize {
|
||||
#[inline(always)]
|
||||
fn to_usize(self) -> usize { self }
|
||||
#[inline(always)]
|
||||
fn from(ix: usize) -> Self { ix }
|
||||
}
|
||||
|
||||
macro_rules! fix_array_impl {
|
||||
($index_type:ty, $len:expr ) => (
|
||||
unsafe impl<T> Array for [T; $len] {
|
||||
type Item = T;
|
||||
type Index = $index_type;
|
||||
#[inline(always)]
|
||||
fn as_ptr(&self) -> *const T { self as *const _ as *const _ }
|
||||
#[inline(always)]
|
||||
fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut _}
|
||||
#[inline(always)]
|
||||
fn capacity() -> usize { $len }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! fix_array_impl_recursive {
|
||||
($index_type:ty, ) => ();
|
||||
($index_type:ty, $len:expr, $($more:expr,)*) => (
|
||||
fix_array_impl!($index_type, $len);
|
||||
fix_array_impl_recursive!($index_type, $($more,)*);
|
||||
);
|
||||
}
|
||||
|
||||
fix_array_impl_recursive!(u8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
|
||||
32, 40, 48, 56, 64, 72, 96, 128, 160, 192, 224,);
|
||||
fix_array_impl_recursive!(u16, 256, 384, 512, 768, 1024, 2048, 4096, 8192, 16384, 32768,);
|
||||
fix_array_impl_recursive!(u32, 1 << 16,);
|
||||
|
|
@ -0,0 +1,326 @@
|
|||
use std::borrow::Borrow;
|
||||
use std::cmp;
|
||||
use std::fmt;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::str;
|
||||
use std::str::Utf8Error;
|
||||
use std::slice;
|
||||
|
||||
use array::{Array, ArrayExt};
|
||||
use array::Index;
|
||||
use CapacityError;
|
||||
use odds::char::encode_utf8;
|
||||
|
||||
/// A string with a fixed capacity.
|
||||
///
|
||||
/// The `ArrayString` is a string backed by a fixed size array. It keeps track
|
||||
/// of its length.
|
||||
///
|
||||
/// The string is a contiguous value that you can store directly on the stack
|
||||
/// if needed.
|
||||
#[derive(Copy)]
|
||||
pub struct ArrayString<A: Array<Item=u8>> {
|
||||
xs: A,
|
||||
len: A::Index,
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> ArrayString<A> {
|
||||
/// Create a new empty `ArrayString`.
|
||||
///
|
||||
/// Capacity is inferred from the type parameter.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayString;
|
||||
///
|
||||
/// let mut string = ArrayString::<[_; 16]>::new();
|
||||
/// string.push_str("foo");
|
||||
/// assert_eq!(&string[..], "foo");
|
||||
/// assert_eq!(string.capacity(), 16);
|
||||
/// ```
|
||||
pub fn new() -> ArrayString<A> {
|
||||
unsafe {
|
||||
ArrayString {
|
||||
xs: ::new_array(),
|
||||
len: Index::from(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new `ArrayString` from a `str`.
|
||||
///
|
||||
/// Capacity is inferred from the type parameter.
|
||||
///
|
||||
/// **Errors** if the backing array is not large enough to fit the string.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayString;
|
||||
///
|
||||
/// let mut string = ArrayString::<[_; 3]>::from("foo").unwrap();
|
||||
/// assert_eq!(&string[..], "foo");
|
||||
/// assert_eq!(string.len(), 3);
|
||||
/// assert_eq!(string.capacity(), 3);
|
||||
/// ```
|
||||
pub fn from(s: &str) -> Result<Self, CapacityError<&str>> {
|
||||
let mut arraystr = Self::new();
|
||||
try!(arraystr.push_str(s));
|
||||
Ok(arraystr)
|
||||
}
|
||||
|
||||
/// Create a new `ArrayString` from a byte string literal.
|
||||
///
|
||||
/// **Errors** if the byte string literal is not valid UTF-8.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayString;
|
||||
///
|
||||
/// let string = ArrayString::from_byte_string(b"hello world").unwrap();
|
||||
/// ```
|
||||
pub fn from_byte_string(b: &A) -> Result<Self, Utf8Error> {
|
||||
let mut arraystr = Self::new();
|
||||
let s = try!(str::from_utf8(b.as_slice()));
|
||||
let _result = arraystr.push_str(s);
|
||||
debug_assert!(_result.is_ok());
|
||||
Ok(arraystr)
|
||||
}
|
||||
|
||||
/// Return the capacity of the `ArrayString`.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayString;
|
||||
///
|
||||
/// let string = ArrayString::<[_; 3]>::new();
|
||||
/// assert_eq!(string.capacity(), 3);
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn capacity(&self) -> usize { A::capacity() }
|
||||
|
||||
/// Return if the `ArrayString` is completely filled.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayString;
|
||||
///
|
||||
/// let mut string = ArrayString::<[_; 1]>::new();
|
||||
/// assert!(!string.is_full());
|
||||
/// string.push_str("A");
|
||||
/// assert!(string.is_full());
|
||||
/// ```
|
||||
pub fn is_full(&self) -> bool { self.len() == self.capacity() }
|
||||
|
||||
/// Adds the given char to the end of the string.
|
||||
///
|
||||
/// Returns `Ok` if the push succeeds.
|
||||
///
|
||||
/// **Errors** if the backing array is not large enough to fit the additional char.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayString;
|
||||
///
|
||||
/// let mut string = ArrayString::<[_; 2]>::new();
|
||||
///
|
||||
/// string.push('a').unwrap();
|
||||
/// string.push('b').unwrap();
|
||||
/// let overflow = string.push('c');
|
||||
///
|
||||
/// assert_eq!(&string[..], "ab");
|
||||
/// assert_eq!(overflow.unwrap_err().element(), 'c');
|
||||
/// ```
|
||||
pub fn push(&mut self, c: char) -> Result<(), CapacityError<char>> {
|
||||
let len = self.len();
|
||||
unsafe {
|
||||
match encode_utf8(c, &mut self.raw_mut_bytes()[len..]) {
|
||||
Ok(n) => {
|
||||
self.set_len(len + n);
|
||||
Ok(())
|
||||
}
|
||||
Err(_) => Err(CapacityError::new(c)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the given string slice to the end of the string.
|
||||
///
|
||||
/// Returns `Ok` if the push succeeds.
|
||||
///
|
||||
/// **Errors** if the backing array is not large enough to fit the string.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayString;
|
||||
///
|
||||
/// let mut string = ArrayString::<[_; 2]>::new();
|
||||
///
|
||||
/// string.push_str("a").unwrap();
|
||||
/// let overflow1 = string.push_str("bc");
|
||||
/// string.push_str("d").unwrap();
|
||||
/// let overflow2 = string.push_str("ef");
|
||||
///
|
||||
/// assert_eq!(&string[..], "ad");
|
||||
/// assert_eq!(overflow1.unwrap_err().element(), "bc");
|
||||
/// assert_eq!(overflow2.unwrap_err().element(), "ef");
|
||||
/// ```
|
||||
pub fn push_str<'a>(&mut self, s: &'a str) -> Result<(), CapacityError<&'a str>> {
|
||||
if s.len() > self.capacity() - self.len() {
|
||||
return Err(CapacityError::new(s));
|
||||
}
|
||||
unsafe {
|
||||
let dst = self.xs.as_mut_ptr().offset(self.len() as isize);
|
||||
let src = s.as_ptr();
|
||||
ptr::copy_nonoverlapping(src, dst, s.len());
|
||||
let newl = self.len() + s.len();
|
||||
self.set_len(newl);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make the string empty.
|
||||
pub fn clear(&mut self) {
|
||||
unsafe {
|
||||
self.set_len(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the strings's length.
|
||||
///
|
||||
/// May panic if `length` is greater than the capacity.
|
||||
///
|
||||
/// This function is `unsafe` because it changes the notion of the
|
||||
/// number of “valid” bytes in the string. Use with care.
|
||||
#[inline]
|
||||
pub unsafe fn set_len(&mut self, length: usize) {
|
||||
debug_assert!(length <= self.capacity());
|
||||
self.len = Index::from(length);
|
||||
}
|
||||
|
||||
/// Return a string slice of the whole `ArrayString`.
|
||||
pub fn as_str(&self) -> &str {
|
||||
self
|
||||
}
|
||||
|
||||
/// Return a mutable slice of the whole string's buffer
|
||||
unsafe fn raw_mut_bytes(&mut self) -> &mut [u8] {
|
||||
slice::from_raw_parts_mut(self.xs.as_mut_ptr(), self.capacity())
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> Deref for ArrayString<A> {
|
||||
type Target = str;
|
||||
#[inline]
|
||||
fn deref(&self) -> &str {
|
||||
unsafe {
|
||||
let sl = slice::from_raw_parts(self.xs.as_ptr(), self.len.to_usize());
|
||||
str::from_utf8_unchecked(sl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> DerefMut for ArrayString<A> {
|
||||
#[inline]
|
||||
fn deref_mut(&mut self) -> &mut str {
|
||||
unsafe {
|
||||
let sl = slice::from_raw_parts_mut(self.xs.as_mut_ptr(), self.len.to_usize());
|
||||
// FIXME: Nothing but transmute to do this right now
|
||||
mem::transmute(sl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> PartialEq for ArrayString<A> {
|
||||
fn eq(&self, rhs: &Self) -> bool {
|
||||
**self == **rhs
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> PartialEq<str> for ArrayString<A> {
|
||||
fn eq(&self, rhs: &str) -> bool {
|
||||
&**self == rhs
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> PartialEq<ArrayString<A>> for str {
|
||||
fn eq(&self, rhs: &ArrayString<A>) -> bool {
|
||||
self == &**rhs
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> Eq for ArrayString<A> { }
|
||||
|
||||
impl<A: Array<Item=u8>> Hash for ArrayString<A> {
|
||||
fn hash<H: Hasher>(&self, h: &mut H) {
|
||||
(**self).hash(h)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> Borrow<str> for ArrayString<A> {
|
||||
fn borrow(&self) -> &str { self }
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> AsRef<str> for ArrayString<A> {
|
||||
fn as_ref(&self) -> &str { self }
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> fmt::Debug for ArrayString<A> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> fmt::Display for ArrayString<A> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
|
||||
}
|
||||
|
||||
/// `Write` appends written data to the end of the string.
|
||||
impl<A: Array<Item=u8>> fmt::Write for ArrayString<A> {
|
||||
fn write_char(&mut self, c: char) -> fmt::Result {
|
||||
self.push(c).map_err(|_| fmt::Error)
|
||||
}
|
||||
fn write_str(&mut self, s: &str) -> fmt::Result {
|
||||
self.push_str(s).map_err(|_| fmt::Error)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8> + Copy> Clone for ArrayString<A> {
|
||||
fn clone(&self) -> ArrayString<A> {
|
||||
*self
|
||||
}
|
||||
fn clone_from(&mut self, rhs: &Self) {
|
||||
// guaranteed to fit due to types matching.
|
||||
self.clear();
|
||||
self.push_str(rhs).ok();
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> PartialOrd for ArrayString<A> {
|
||||
fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
|
||||
(**self).partial_cmp(&**rhs)
|
||||
}
|
||||
fn lt(&self, rhs: &Self) -> bool { **self < **rhs }
|
||||
fn le(&self, rhs: &Self) -> bool { **self <= **rhs }
|
||||
fn gt(&self, rhs: &Self) -> bool { **self > **rhs }
|
||||
fn ge(&self, rhs: &Self) -> bool { **self >= **rhs }
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> PartialOrd<str> for ArrayString<A> {
|
||||
fn partial_cmp(&self, rhs: &str) -> Option<cmp::Ordering> {
|
||||
(**self).partial_cmp(rhs)
|
||||
}
|
||||
fn lt(&self, rhs: &str) -> bool { &**self < rhs }
|
||||
fn le(&self, rhs: &str) -> bool { &**self <= rhs }
|
||||
fn gt(&self, rhs: &str) -> bool { &**self > rhs }
|
||||
fn ge(&self, rhs: &str) -> bool { &**self >= rhs }
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> PartialOrd<ArrayString<A>> for str {
|
||||
fn partial_cmp(&self, rhs: &ArrayString<A>) -> Option<cmp::Ordering> {
|
||||
self.partial_cmp(&**rhs)
|
||||
}
|
||||
fn lt(&self, rhs: &ArrayString<A>) -> bool { self < &**rhs }
|
||||
fn le(&self, rhs: &ArrayString<A>) -> bool { self <= &**rhs }
|
||||
fn gt(&self, rhs: &ArrayString<A>) -> bool { self > &**rhs }
|
||||
fn ge(&self, rhs: &ArrayString<A>) -> bool { self >= &**rhs }
|
||||
}
|
||||
|
||||
impl<A: Array<Item=u8>> Ord for ArrayString<A> {
|
||||
fn cmp(&self, rhs: &Self) -> cmp::Ordering {
|
||||
(**self).cmp(&**rhs)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,876 @@
|
|||
//! **arrayvec** provides the types `ArrayVec` and `ArrayString`:
|
||||
//! array-backed vector and string types, which store their contents inline.
|
||||
//!
|
||||
//! The **arrayvec** crate has the following cargo feature flags:
|
||||
//!
|
||||
//! - `std`
|
||||
//! - Optional, enabled by default
|
||||
//! - Requires Rust 1.6 *to disable*
|
||||
//! - Use libstd
|
||||
//!
|
||||
//! - `use_union`
|
||||
//! - Optional
|
||||
//! - Requires Rust nightly channel
|
||||
//! - Use the unstable feature untagged unions for the internal implementation,
|
||||
//! which has reduced space overhead
|
||||
//!
|
||||
//! - `use_generic_array`
|
||||
//! - Optional
|
||||
//! - Requires Rust stable channel
|
||||
//! - Depend on generic-array and allow using it just like a fixed
|
||||
//! size array for ArrayVec storage.
|
||||
#![doc(html_root_url="https://docs.rs/arrayvec/0.3/")]
|
||||
#![cfg_attr(not(feature="std"), no_std)]
|
||||
extern crate odds;
|
||||
extern crate nodrop;
|
||||
|
||||
#[cfg(feature = "use_generic_array")]
|
||||
extern crate generic_array;
|
||||
|
||||
#[cfg(not(feature="std"))]
|
||||
extern crate core as std;
|
||||
|
||||
use std::cmp;
|
||||
use std::iter;
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
use std::ops::{
|
||||
Deref,
|
||||
DerefMut,
|
||||
};
|
||||
use std::slice;
|
||||
|
||||
// extra traits
|
||||
use std::borrow::{Borrow, BorrowMut};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::fmt;
|
||||
|
||||
#[cfg(feature="std")]
|
||||
use std::io;
|
||||
#[cfg(feature="std")]
|
||||
use std::error::Error;
|
||||
#[cfg(feature="std")]
|
||||
use std::any::Any; // core but unused
|
||||
|
||||
use nodrop::NoDrop;
|
||||
|
||||
mod array;
|
||||
mod array_string;
|
||||
|
||||
pub use array::Array;
|
||||
pub use odds::IndexRange as RangeArgument;
|
||||
use array::Index;
|
||||
pub use array_string::ArrayString;
|
||||
|
||||
|
||||
unsafe fn new_array<A: Array>() -> A {
|
||||
// Note: Returning an uninitialized value here only works
|
||||
// if we can be sure the data is never used. The nullable pointer
|
||||
// inside enum optimization conflicts with this this for example,
|
||||
// so we need to be extra careful. See `NoDrop` enum.
|
||||
mem::uninitialized()
|
||||
}
|
||||
|
||||
/// A vector with a fixed capacity.
|
||||
///
|
||||
/// The `ArrayVec` is a vector backed by a fixed size array. It keeps track of
|
||||
/// the number of initialized elements.
|
||||
///
|
||||
/// The vector is a contiguous value that you can store directly on the stack
|
||||
/// if needed.
|
||||
///
|
||||
/// It offers a simple API but also dereferences to a slice, so
|
||||
/// that the full slice API is available.
|
||||
///
|
||||
/// ArrayVec can be converted into a by value iterator.
|
||||
pub struct ArrayVec<A: Array> {
|
||||
xs: NoDrop<A>,
|
||||
len: A::Index,
|
||||
}
|
||||
|
||||
impl<A: Array> Drop for ArrayVec<A> {
|
||||
fn drop(&mut self) {
|
||||
self.clear();
|
||||
|
||||
// NoDrop inhibits array's drop
|
||||
// panic safety: NoDrop::drop will trigger on panic, so the inner
|
||||
// array will not drop even after panic.
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> ArrayVec<A> {
|
||||
/// Create a new empty `ArrayVec`.
|
||||
///
|
||||
/// Capacity is inferred from the type parameter.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::<[_; 16]>::new();
|
||||
/// array.push(1);
|
||||
/// array.push(2);
|
||||
/// assert_eq!(&array[..], &[1, 2]);
|
||||
/// assert_eq!(array.capacity(), 16);
|
||||
/// ```
|
||||
pub fn new() -> ArrayVec<A> {
|
||||
unsafe {
|
||||
ArrayVec { xs: NoDrop::new(new_array()), len: Index::from(0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the number of elements in the `ArrayVec`.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::from([1, 2, 3]);
|
||||
/// array.pop();
|
||||
/// assert_eq!(array.len(), 2);
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize { self.len.to_usize() }
|
||||
|
||||
/// Return the capacity of the `ArrayVec`.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let array = ArrayVec::from([1, 2, 3]);
|
||||
/// assert_eq!(array.capacity(), 3);
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn capacity(&self) -> usize { A::capacity() }
|
||||
|
||||
/// Return if the `ArrayVec` is completely filled.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::<[_; 1]>::new();
|
||||
/// assert!(!array.is_full());
|
||||
/// array.push(1);
|
||||
/// assert!(array.is_full());
|
||||
/// ```
|
||||
pub fn is_full(&self) -> bool { self.len() == self.capacity() }
|
||||
|
||||
/// Push `element` to the end of the vector.
|
||||
///
|
||||
/// Return `None` if the push succeeds, or and return `Some(` *element* `)`
|
||||
/// if the vector is full.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::<[_; 2]>::new();
|
||||
///
|
||||
/// array.push(1);
|
||||
/// array.push(2);
|
||||
/// let overflow = array.push(3);
|
||||
///
|
||||
/// assert_eq!(&array[..], &[1, 2]);
|
||||
/// assert_eq!(overflow, Some(3));
|
||||
/// ```
|
||||
pub fn push(&mut self, element: A::Item) -> Option<A::Item> {
|
||||
if self.len() < A::capacity() {
|
||||
let len = self.len();
|
||||
unsafe {
|
||||
ptr::write(self.get_unchecked_mut(len), element);
|
||||
self.set_len(len + 1);
|
||||
}
|
||||
None
|
||||
} else {
|
||||
Some(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert `element` in position `index`.
|
||||
///
|
||||
/// Shift up all elements after `index`. If any is pushed out, it is returned.
|
||||
///
|
||||
/// Return `None` if no element is shifted out.
|
||||
///
|
||||
/// `index` must be <= `self.len()` and < `self.capacity()`. Note that any
|
||||
/// out of bounds index insert results in the element being "shifted out"
|
||||
/// and returned directly.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::<[_; 2]>::new();
|
||||
///
|
||||
/// assert_eq!(array.insert(0, "x"), None);
|
||||
/// assert_eq!(array.insert(0, "y"), None);
|
||||
/// assert_eq!(array.insert(0, "z"), Some("x"));
|
||||
/// assert_eq!(array.insert(1, "w"), Some("y"));
|
||||
/// assert_eq!(&array[..], &["z", "w"]);
|
||||
///
|
||||
/// ```
|
||||
pub fn insert(&mut self, index: usize, element: A::Item) -> Option<A::Item> {
|
||||
if index > self.len() || index == self.capacity() {
|
||||
return Some(element);
|
||||
}
|
||||
let mut ret = None;
|
||||
if self.len() == self.capacity() {
|
||||
ret = self.pop();
|
||||
}
|
||||
let len = self.len();
|
||||
|
||||
// follows is just like Vec<T>
|
||||
unsafe { // infallible
|
||||
// The spot to put the new value
|
||||
{
|
||||
let p = self.get_unchecked_mut(index) as *mut _;
|
||||
// Shift everything over to make space. (Duplicating the
|
||||
// `index`th element into two consecutive places.)
|
||||
ptr::copy(p, p.offset(1), len - index);
|
||||
// Write it in, overwriting the first copy of the `index`th
|
||||
// element.
|
||||
ptr::write(p, element);
|
||||
}
|
||||
self.set_len(len + 1);
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
/// Remove the last element in the vector.
|
||||
///
|
||||
/// Return `Some(` *element* `)` if the vector is non-empty, else `None`.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::<[_; 2]>::new();
|
||||
///
|
||||
/// array.push(1);
|
||||
///
|
||||
/// assert_eq!(array.pop(), Some(1));
|
||||
/// assert_eq!(array.pop(), None);
|
||||
/// ```
|
||||
pub fn pop(&mut self) -> Option<A::Item> {
|
||||
if self.len() == 0 {
|
||||
return None
|
||||
}
|
||||
unsafe {
|
||||
let new_len = self.len() - 1;
|
||||
self.set_len(new_len);
|
||||
Some(ptr::read(self.get_unchecked_mut(new_len)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the element at `index` and swap the last element into its place.
|
||||
///
|
||||
/// This operation is O(1).
|
||||
///
|
||||
/// Return `Some(` *element* `)` if the index is in bounds, else `None`.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::from([1, 2, 3]);
|
||||
///
|
||||
/// assert_eq!(array.swap_remove(0), Some(1));
|
||||
/// assert_eq!(&array[..], &[3, 2]);
|
||||
///
|
||||
/// assert_eq!(array.swap_remove(10), None);
|
||||
/// ```
|
||||
pub fn swap_remove(&mut self, index: usize) -> Option<A::Item> {
|
||||
let len = self.len();
|
||||
if index >= len {
|
||||
return None
|
||||
}
|
||||
self.swap(index, len - 1);
|
||||
self.pop()
|
||||
}
|
||||
|
||||
/// Remove the element at `index` and shift down the following elements.
|
||||
///
|
||||
/// Return `Some(` *element* `)` if the index is in bounds, else `None`.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::from([1, 2, 3]);
|
||||
///
|
||||
/// assert_eq!(array.remove(0), Some(1));
|
||||
/// assert_eq!(&array[..], &[2, 3]);
|
||||
///
|
||||
/// assert_eq!(array.remove(10), None);
|
||||
/// ```
|
||||
pub fn remove(&mut self, index: usize) -> Option<A::Item> {
|
||||
if index >= self.len() {
|
||||
None
|
||||
} else {
|
||||
self.drain(index..index + 1).next()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove all elements in the vector.
|
||||
pub fn clear(&mut self) {
|
||||
while let Some(_) = self.pop() { }
|
||||
}
|
||||
|
||||
/// Retains only the elements specified by the predicate.
|
||||
///
|
||||
/// In other words, remove all elements `e` such that `f(&mut e)` returns false.
|
||||
/// This method operates in place and preserves the order of the retained
|
||||
/// elements.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::from([1, 2, 3, 4]);
|
||||
/// array.retain(|x| *x & 1 != 0 );
|
||||
/// assert_eq!(&array[..], &[1, 3]);
|
||||
/// ```
|
||||
pub fn retain<F>(&mut self, mut f: F)
|
||||
where F: FnMut(&mut A::Item) -> bool
|
||||
{
|
||||
let len = self.len();
|
||||
let mut del = 0;
|
||||
{
|
||||
let v = &mut **self;
|
||||
|
||||
for i in 0..len {
|
||||
if !f(&mut v[i]) {
|
||||
del += 1;
|
||||
} else if del > 0 {
|
||||
v.swap(i - del, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
if del > 0 {
|
||||
self.drain(len - del..);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the vector's length without dropping or moving out elements
|
||||
///
|
||||
/// May panic if `length` is greater than the capacity.
|
||||
///
|
||||
/// This function is `unsafe` because it changes the notion of the
|
||||
/// number of “valid” elements in the vector. Use with care.
|
||||
#[inline]
|
||||
pub unsafe fn set_len(&mut self, length: usize) {
|
||||
debug_assert!(length <= self.capacity());
|
||||
self.len = Index::from(length);
|
||||
}
|
||||
|
||||
|
||||
/// Create a draining iterator that removes the specified range in the vector
|
||||
/// and yields the removed items from start to end. The element range is
|
||||
/// removed even if the iterator is not consumed until the end.
|
||||
///
|
||||
/// Note: It is unspecified how many elements are removed from the vector,
|
||||
/// if the `Drain` value is leaked.
|
||||
///
|
||||
/// **Panics** if the starting point is greater than the end point or if
|
||||
/// the end point is greater than the length of the vector.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut v = ArrayVec::from([1, 2, 3]);
|
||||
/// let u: Vec<_> = v.drain(0..2).collect();
|
||||
/// assert_eq!(&v[..], &[3]);
|
||||
/// assert_eq!(&u[..], &[1, 2]);
|
||||
/// ```
|
||||
pub fn drain<R: RangeArgument>(&mut self, range: R) -> Drain<A> {
|
||||
// Memory safety
|
||||
//
|
||||
// When the Drain is first created, it shortens the length of
|
||||
// the source vector to make sure no uninitalized or moved-from elements
|
||||
// are accessible at all if the Drain's destructor never gets to run.
|
||||
//
|
||||
// Drain will ptr::read out the values to remove.
|
||||
// When finished, remaining tail of the vec is copied back to cover
|
||||
// the hole, and the vector length is restored to the new length.
|
||||
//
|
||||
let len = self.len();
|
||||
let start = range.start().unwrap_or(0);
|
||||
let end = range.end().unwrap_or(len);
|
||||
// bounds check happens here
|
||||
let range_slice: *const _ = &self[start..end];
|
||||
|
||||
unsafe {
|
||||
// set self.vec length's to start, to be safe in case Drain is leaked
|
||||
self.set_len(start);
|
||||
Drain {
|
||||
tail_start: end,
|
||||
tail_len: len - end,
|
||||
iter: (*range_slice).iter(),
|
||||
vec: self as *mut _,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the inner fixed size array, if it is full to its capacity.
|
||||
///
|
||||
/// Return an `Ok` value with the array if length equals capacity,
|
||||
/// return an `Err` with self otherwise.
|
||||
///
|
||||
/// `Note:` This function may incur unproportionally large overhead
|
||||
/// to move the array out, its performance is not optimal.
|
||||
pub fn into_inner(self) -> Result<A, Self> {
|
||||
if self.len() < self.capacity() {
|
||||
Err(self)
|
||||
} else {
|
||||
unsafe {
|
||||
let array = ptr::read(&*self.xs);
|
||||
mem::forget(self);
|
||||
Ok(array)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispose of `self` without the overwriting that is needed in Drop.
|
||||
pub fn dispose(mut self) {
|
||||
self.clear();
|
||||
mem::forget(self);
|
||||
}
|
||||
|
||||
/// Return a slice containing all elements of the vector.
|
||||
pub fn as_slice(&self) -> &[A::Item] {
|
||||
self
|
||||
}
|
||||
|
||||
/// Return a mutable slice containing all elements of the vector.
|
||||
pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> Deref for ArrayVec<A> {
|
||||
type Target = [A::Item];
|
||||
#[inline]
|
||||
fn deref(&self) -> &[A::Item] {
|
||||
unsafe {
|
||||
slice::from_raw_parts(self.xs.as_ptr(), self.len())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> DerefMut for ArrayVec<A> {
|
||||
#[inline]
|
||||
fn deref_mut(&mut self) -> &mut [A::Item] {
|
||||
let len = self.len();
|
||||
unsafe {
|
||||
slice::from_raw_parts_mut(self.xs.as_mut_ptr(), len)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an `ArrayVec` from an array.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::from([1, 2, 3]);
|
||||
/// assert_eq!(array.len(), 3);
|
||||
/// assert_eq!(array.capacity(), 3);
|
||||
/// ```
|
||||
impl<A: Array> From<A> for ArrayVec<A> {
|
||||
fn from(array: A) -> Self {
|
||||
ArrayVec { xs: NoDrop::new(array), len: Index::from(A::capacity()) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Iterate the `ArrayVec` with references to each element.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let array = ArrayVec::from([1, 2, 3]);
|
||||
///
|
||||
/// for elt in &array {
|
||||
/// // ...
|
||||
/// }
|
||||
/// ```
|
||||
impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
|
||||
type Item = &'a A::Item;
|
||||
type IntoIter = slice::Iter<'a, A::Item>;
|
||||
fn into_iter(self) -> Self::IntoIter { self.iter() }
|
||||
}
|
||||
|
||||
/// Iterate the `ArrayVec` with mutable references to each element.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// let mut array = ArrayVec::from([1, 2, 3]);
|
||||
///
|
||||
/// for elt in &mut array {
|
||||
/// // ...
|
||||
/// }
|
||||
/// ```
|
||||
impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
|
||||
type Item = &'a mut A::Item;
|
||||
type IntoIter = slice::IterMut<'a, A::Item>;
|
||||
fn into_iter(self) -> Self::IntoIter { self.iter_mut() }
|
||||
}
|
||||
|
||||
/// Iterate the `ArrayVec` with each element by value.
|
||||
///
|
||||
/// The vector is consumed by this operation.
|
||||
///
|
||||
/// ```
|
||||
/// use arrayvec::ArrayVec;
|
||||
///
|
||||
/// for elt in ArrayVec::from([1, 2, 3]) {
|
||||
/// // ...
|
||||
/// }
|
||||
/// ```
|
||||
impl<A: Array> IntoIterator for ArrayVec<A> {
|
||||
type Item = A::Item;
|
||||
type IntoIter = IntoIter<A>;
|
||||
fn into_iter(self) -> IntoIter<A> {
|
||||
IntoIter { index: Index::from(0), v: self, }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// By-value iterator for `ArrayVec`.
|
||||
pub struct IntoIter<A: Array> {
|
||||
index: A::Index,
|
||||
v: ArrayVec<A>,
|
||||
}
|
||||
|
||||
impl<A: Array> Iterator for IntoIter<A> {
|
||||
type Item = A::Item;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<A::Item> {
|
||||
if self.index == self.v.len {
|
||||
None
|
||||
} else {
|
||||
unsafe {
|
||||
let index = self.index.to_usize();
|
||||
self.index = Index::from(index + 1);
|
||||
Some(ptr::read(self.v.get_unchecked_mut(index)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.v.len() - self.index.to_usize();
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> DoubleEndedIterator for IntoIter<A> {
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<A::Item> {
|
||||
if self.index == self.v.len {
|
||||
None
|
||||
} else {
|
||||
unsafe {
|
||||
let new_len = self.v.len() - 1;
|
||||
self.v.set_len(new_len);
|
||||
Some(ptr::read(self.v.get_unchecked_mut(new_len)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> ExactSizeIterator for IntoIter<A> { }
|
||||
|
||||
impl<A: Array> Drop for IntoIter<A> {
|
||||
fn drop(&mut self) {
|
||||
// panic safety: Set length to 0 before dropping elements.
|
||||
let index = self.index.to_usize();
|
||||
let len = self.v.len();
|
||||
unsafe {
|
||||
self.v.set_len(0);
|
||||
let elements = slice::from_raw_parts(self.v.get_unchecked_mut(index),
|
||||
len - index);
|
||||
for elt in elements {
|
||||
ptr::read(elt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A draining iterator for `ArrayVec`.
|
||||
pub struct Drain<'a, A>
|
||||
where A: Array,
|
||||
A::Item: 'a,
|
||||
{
|
||||
/// Index of tail to preserve
|
||||
tail_start: usize,
|
||||
/// Length of tail
|
||||
tail_len: usize,
|
||||
/// Current remaining range to remove
|
||||
iter: slice::Iter<'a, A::Item>,
|
||||
vec: *mut ArrayVec<A>,
|
||||
}
|
||||
|
||||
unsafe impl<'a, A: Array + Sync> Sync for Drain<'a, A> {}
|
||||
unsafe impl<'a, A: Array + Send> Send for Drain<'a, A> {}
|
||||
|
||||
impl<'a, A: Array> Iterator for Drain<'a, A>
|
||||
where A::Item: 'a,
|
||||
{
|
||||
type Item = A::Item;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.iter.next().map(|elt|
|
||||
unsafe {
|
||||
ptr::read(elt as *const _)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A: Array> DoubleEndedIterator for Drain<'a, A>
|
||||
where A::Item: 'a,
|
||||
{
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<Self::Item> {
|
||||
self.iter.next_back().map(|elt|
|
||||
unsafe {
|
||||
ptr::read(elt as *const _)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A: Array> ExactSizeIterator for Drain<'a, A> where A::Item: 'a {}
|
||||
|
||||
impl<'a, A: Array> Drop for Drain<'a, A>
|
||||
where A::Item: 'a
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
// len is currently 0 so panicking while dropping will not cause a double drop.
|
||||
|
||||
// exhaust self first
|
||||
while let Some(_) = self.next() { }
|
||||
|
||||
if self.tail_len > 0 {
|
||||
unsafe {
|
||||
let source_vec = &mut *self.vec;
|
||||
// memmove back untouched tail, update to new length
|
||||
let start = source_vec.len();
|
||||
let tail = self.tail_start;
|
||||
let src = source_vec.as_ptr().offset(tail as isize);
|
||||
let dst = source_vec.as_mut_ptr().offset(start as isize);
|
||||
ptr::copy(src, dst, self.tail_len);
|
||||
source_vec.set_len(start + self.tail_len);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// Extend the `ArrayVec` with an iterator.
|
||||
///
|
||||
/// Does not extract more items than there is space for. No error
|
||||
/// occurs if there are more iterator elements.
|
||||
impl<A: Array> Extend<A::Item> for ArrayVec<A> {
|
||||
fn extend<T: IntoIterator<Item=A::Item>>(&mut self, iter: T) {
|
||||
let take = self.capacity() - self.len();
|
||||
for elt in iter.into_iter().take(take) {
|
||||
self.push(elt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an `ArrayVec` from an iterator.
|
||||
///
|
||||
/// Does not extract more items than there is space for. No error
|
||||
/// occurs if there are more iterator elements.
|
||||
impl<A: Array> iter::FromIterator<A::Item> for ArrayVec<A> {
|
||||
fn from_iter<T: IntoIterator<Item=A::Item>>(iter: T) -> Self {
|
||||
let mut array = ArrayVec::new();
|
||||
array.extend(iter);
|
||||
array
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> Clone for ArrayVec<A>
|
||||
where A::Item: Clone
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
self.iter().cloned().collect()
|
||||
}
|
||||
|
||||
fn clone_from(&mut self, rhs: &Self) {
|
||||
// recursive case for the common prefix
|
||||
let prefix = cmp::min(self.len(), rhs.len());
|
||||
{
|
||||
let a = &mut self[..prefix];
|
||||
let b = &rhs[..prefix];
|
||||
for i in 0..prefix {
|
||||
a[i].clone_from(&b[i]);
|
||||
}
|
||||
}
|
||||
if prefix < self.len() {
|
||||
// rhs was shorter
|
||||
for _ in 0..self.len() - prefix {
|
||||
self.pop();
|
||||
}
|
||||
} else {
|
||||
for elt in &rhs[self.len()..] {
|
||||
self.push(elt.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> Hash for ArrayVec<A>
|
||||
where A::Item: Hash
|
||||
{
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
Hash::hash(&**self, state)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> PartialEq for ArrayVec<A>
|
||||
where A::Item: PartialEq
|
||||
{
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
**self == **other
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> PartialEq<[A::Item]> for ArrayVec<A>
|
||||
where A::Item: PartialEq
|
||||
{
|
||||
fn eq(&self, other: &[A::Item]) -> bool {
|
||||
**self == *other
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq { }
|
||||
|
||||
impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> {
|
||||
fn borrow(&self) -> &[A::Item] { self }
|
||||
}
|
||||
|
||||
impl<A: Array> BorrowMut<[A::Item]> for ArrayVec<A> {
|
||||
fn borrow_mut(&mut self) -> &mut [A::Item] { self }
|
||||
}
|
||||
|
||||
impl<A: Array> AsRef<[A::Item]> for ArrayVec<A> {
|
||||
fn as_ref(&self) -> &[A::Item] { self }
|
||||
}
|
||||
|
||||
impl<A: Array> AsMut<[A::Item]> for ArrayVec<A> {
|
||||
fn as_mut(&mut self) -> &mut [A::Item] { self }
|
||||
}
|
||||
|
||||
impl<A: Array> fmt::Debug for ArrayVec<A> where A::Item: fmt::Debug {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
|
||||
}
|
||||
|
||||
impl<A: Array> Default for ArrayVec<A> {
|
||||
fn default() -> ArrayVec<A> {
|
||||
ArrayVec::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> PartialOrd for ArrayVec<A> where A::Item: PartialOrd {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &ArrayVec<A>) -> Option<cmp::Ordering> {
|
||||
(**self).partial_cmp(other)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn lt(&self, other: &Self) -> bool {
|
||||
(**self).lt(other)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn le(&self, other: &Self) -> bool {
|
||||
(**self).le(other)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn ge(&self, other: &Self) -> bool {
|
||||
(**self).ge(other)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn gt(&self, other: &Self) -> bool {
|
||||
(**self).gt(other)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Array> Ord for ArrayVec<A> where A::Item: Ord {
|
||||
fn cmp(&self, other: &ArrayVec<A>) -> cmp::Ordering {
|
||||
(**self).cmp(other)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature="std")]
|
||||
/// `Write` appends written data to the end of the vector.
|
||||
///
|
||||
/// Requires `features="std"`.
|
||||
impl<A: Array<Item=u8>> io::Write for ArrayVec<A> {
|
||||
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
|
||||
unsafe {
|
||||
let len = self.len();
|
||||
let mut tail = slice::from_raw_parts_mut(self.get_unchecked_mut(len),
|
||||
A::capacity() - len);
|
||||
let result = tail.write(data);
|
||||
if let Ok(written) = result {
|
||||
self.set_len(len + written);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> { Ok(()) }
|
||||
}
|
||||
|
||||
/// Error value indicating insufficient capacity
|
||||
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub struct CapacityError<T = ()> {
|
||||
element: T,
|
||||
}
|
||||
|
||||
impl<T> CapacityError<T> {
|
||||
fn new(element: T) -> CapacityError<T> {
|
||||
CapacityError {
|
||||
element: element,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the overflowing element
|
||||
pub fn element(self) -> T {
|
||||
self.element
|
||||
}
|
||||
|
||||
/// Convert into a `CapacityError` that does not carry an element.
|
||||
pub fn simplify(self) -> CapacityError {
|
||||
CapacityError { element: () }
|
||||
}
|
||||
}
|
||||
|
||||
const CAPERROR: &'static str = "insufficient capacity";
|
||||
|
||||
#[cfg(feature="std")]
|
||||
/// Requires `features="std"`.
|
||||
impl<T: Any> Error for CapacityError<T> {
|
||||
fn description(&self) -> &str {
|
||||
CAPERROR
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> fmt::Display for CapacityError<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", CAPERROR)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> fmt::Debug for CapacityError<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}: {}", "CapacityError", CAPERROR)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
#![cfg(feature = "use_generic_array")]
|
||||
|
||||
extern crate arrayvec;
|
||||
#[macro_use]
|
||||
extern crate generic_array;
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
|
||||
use generic_array::GenericArray;
|
||||
|
||||
use generic_array::typenum::U41;
|
||||
|
||||
#[test]
|
||||
fn test_simple() {
|
||||
let mut vec: ArrayVec<GenericArray<i32, U41>> = ArrayVec::new();
|
||||
|
||||
assert_eq!(vec.len(), 0);
|
||||
assert_eq!(vec.capacity(), 41);
|
||||
vec.extend(0..20);
|
||||
assert_eq!(vec.len(), 20);
|
||||
assert_eq!(&vec[..5], &[0, 1, 2, 3, 4]);
|
||||
}
|
||||
|
|
@ -0,0 +1,443 @@
|
|||
extern crate arrayvec;
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
use arrayvec::ArrayString;
|
||||
use std::mem;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_simple() {
|
||||
use std::ops::Add;
|
||||
|
||||
let mut vec: ArrayVec<[Vec<i32>; 3]> = ArrayVec::new();
|
||||
|
||||
vec.push(vec![1, 2, 3, 4]);
|
||||
vec.push(vec![10]);
|
||||
vec.push(vec![-1, 13, -2]);
|
||||
|
||||
for elt in &vec {
|
||||
assert_eq!(elt.iter().fold(0, Add::add), 10);
|
||||
}
|
||||
|
||||
let sum_len = vec.into_iter().map(|x| x.len()).fold(0, Add::add);
|
||||
assert_eq!(sum_len, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_u16_index() {
|
||||
const N: usize = 4096;
|
||||
let mut vec: ArrayVec<[_; N]> = ArrayVec::new();
|
||||
for _ in 0..N {
|
||||
assert!(vec.push(1u8).is_none());
|
||||
}
|
||||
assert!(vec.push(0).is_some());
|
||||
assert_eq!(vec.len(), N);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_iter() {
|
||||
let mut iter = ArrayVec::from([1, 2, 3]).into_iter();
|
||||
assert_eq!(iter.size_hint(), (3, Some(3)));
|
||||
assert_eq!(iter.next_back(), Some(3));
|
||||
assert_eq!(iter.next(), Some(1));
|
||||
assert_eq!(iter.next_back(), Some(2));
|
||||
assert_eq!(iter.size_hint(), (0, Some(0)));
|
||||
assert_eq!(iter.next_back(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_drop() {
|
||||
use std::cell::Cell;
|
||||
|
||||
let flag = &Cell::new(0);
|
||||
|
||||
struct Bump<'a>(&'a Cell<i32>);
|
||||
|
||||
impl<'a> Drop for Bump<'a> {
|
||||
fn drop(&mut self) {
|
||||
let n = self.0.get();
|
||||
self.0.set(n + 1);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let mut array = ArrayVec::<[Bump; 128]>::new();
|
||||
array.push(Bump(flag));
|
||||
array.push(Bump(flag));
|
||||
}
|
||||
assert_eq!(flag.get(), 2);
|
||||
|
||||
// test something with the nullable pointer optimization
|
||||
flag.set(0);
|
||||
|
||||
{
|
||||
let mut array = ArrayVec::<[_; 3]>::new();
|
||||
array.push(vec![Bump(flag)]);
|
||||
array.push(vec![Bump(flag), Bump(flag)]);
|
||||
array.push(vec![]);
|
||||
array.push(vec![Bump(flag)]);
|
||||
assert_eq!(flag.get(), 1);
|
||||
drop(array.pop());
|
||||
assert_eq!(flag.get(), 1);
|
||||
drop(array.pop());
|
||||
assert_eq!(flag.get(), 3);
|
||||
}
|
||||
|
||||
assert_eq!(flag.get(), 4);
|
||||
|
||||
// test into_inner
|
||||
flag.set(0);
|
||||
{
|
||||
let mut array = ArrayVec::<[_; 3]>::new();
|
||||
array.push(Bump(flag));
|
||||
array.push(Bump(flag));
|
||||
array.push(Bump(flag));
|
||||
let inner = array.into_inner();
|
||||
assert!(inner.is_ok());
|
||||
assert_eq!(flag.get(), 0);
|
||||
drop(inner);
|
||||
assert_eq!(flag.get(), 3);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extend() {
|
||||
let mut range = 0..10;
|
||||
|
||||
let mut array: ArrayVec<[_; 5]> = range.by_ref().collect();
|
||||
assert_eq!(&array[..], &[0, 1, 2, 3, 4]);
|
||||
assert_eq!(range.next(), Some(5));
|
||||
|
||||
array.extend(range.by_ref());
|
||||
assert_eq!(range.next(), Some(6));
|
||||
|
||||
let mut array: ArrayVec<[_; 10]> = (0..3).collect();
|
||||
assert_eq!(&array[..], &[0, 1, 2]);
|
||||
array.extend(3..5);
|
||||
assert_eq!(&array[..], &[0, 1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_send_sync() {
|
||||
let data = ArrayVec::<[Vec<i32>; 5]>::new();
|
||||
&data as &Send;
|
||||
&data as &Sync;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_size() {
|
||||
// Future rust will kill these drop flags!
|
||||
// 4 elements size + 1 len + 1 enum tag + [1 drop flag]
|
||||
type ByteArray = ArrayVec<[u8; 4]>;
|
||||
println!("{}", mem::size_of::<ByteArray>());
|
||||
assert!(mem::size_of::<ByteArray>() <= 8);
|
||||
|
||||
// 12 element size + 1 enum tag + 3 padding + 1 len + 1 drop flag + 2 padding
|
||||
type QuadArray = ArrayVec<[u32; 3]>;
|
||||
println!("{}", mem::size_of::<QuadArray>());
|
||||
assert!(mem::size_of::<QuadArray>() <= 24);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_drain() {
|
||||
let mut v = ArrayVec::from([0; 8]);
|
||||
v.pop();
|
||||
v.drain(0..7);
|
||||
assert_eq!(&v[..], &[]);
|
||||
|
||||
v.extend(0..);
|
||||
v.drain(1..4);
|
||||
assert_eq!(&v[..], &[0, 4, 5, 6, 7]);
|
||||
let u: ArrayVec<[_; 3]> = v.drain(1..4).rev().collect();
|
||||
assert_eq!(&u[..], &[6, 5, 4]);
|
||||
assert_eq!(&v[..], &[0, 7]);
|
||||
v.drain(..);
|
||||
assert_eq!(&v[..], &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_retain() {
|
||||
let mut v = ArrayVec::from([0; 8]);
|
||||
for (i, elt) in v.iter_mut().enumerate() {
|
||||
*elt = i;
|
||||
}
|
||||
v.retain(|_| true);
|
||||
assert_eq!(&v[..], &[0, 1, 2, 3, 4, 5, 6, 7]);
|
||||
v.retain(|elt| {
|
||||
*elt /= 2;
|
||||
*elt % 2 == 0
|
||||
});
|
||||
assert_eq!(&v[..], &[0, 0, 2, 2]);
|
||||
v.retain(|_| false);
|
||||
assert_eq!(&v[..], &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_drain_oob() {
|
||||
let mut v = ArrayVec::from([0; 8]);
|
||||
v.pop();
|
||||
v.drain(0..8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_drop_panic() {
|
||||
struct DropPanic;
|
||||
|
||||
impl Drop for DropPanic {
|
||||
fn drop(&mut self) {
|
||||
panic!("drop");
|
||||
}
|
||||
}
|
||||
|
||||
let mut array = ArrayVec::<[DropPanic; 1]>::new();
|
||||
array.push(DropPanic);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_drop_panic_into_iter() {
|
||||
struct DropPanic;
|
||||
|
||||
impl Drop for DropPanic {
|
||||
fn drop(&mut self) {
|
||||
panic!("drop");
|
||||
}
|
||||
}
|
||||
|
||||
let mut array = ArrayVec::<[DropPanic; 1]>::new();
|
||||
array.push(DropPanic);
|
||||
array.into_iter();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_insert() {
|
||||
let mut v = ArrayVec::from([]);
|
||||
assert_eq!(v.push(1), Some(1));
|
||||
assert_eq!(v.insert(0, 1), Some(1));
|
||||
|
||||
let mut v = ArrayVec::<[_; 3]>::new();
|
||||
v.insert(0, 0);
|
||||
v.insert(1, 1);
|
||||
v.insert(2, 2);
|
||||
v.insert(3, 3);
|
||||
assert_eq!(&v[..], &[0, 1, 2]);
|
||||
v.insert(1, 9);
|
||||
assert_eq!(&v[..], &[0, 9, 1]);
|
||||
|
||||
let mut v = ArrayVec::from([2]);
|
||||
assert_eq!(v.insert(1, 1), Some(1));
|
||||
assert_eq!(v.insert(2, 1), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_in_option() {
|
||||
// Sanity check that we are sound w.r.t Option & non-nullable layout optimization.
|
||||
let mut v = Some(ArrayVec::<[&i32; 1]>::new());
|
||||
assert!(v.is_some());
|
||||
unsafe {
|
||||
*v.as_mut().unwrap().get_unchecked_mut(0) = mem::zeroed();
|
||||
}
|
||||
assert!(v.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_into_inner_1() {
|
||||
let mut v = ArrayVec::from([1, 2]);
|
||||
v.pop();
|
||||
let u = v.clone();
|
||||
assert_eq!(v.into_inner(), Err(u));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_into_inner_2() {
|
||||
let mut v = ArrayVec::<[String; 4]>::new();
|
||||
v.push("a".into());
|
||||
v.push("b".into());
|
||||
v.push("c".into());
|
||||
v.push("d".into());
|
||||
assert_eq!(v.into_inner().unwrap(), ["a", "b", "c", "d"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_into_inner_3_() {
|
||||
let mut v = ArrayVec::<[i32; 4]>::new();
|
||||
v.extend(1..);
|
||||
assert_eq!(v.into_inner().unwrap(), [1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write() {
|
||||
use std::io::Write;
|
||||
let mut v = ArrayVec::<[_; 8]>::new();
|
||||
write!(&mut v, "\x01\x02\x03").unwrap();
|
||||
assert_eq!(&v[..], &[1, 2, 3]);
|
||||
let r = v.write(&[9; 16]).unwrap();
|
||||
assert_eq!(r, 5);
|
||||
assert_eq!(&v[..], &[1, 2, 3, 9, 9, 9, 9, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_clone_from() {
|
||||
let mut v = ArrayVec::<[_; 4]>::new();
|
||||
v.push(vec![1, 2]);
|
||||
v.push(vec![3, 4, 5]);
|
||||
v.push(vec![6]);
|
||||
let reference = v.to_vec();
|
||||
let mut u = ArrayVec::<[_; 4]>::new();
|
||||
u.clone_from(&v);
|
||||
assert_eq!(&u, &reference[..]);
|
||||
|
||||
let mut t = ArrayVec::<[_; 4]>::new();
|
||||
t.push(vec![97]);
|
||||
t.push(vec![]);
|
||||
t.push(vec![5, 6, 2]);
|
||||
t.push(vec![2]);
|
||||
t.clone_from(&v);
|
||||
assert_eq!(&t, &reference[..]);
|
||||
t.clear();
|
||||
t.clone_from(&v);
|
||||
assert_eq!(&t, &reference[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string() {
|
||||
use std::error::Error;
|
||||
|
||||
let text = "hello world";
|
||||
let mut s = ArrayString::<[_; 16]>::new();
|
||||
s.push_str(text).unwrap();
|
||||
assert_eq!(&s, text);
|
||||
assert_eq!(text, &s);
|
||||
|
||||
// Make sure Hash / Eq / Borrow match up so we can use HashMap
|
||||
let mut map = HashMap::new();
|
||||
map.insert(s, 1);
|
||||
assert_eq!(map[text], 1);
|
||||
|
||||
let mut t = ArrayString::<[_; 2]>::new();
|
||||
assert!(t.push_str(text).is_err());
|
||||
assert_eq!(&t, "");
|
||||
|
||||
t.push_str("ab").unwrap();
|
||||
// DerefMut
|
||||
let tmut: &mut str = &mut t;
|
||||
assert_eq!(tmut, "ab");
|
||||
|
||||
// Test Error trait / try
|
||||
let t = || -> Result<(), Box<Error>> {
|
||||
let mut t = ArrayString::<[_; 2]>::new();
|
||||
try!(t.push_str(text));
|
||||
Ok(())
|
||||
}();
|
||||
assert!(t.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_from() {
|
||||
let text = "hello world";
|
||||
// Test `from` constructor
|
||||
let u = ArrayString::<[_; 11]>::from(text).unwrap();
|
||||
assert_eq!(&u, text);
|
||||
assert_eq!(u.len(), text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_from_bytes() {
|
||||
let text = "hello world";
|
||||
let u = ArrayString::from_byte_string(b"hello world").unwrap();
|
||||
assert_eq!(&u, text);
|
||||
assert_eq!(u.len(), text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_clone() {
|
||||
let text = "hi";
|
||||
let mut s = ArrayString::<[_; 4]>::new();
|
||||
s.push_str("abcd").unwrap();
|
||||
let t = ArrayString::<[_; 4]>::from(text).unwrap();
|
||||
s.clone_from(&t);
|
||||
assert_eq!(&t, &s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_push() {
|
||||
let text = "abcαβγ";
|
||||
let mut s = ArrayString::<[_; 8]>::new();
|
||||
for c in text.chars() {
|
||||
if let Err(_) = s.push(c) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!("abcαβ", &s[..]);
|
||||
s.push('x').ok();
|
||||
assert_eq!("abcαβx", &s[..]);
|
||||
assert!(s.push('x').is_err());
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_insert_at_length() {
|
||||
let mut v = ArrayVec::<[_; 8]>::new();
|
||||
let result1 = v.insert(0, "a");
|
||||
let result2 = v.insert(1, "b");
|
||||
assert!(result1.is_none() && result2.is_none());
|
||||
assert_eq!(&v[..], &["a", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_insert_out_of_bounds() {
|
||||
let mut v = ArrayVec::<[_; 8]>::new();
|
||||
let result = v.insert(1, "test");
|
||||
assert_eq!(result, Some("test"));
|
||||
assert_eq!(v.len(), 0);
|
||||
|
||||
let mut u = ArrayVec::from([1, 2, 3, 4]);
|
||||
let ret = u.insert(3, 99);
|
||||
assert_eq!(&u[..], &[1, 2, 3, 99]);
|
||||
assert_eq!(ret, Some(4));
|
||||
let ret = u.insert(4, 77);
|
||||
assert_eq!(&u[..], &[1, 2, 3, 99]);
|
||||
assert_eq!(ret, Some(77));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_drop_in_insert() {
|
||||
use std::cell::Cell;
|
||||
|
||||
let flag = &Cell::new(0);
|
||||
|
||||
struct Bump<'a>(&'a Cell<i32>);
|
||||
|
||||
impl<'a> Drop for Bump<'a> {
|
||||
fn drop(&mut self) {
|
||||
let n = self.0.get();
|
||||
self.0.set(n + 1);
|
||||
}
|
||||
}
|
||||
|
||||
flag.set(0);
|
||||
|
||||
{
|
||||
let mut array = ArrayVec::<[_; 2]>::new();
|
||||
array.push(Bump(flag));
|
||||
array.insert(0, Bump(flag));
|
||||
assert_eq!(flag.get(), 0);
|
||||
let ret = array.insert(1, Bump(flag));
|
||||
assert_eq!(flag.get(), 0);
|
||||
assert!(ret.is_some());
|
||||
drop(ret);
|
||||
assert_eq!(flag.get(), 1);
|
||||
}
|
||||
assert_eq!(flag.get(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sizes() {
|
||||
let v = ArrayVec::from([0u8; 1 << 16]);
|
||||
assert_eq!(vec![0u8; v.len()], &v[..]);
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"824532e5f3a5ae93bb793e596b027cb8d2f58081daf13338c2e38cf37c45eb3e","src/lib.rs":"af65dcd2a028bc4420bca139f8dd37922f9e101f717e117f4b0ef66a8d70711c"},"package":"52cd74cd09beba596430cc6e3091b74007169a56246e1262f0ba451ea95117b2"}
|
|
@ -0,0 +1,35 @@
|
|||
[package]
|
||||
name = "nodrop"
|
||||
version = "0.1.9"
|
||||
authors = ["bluss"]
|
||||
|
||||
license = "MIT/Apache-2.0"
|
||||
|
||||
description = "A wrapper type to inhibit drop (destructor)."
|
||||
documentation = "http://bluss.github.io/arrayvec/doc/nodrop"
|
||||
repository = "https://github.com/bluss/arrayvec"
|
||||
|
||||
keywords = ["container", "drop", "no_std"]
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
|
||||
# Default, requires Rust 1.6+ to disable
|
||||
# Use libstd
|
||||
std = ["odds/std"]
|
||||
|
||||
# Optional, nightly channel
|
||||
# Use `needs_drop` to skip overwriting if not necessary
|
||||
use_needs_drop = []
|
||||
|
||||
# Optional, nightly channel
|
||||
use_union = ["nodrop-union"]
|
||||
|
||||
[dependencies.odds]
|
||||
version = "0.2.12"
|
||||
default-features = false
|
||||
|
||||
[dependencies.nodrop-union]
|
||||
path = "../nodrop-union"
|
||||
version = "0.1.8"
|
||||
optional = true
|
|
@ -0,0 +1,186 @@
|
|||
//!
|
||||
//! The **nodrop** crate has the following cargo feature flags:
|
||||
//!
|
||||
//! - `std`
|
||||
//! - Optional, enabled by default
|
||||
//! - Requires Rust 1.6 *to disable*
|
||||
//! - Use libstd
|
||||
//! - `use_needs_drop`
|
||||
//! - Optional
|
||||
//! - Requires nightly channel.
|
||||
//! - Use `needs_drop` to skip overwriting if not necessary
|
||||
//! - `use_union`
|
||||
//! - Optional
|
||||
//! - Requires nightly channel
|
||||
//! - Using untagged union, finally we have an implementation of `NoDrop` without hacks,
|
||||
//! for example the fact that `NoDrop<T>` never has a destructor anymore.
|
||||
//!
|
||||
|
||||
#![cfg_attr(feature="use_needs_drop", feature(core_intrinsics))]
|
||||
|
||||
#![cfg_attr(not(any(test, feature="std")), no_std)]
|
||||
#[cfg(not(any(test, feature="std")))]
|
||||
extern crate core as std;
|
||||
|
||||
#[cfg(not(feature = "use_union"))]
|
||||
extern crate odds;
|
||||
|
||||
#[cfg(feature = "use_union")]
|
||||
extern crate nodrop_union as imp;
|
||||
|
||||
pub use imp::NoDrop;
|
||||
|
||||
|
||||
#[cfg(not(feature = "use_union"))]
|
||||
mod imp {
|
||||
use odds::debug_assert_unreachable;
|
||||
use std::ptr;
|
||||
use std::mem;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
/// repr(u8) - Make sure the non-nullable pointer optimization does not occur!
|
||||
#[repr(u8)]
|
||||
enum Flag<T> {
|
||||
Alive(T),
|
||||
// Dummy u8 field below, again to beat the enum layout opt
|
||||
Dropped(u8),
|
||||
}
|
||||
|
||||
|
||||
/// A type holding **T** that will not call its destructor on drop
|
||||
pub struct NoDrop<T>(Flag<T>);
|
||||
|
||||
impl<T> NoDrop<T> {
|
||||
/// Create a new **NoDrop**.
|
||||
#[inline]
|
||||
pub fn new(value: T) -> NoDrop<T> {
|
||||
NoDrop(Flag::Alive(value))
|
||||
}
|
||||
|
||||
/// Extract the inner value.
|
||||
///
|
||||
/// Once extracted, the value can of course drop again.
|
||||
#[inline]
|
||||
pub fn into_inner(mut self) -> T {
|
||||
let inner = unsafe {
|
||||
ptr::read(&mut *self)
|
||||
};
|
||||
// skip Drop, so we don't even have to overwrite
|
||||
mem::forget(self);
|
||||
inner
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "use_needs_drop"))]
|
||||
#[inline]
|
||||
fn needs_drop<T>() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(feature = "use_needs_drop")]
|
||||
#[inline]
|
||||
fn needs_drop<T>() -> bool {
|
||||
unsafe {
|
||||
::std::intrinsics::needs_drop::<T>()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for NoDrop<T> {
|
||||
fn drop(&mut self) {
|
||||
if needs_drop::<T>() {
|
||||
// inhibit drop
|
||||
unsafe {
|
||||
ptr::write(&mut self.0, Flag::Dropped(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for NoDrop<T> {
|
||||
type Target = T;
|
||||
|
||||
// Use type invariant, always Flag::Alive.
|
||||
#[inline]
|
||||
fn deref(&self) -> &T {
|
||||
match self.0 {
|
||||
Flag::Alive(ref inner) => inner,
|
||||
_ => unsafe { debug_assert_unreachable() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for NoDrop<T> {
|
||||
// Use type invariant, always Flag::Alive.
|
||||
#[inline]
|
||||
fn deref_mut(&mut self) -> &mut T {
|
||||
match self.0 {
|
||||
Flag::Alive(ref mut inner) => inner,
|
||||
_ => unsafe { debug_assert_unreachable() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn test_no_nonnullable_opt() {
|
||||
// Make sure `Flag` does not apply the non-nullable pointer optimization
|
||||
// as Option would do.
|
||||
assert!(mem::size_of::<Flag<&i32>>() > mem::size_of::<&i32>());
|
||||
assert!(mem::size_of::<Flag<Vec<i32>>>() > mem::size_of::<Vec<i32>>());
|
||||
assert!(mem::size_of::<Option<Flag<&i32>>>() > mem::size_of::<Flag<&i32>>());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::NoDrop;
|
||||
|
||||
#[test]
|
||||
fn test_drop() {
|
||||
use std::cell::Cell;
|
||||
|
||||
let flag = &Cell::new(0);
|
||||
|
||||
struct Bump<'a>(&'a Cell<i32>);
|
||||
|
||||
impl<'a> Drop for Bump<'a> {
|
||||
fn drop(&mut self) {
|
||||
let n = self.0.get();
|
||||
self.0.set(n + 1);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let _ = NoDrop::new([Bump(flag), Bump(flag)]);
|
||||
}
|
||||
assert_eq!(flag.get(), 0);
|
||||
|
||||
// test something with the nullable pointer optimization
|
||||
flag.set(0);
|
||||
|
||||
{
|
||||
let mut array = NoDrop::new(Vec::new());
|
||||
array.push(vec![Bump(flag)]);
|
||||
array.push(vec![Bump(flag), Bump(flag)]);
|
||||
array.push(vec![]);
|
||||
array.push(vec![Bump(flag)]);
|
||||
drop(array.pop());
|
||||
assert_eq!(flag.get(), 1);
|
||||
drop(array.pop());
|
||||
assert_eq!(flag.get(), 1);
|
||||
drop(array.pop());
|
||||
assert_eq!(flag.get(), 3);
|
||||
}
|
||||
|
||||
// last one didn't drop.
|
||||
assert_eq!(flag.get(), 3);
|
||||
|
||||
flag.set(0);
|
||||
{
|
||||
let array = NoDrop::new(Bump(flag));
|
||||
array.into_inner();
|
||||
assert_eq!(flag.get(), 1);
|
||||
}
|
||||
assert_eq!(flag.get(), 1);
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".travis.yml":"d6121c742626b87ad3802535ea74cbb142ade5e1c51a497b4463988df8537091","Cargo.toml":"5a37fc8a9b180aa7d4d7cc1c8ec7ebc18c437c99007e09f5ee3d5721d9342506","README.rst":"034f294ea23f852275c718bf2e1915fa7a66a0eadbce5d89a9ec28890b95a866","benches/bench.rs":"986faa214548837b2695e5613e454e27f46612162ef78f6313f9c2a24e03b544","benches/count_ones.rs":"619b4dac77d3ecfbab5f56fe5bbce7d05d1e3bfced5d970641df96c827da85b1","benches/find.rs":"884945080ad4c6196e7831f31db70cd832520bef291a0b58d3cfe465d3515e24","src/char.rs":"3fb5a096bb27ff569a313f3ba3ea45973853757493c9f0554f53d981265de050","src/fix.rs":"88e20e7a42116044a734c6903aefdcf5a6c2c1a89e19e3c92838dbf0ca992226","src/lib.rs":"3b66ad414c002511d139c2440f21ee81151feabf8b2a4b74a425817513d4a892","src/range.rs":"d146b2376ac192d8d0ae9af3095685ae72df50094bc256ee12b6780e44305d19","src/slice/iter.rs":"b3032584401ca72b65cc5e980b03bec12592e9b0ecaa92d80ef6e8b8065692f8","src/slice/mod.rs":"c09d5706bf55d189fa7efa79b69776d30acd233d2d8efb1ec7cd412c0eed490d","src/slice/unalign.rs":"ec160e13f7776b8c020ec7f546593c68f09640febba71a9c0383e53267ba6cff","src/stride.rs":"6ca3dfbfdba0670b2f64143f490300ed2e501e1c3a47aee090a9ad5db29cc939","src/string.rs":"326716e14e5cf1b297bcf011fdd7fbb8dfb6a506a014aa4877843ef303e602e2","src/vec.rs":"9fc90c4f468bdc202ef47ca038240fa011d01633b865a0a52d7288db3782ef7d","tests/slice.rs":"596e7f3b3e5054b0db27d5d7a58dfe6532a6cf859415ecdaf21d3bcaf76043ad","tests/stride.rs":"7180644a6ab49b2724bd369af404ab5326c94990690e096508b03ae0b640e86e","tests/tests.rs":"a889080752ade5e18cd89a8146b53a660c993e55aa114865a4aecadefbbdb06f"},"package":"c3df9b730298cea3a1c3faa90b7e2f9df3a9c400d0936d6015e6165734eefcba"}
|
|
@ -0,0 +1,24 @@
|
|||
language: rust
|
||||
sudo: false
|
||||
matrix:
|
||||
include:
|
||||
- rust: 1.2.0
|
||||
env:
|
||||
- TESTFAILOK=1
|
||||
- rust: stable
|
||||
env:
|
||||
- NODEFAULT=1
|
||||
- rust: beta
|
||||
- rust: nightly
|
||||
env:
|
||||
- FEATURES='unstable'
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
script:
|
||||
- |
|
||||
cargo build --verbose --features "$FEATURES" &&
|
||||
([ "$NODEFAULT" != 1 ] || cargo build --verbose --no-default-features) &&
|
||||
(cargo test --verbose --features "$FEATURES" || [ "$TESTFAILOK" = 1 ]) &&
|
||||
(cargo test --release --verbose --features "$FEATURES" || [ "$TESTFAILOK" = 1 ]) &&
|
||||
cargo doc --verbose --features "$FEATURES"
|
|
@ -0,0 +1,28 @@
|
|||
[package]
|
||||
name = "odds"
|
||||
version = "0.2.25"
|
||||
authors = ["bluss"]
|
||||
license = "MIT/Apache-2.0"
|
||||
|
||||
description = "Odds and ends — collection miscellania. Extra functionality for slices (`.find()`, `RevSlice`), strings and other things. Debug checked variants of `get_unchecked` and `slice_unchecked`, and extra methods for strings and vectors: `repeat`, `insert_str` and `splice`. Things in odds may move to more appropriate crates if we find them."
|
||||
documentation = "https://docs.rs/odds/"
|
||||
repository = "https://github.com/bluss/odds"
|
||||
|
||||
keywords = ["data-structure", "debug-assert", "slice", "string", "no_std"]
|
||||
|
||||
[dependencies]
|
||||
|
||||
[dev-dependencies]
|
||||
itertools = "0.5.1"
|
||||
memchr = "0.1.11"
|
||||
lazy_static = "0.2.2"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
# Default
|
||||
# Use libstd
|
||||
std = []
|
||||
unstable = []
|
||||
|
||||
[profile.bench]
|
||||
debug = true
|
|
@ -0,0 +1,162 @@
|
|||
|
||||
odds
|
||||
====
|
||||
|
||||
Odds and ends — collection miscellania. Extra functionality related to slices,
|
||||
strings and other things.
|
||||
|
||||
Please read the `API documentation here`__
|
||||
|
||||
__ https://docs.rs/odds/
|
||||
|
||||
|build_status|_ |crates|_
|
||||
|
||||
.. |build_status| image:: https://travis-ci.org/bluss/odds.svg
|
||||
.. _build_status: https://travis-ci.org/bluss/odds
|
||||
|
||||
.. |crates| image:: http://meritbadge.herokuapp.com/odds
|
||||
.. _crates: https://crates.io/crates/odds
|
||||
|
||||
Recent Changes
|
||||
--------------
|
||||
|
||||
- 0.2.25
|
||||
|
||||
- Add ``UnalignedIter``
|
||||
- Add ``SliceCopyIter``
|
||||
- ``CharStr`` now implements more traits.
|
||||
|
||||
- 0.2.24
|
||||
|
||||
- Add ``CharStr``
|
||||
|
||||
- 0.2.23
|
||||
|
||||
- Add ``RevSlice``, a reversed view of a slice
|
||||
- Add ``encode_utf8`` for encoding chars
|
||||
|
||||
- 0.2.22
|
||||
|
||||
- Improve slice's ``.find()`` and ``.rfind()`` and related methods
|
||||
by explicitly unrolling their search loop.
|
||||
|
||||
- 0.2.21
|
||||
|
||||
- Add ``slice::rotate_left`` to cyclically rotate elements in a slice.
|
||||
|
||||
- 0.2.20
|
||||
|
||||
- Add ``SliceFindSplit`` with ``.find_split, .rfind_split, .find_split_mut,``
|
||||
``.rfind_split_mut``.
|
||||
- Add ``VecFindRemove`` with ``.find_remove(), .rfind_remove()``.
|
||||
|
||||
- 0.2.19
|
||||
|
||||
- Add trait ``SliceFind`` with methods ``.find(&T), .rfind(&T)`` for
|
||||
slices.
|
||||
- Add function ``vec(iterable) -> Vec``
|
||||
- Add prelude module
|
||||
|
||||
- 0.2.18
|
||||
|
||||
- Correct ``split_aligned_for<T>`` to use the trait bound.
|
||||
|
||||
- 0.2.17
|
||||
|
||||
- Add ``split_aligned_for<T>`` function that splits a byte slice into
|
||||
head and tail slices and a main slice that is a well aligned block
|
||||
of type ``&[T]``. Where ``T`` is a pod type like for example ``u64``.
|
||||
- Add ``Stride, StrideMut`` that moved here from itertools
|
||||
- Add ``mend_slices`` iterator extension that moved here from itertools
|
||||
|
||||
- 0.2.16
|
||||
|
||||
- Add ``fix`` function that makes it much easier to use the ``Fix`` combinator.
|
||||
Type inference works much better for the closure this way.
|
||||
|
||||
- 0.2.15
|
||||
|
||||
- Add ``std::slice::shared_prefix`` to efficiently compute the shared
|
||||
prefix of two byte slices
|
||||
- Add str extension methods ``.char_chunks(n)`` and ``char_windows(n)``
|
||||
that are iterators that do the char-wise equivalent of slice's chunks and windows
|
||||
iterators.
|
||||
|
||||
- 0.2.14
|
||||
|
||||
- Fix ``get_slice`` to check ``start <= end`` as well.
|
||||
|
||||
- 0.2.13
|
||||
|
||||
- Add extension trait ``StrSlice`` with method ``get_slice`` that is a slicing
|
||||
method that returns an optional slice.
|
||||
|
||||
- 0.2.12
|
||||
|
||||
- Add default feature "std". odds uses ``no_std`` if you opt out of this
|
||||
feature.
|
||||
|
||||
- 0.2.11
|
||||
|
||||
- Add type parameter to ``IndexRange`` (that defaults to ``usize``,
|
||||
so that it's non-breaking).
|
||||
- Drop dep on ``unreachable`` (provided in a simpler implementation locally).
|
||||
|
||||
- 0.2.10
|
||||
|
||||
- Fix feature flags when using cargo feature ``unstable``
|
||||
|
||||
- 0.2.9
|
||||
|
||||
- Add ``slice_unchecked_mut``
|
||||
- Add ``ref_slice``, ``ref_slice_mut``
|
||||
|
||||
- 0.2.8
|
||||
|
||||
- Add `VecExt::retain_mut`
|
||||
|
||||
- 0.2.7
|
||||
|
||||
- `inline(always)` on `debug_assert_unreachable`
|
||||
|
||||
- 0.2.6
|
||||
|
||||
- Add lifetime bounds for Fix for well-formedness (Rust RFC 1214)
|
||||
- Add `StrExt::is_acceptable_index`
|
||||
|
||||
- 0.2.5
|
||||
|
||||
- Add `StringExt::insert_str` and `VecExt::splice`
|
||||
|
||||
- 0.2.4
|
||||
|
||||
- Add `odds::string::StrExt`, extensions to `&str`.
|
||||
|
||||
- 0.2.3
|
||||
|
||||
- Add default for Fix so that ``Fix<T> == Fix<T, T>``
|
||||
|
||||
- 0.2.2
|
||||
|
||||
- Add ptr_eq, ref_eq
|
||||
|
||||
- 0.2.1
|
||||
|
||||
- Add slice_unchecked
|
||||
|
||||
- 0.2.0
|
||||
|
||||
- Removed **Void**, see ``void`` crate instead.
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
Dual-licensed to be compatible with the Rust project.
|
||||
|
||||
Licensed under the Apache License, Version 2.0
|
||||
http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
|
||||
http://opensource.org/licenses/MIT, at your
|
||||
option. This file may not be copied, modified, or distributed
|
||||
except according to those terms.
|
||||
|
||||
|
|
@ -0,0 +1,400 @@
|
|||
|
||||
#![feature(test)]
|
||||
extern crate test;
|
||||
|
||||
extern crate odds;
|
||||
extern crate memchr;
|
||||
extern crate itertools;
|
||||
|
||||
#[macro_use] extern crate lazy_static;
|
||||
|
||||
use std::mem::{size_of, size_of_val};
|
||||
use test::Bencher;
|
||||
use test::black_box;
|
||||
|
||||
use itertools::enumerate;
|
||||
|
||||
use odds::slice::shared_prefix;
|
||||
use odds::stride::Stride;
|
||||
use odds::slice::unalign::UnalignedIter;
|
||||
|
||||
#[bench]
|
||||
fn find_word_memcmp_ascii(b: &mut Bencher) {
|
||||
let words = &*WORDS_ASCII;
|
||||
let word = b"the";
|
||||
b.iter(|| {
|
||||
words.iter().map(|w|
|
||||
(w.as_bytes() == &word[..]) as usize
|
||||
).sum::<usize>()
|
||||
});
|
||||
b.bytes = words.iter().map(|w| w.len() as u64).sum::<u64>()
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn find_word_shpfx_ascii(b: &mut Bencher) {
|
||||
let words = &*WORDS_ASCII;
|
||||
let word = b"the";
|
||||
b.iter(|| {
|
||||
words.iter().map(|w|
|
||||
(shared_prefix(w.as_bytes(), &word[..]) == word.len()) as usize
|
||||
).sum::<usize>()
|
||||
});
|
||||
b.bytes = words.iter().map(|w| w.len() as u64).sum::<u64>()
|
||||
}
|
||||
|
||||
|
||||
#[bench]
|
||||
fn shpfx(bench: &mut Bencher) {
|
||||
let a = vec![0u8; 64 * 1024 * 1024];
|
||||
let mut b = vec![0u8; 64 * 1024 * 1024];
|
||||
const OFF: usize = 47 * 1024 * 1024;
|
||||
b[OFF] = 1;
|
||||
|
||||
bench.iter(|| {
|
||||
shared_prefix(&a, &b);
|
||||
});
|
||||
bench.bytes = size_of_val(&b[..OFF]) as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn shpfx_memcmp(bench: &mut Bencher) {
|
||||
let a = vec![0u8; 64 * 1024 * 1024];
|
||||
let mut b = vec![0u8; 64 * 1024 * 1024];
|
||||
const OFF: usize = 47 * 1024 * 1024;
|
||||
b[OFF] = 1;
|
||||
|
||||
bench.iter(|| {
|
||||
&a[..] == &b[..]
|
||||
});
|
||||
bench.bytes = size_of_val(&b[..OFF]) as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn shpfx_short(bench: &mut Bencher) {
|
||||
let a = vec![0; 64 * 1024];
|
||||
let mut b = vec![0; 64 * 1024];
|
||||
const OFF: usize = 47 * 1024;
|
||||
b[OFF] = 1;
|
||||
|
||||
bench.iter(|| {
|
||||
shared_prefix(&a, &b)
|
||||
});
|
||||
bench.bytes = size_of_val(&b[..OFF]) as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn shpfx_memcmp_short(bench: &mut Bencher) {
|
||||
let a = vec![0u8; 64 * 1024];
|
||||
let mut b = vec![0u8; 64 * 1024];
|
||||
const OFF: usize = 47 * 1024;
|
||||
b[OFF] = 1;
|
||||
|
||||
bench.iter(|| {
|
||||
&a[..] == &b[..]
|
||||
});
|
||||
bench.bytes = size_of_val(&b[..OFF]) as u64;
|
||||
}
|
||||
|
||||
fn bench_data() -> Vec<u8> { vec![b'z'; 10_000] }
|
||||
|
||||
#[bench]
|
||||
fn optimized_memchr(b: &mut test::Bencher) {
|
||||
let haystack = bench_data();
|
||||
let needle = b'a';
|
||||
b.iter(|| {
|
||||
memchr::memchr(needle, &haystack)
|
||||
});
|
||||
b.bytes = haystack.len() as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn odds_memchr(b: &mut Bencher) {
|
||||
let haystack = bench_data();
|
||||
let needle = b'a';
|
||||
b.iter(|| {
|
||||
memchr_mockup(needle, &haystack[1..])
|
||||
});
|
||||
b.bytes = haystack.len() as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn odds_unalign_memchr(b: &mut Bencher) {
|
||||
let haystack = bench_data();
|
||||
let needle = b'a';
|
||||
b.iter(|| {
|
||||
memchr_unalign(needle, &haystack[1..])
|
||||
});
|
||||
b.bytes = haystack.len() as u64;
|
||||
}
|
||||
|
||||
// use truncation
|
||||
const LO_USIZE: usize = !0 / 0xff;
|
||||
const HI_USIZE: usize = 0x8080808080808080 as usize;
|
||||
|
||||
/// Return `true` if `x` contains any zero byte.
|
||||
///
|
||||
/// From *Matters Computational*, J. Arndt
|
||||
///
|
||||
/// "The idea is to subtract one from each of the bytes and then look for
|
||||
/// bytes where the borrow propagated all the way to the most significant
|
||||
/// bit."
|
||||
#[inline]
|
||||
fn contains_zero_byte(x: usize) -> bool {
|
||||
x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0
|
||||
}
|
||||
|
||||
fn find<T>(pat: T, text: &[T]) -> Option<usize>
|
||||
where T: PartialEq
|
||||
{
|
||||
text.iter().position(|x| *x == pat)
|
||||
}
|
||||
|
||||
fn find_shorter_than<Shorter>(pat: u8, text: &[u8]) -> Option<usize> {
|
||||
use std::cmp::min;
|
||||
let len = min(text.len(), size_of::<Shorter>() - 1);
|
||||
let text = &text[..len];
|
||||
for i in 0..len {
|
||||
if text[i] == pat {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// quick and dumb memchr copy
|
||||
fn memchr_mockup(pat: u8, text: &[u8]) -> Option<usize> {
|
||||
type T = [usize; 2];
|
||||
let block_size = size_of::<T>();
|
||||
let (a, b, c) = odds::slice::split_aligned_for::<T>(text);
|
||||
if let r @ Some(_) = find_shorter_than::<T>(pat, a) {
|
||||
return r;
|
||||
}
|
||||
|
||||
let rep = LO_USIZE * (pat as usize);
|
||||
let mut reach = None;
|
||||
for (i, block) in enumerate(b) {
|
||||
let f1 = contains_zero_byte(rep ^ block[0]);
|
||||
let f2 = contains_zero_byte(rep ^ block[1]);
|
||||
if f1 || f2 {
|
||||
reach = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(i) = reach {
|
||||
find(pat, &text[i * block_size..]).map(|pos| pos + a.len())
|
||||
} else {
|
||||
find_shorter_than::<T>(pat, c).map(|pos| pos + text.len() - c.len())
|
||||
}
|
||||
}
|
||||
|
||||
// quick and dumb memchr copy
|
||||
#[inline(never)]
|
||||
fn memchr_unalign(pat: u8, text: &[u8]) -> Option<usize> {
|
||||
type T = [usize; 2];
|
||||
let mut iter = UnalignedIter::<T>::from_slice(text);
|
||||
let rep = LO_USIZE * (pat as usize);
|
||||
while let Some(block) = iter.peek_next() {
|
||||
let f1 = contains_zero_byte(rep ^ block[0]);
|
||||
let f2 = contains_zero_byte(rep ^ block[1]);
|
||||
if f1 || f2 {
|
||||
break;
|
||||
}
|
||||
iter.next();
|
||||
}
|
||||
{
|
||||
let tail = iter.tail();
|
||||
let block_len = text.len() - tail.len();
|
||||
for (j, byte) in tail.enumerate() {
|
||||
if byte == pat {
|
||||
return Some(block_len + j);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[bench]
|
||||
fn slice_iter_pos1(b: &mut Bencher)
|
||||
{
|
||||
let xs = black_box(vec![1; 128]);
|
||||
b.iter(|| {
|
||||
let mut s = 0;
|
||||
for elt in &xs {
|
||||
s += *elt;
|
||||
}
|
||||
s
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn stride_iter_pos1(b: &mut Bencher)
|
||||
{
|
||||
let xs = black_box(vec![1; 128]);
|
||||
b.iter(|| {
|
||||
let mut s = 0;
|
||||
for elt in Stride::from_slice(&xs, 1) {
|
||||
s += *elt;
|
||||
}
|
||||
s
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn stride_iter_rev(b: &mut Bencher)
|
||||
{
|
||||
let xs = black_box(vec![1; 128]);
|
||||
b.iter(|| {
|
||||
let mut s = 0;
|
||||
for elt in Stride::from_slice(&xs, 1).rev() {
|
||||
s += *elt;
|
||||
}
|
||||
s
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn stride_iter_neg1(b: &mut Bencher)
|
||||
{
|
||||
let xs = black_box(vec![1; 128]);
|
||||
b.iter(|| {
|
||||
let mut s = 0;
|
||||
for elt in Stride::from_slice(&xs, -1) {
|
||||
s += *elt;
|
||||
}
|
||||
s
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
//
|
||||
|
||||
|
||||
lazy_static! {
|
||||
static ref WORDS_ASCII: Vec<String> = {
|
||||
LONG.split_whitespace().map(String::from).collect()
|
||||
};
|
||||
static ref WORDS_CY: Vec<String> = {
|
||||
LONG_CY.split_whitespace().map(String::from).collect()
|
||||
};
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn memchr_words_ascii(b: &mut Bencher) {
|
||||
let words = &*WORDS_ASCII;
|
||||
let pat = b'a';
|
||||
b.iter(|| {
|
||||
words.iter().map(|w|
|
||||
memchr::memchr(pat, w.as_bytes()).unwrap_or(0)
|
||||
).sum::<usize>()
|
||||
});
|
||||
b.bytes = words.iter().map(|w| w.len() as u64).sum::<u64>()
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn memchr_odds_words_ascii(b: &mut Bencher) {
|
||||
let words = &*WORDS_ASCII;
|
||||
let pat = b'a';
|
||||
b.iter(|| {
|
||||
words.iter().map(|w|
|
||||
memchr_mockup(pat, w.as_bytes()).unwrap_or(0)
|
||||
).sum::<usize>()
|
||||
});
|
||||
b.bytes = words.iter().map(|w| w.len() as u64).sum::<u64>()
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn memchr_odds_words_cy(b: &mut Bencher) {
|
||||
let words = &*WORDS_CY;
|
||||
let pat = b'a';
|
||||
b.iter(|| {
|
||||
words.iter().map(|w|
|
||||
memchr_mockup(pat, w.as_bytes()).unwrap_or(0)
|
||||
).sum::<usize>()
|
||||
});
|
||||
b.bytes = words.iter().map(|w| w.len() as u64).sum::<u64>()
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn memchr_unalign_words_ascii(b: &mut Bencher) {
|
||||
let words = &*WORDS_ASCII;
|
||||
let pat = b'a';
|
||||
b.iter(|| {
|
||||
words.iter().map(|w|
|
||||
memchr_unalign(pat, w.as_bytes()).unwrap_or(0)
|
||||
).sum::<usize>()
|
||||
});
|
||||
b.bytes = words.iter().map(|w| w.len() as u64).sum::<u64>()
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn memchr_unalign_words_cy(b: &mut Bencher) {
|
||||
let words = &*WORDS_CY;
|
||||
let pat = b'a';
|
||||
b.iter(|| {
|
||||
words.iter().map(|w|
|
||||
memchr_unalign(pat, w.as_bytes()).unwrap_or(0)
|
||||
).sum::<usize>()
|
||||
});
|
||||
b.bytes = words.iter().map(|w| w.len() as u64).sum::<u64>()
|
||||
}
|
||||
|
||||
static LONG: &'static str = "\
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis lorem sit amet dolor \
|
||||
ultricies condimentum. Praesent iaculis purus elit, ac malesuada quam malesuada in. Duis sed orci \
|
||||
eros. Suspendisse sit amet magna mollis, mollis nunc luctus, imperdiet mi. Integer fringilla non \
|
||||
sem ut lacinia. Fusce varius tortor a risus porttitor hendrerit. Morbi mauris dui, ultricies nec \
|
||||
tempus vel, gravida nec quam.
|
||||
|
||||
In est dui, tincidunt sed tempus interdum, adipiscing laoreet ante. Etiam tempor, tellus quis \
|
||||
sagittis interdum, nulla purus mattis sem, quis auctor erat odio ac tellus. In nec nunc sit amet \
|
||||
diam volutpat molestie at sed ipsum. Vestibulum laoreet consequat vulputate. Integer accumsan \
|
||||
lorem ac dignissim placerat. Suspendisse convallis faucibus lorem. Aliquam erat volutpat. In vel \
|
||||
eleifend felis. Sed suscipit nulla lorem, sed mollis est sollicitudin et. Nam fermentum egestas \
|
||||
interdum. Curabitur ut nisi justo.
|
||||
|
||||
Sed sollicitudin ipsum tellus, ut condimentum leo eleifend nec. Cras ut velit ante. Phasellus nec \
|
||||
mollis odio. Mauris molestie erat in arcu mattis, at aliquet dolor vehicula. Quisque malesuada \
|
||||
lectus sit amet nisi pretium, a condimentum ipsum porta. Morbi at dapibus diam. Praesent egestas \
|
||||
est sed risus elementum, eu rutrum metus ultrices. Etiam fermentum consectetur magna, id rutrum \
|
||||
felis accumsan a. Aliquam ut pellentesque libero. Sed mi nulla, lobortis eu tortor id, suscipit \
|
||||
ultricies neque. Morbi iaculis sit amet risus at iaculis. Praesent eget ligula quis turpis \
|
||||
feugiat suscipit vel non arcu. Interdum et malesuada fames ac ante ipsum primis in faucibus. \
|
||||
Aliquam sit amet placerat lorem.
|
||||
|
||||
Cras a lacus vel ante posuere elementum. Nunc est leo, bibendum ut facilisis vel, bibendum at \
|
||||
mauris. Nullam adipiscing diam vel odio ornare, luctus adipiscing mi luctus. Nulla facilisi. \
|
||||
Mauris adipiscing bibendum neque, quis adipiscing lectus tempus et. Sed feugiat erat et nisl \
|
||||
lobortis pharetra. Donec vitae erat enim. Nullam sit amet felis et quam lacinia tincidunt. Aliquam \
|
||||
suscipit dapibus urna. Sed volutpat urna in magna pulvinar volutpat. Phasellus nec tellus ac diam \
|
||||
cursus accumsan.
|
||||
|
||||
Nam lectus enim, dapibus non nisi tempor, consectetur convallis massa. Maecenas eleifend dictum \
|
||||
feugiat. Etiam quis mauris vel risus luctus mattis a a nunc. Nullam orci quam, imperdiet id \
|
||||
vehicula in, porttitor ut nibh. Duis sagittis adipiscing nisl vitae congue. Donec mollis risus eu \
|
||||
leo suscipit, varius porttitor nulla porta. Pellentesque ut sem nec nisi euismod vehicula. Nulla \
|
||||
malesuada sollicitudin quam eu fermentum.";
|
||||
|
||||
static LONG_CY: &'static str = "\
|
||||
Брутэ дольорэ компрэхэнжам йн эжт, ючю коммюны дылыктуч эа, квюо льаорыыт вёвындо мэнандря экз. Ед ыюм емпыдит аккюсам, нык дйкит ютенам ад. Хаж аппэтырэ хонэзтатёз нэ. Ад мовэт путант юрбанйтаж вяш.
|
||||
|
||||
Коммодо квюальизквюэ абхоррэант нэ ыюм, праэчынт еракюндйа ылаборарэт эю мыа. Нэ квуым жюмо вольуптатибюж вяш, про ыт бонорюм вёвындо, мэя юллюм новум ку. Пропрёаы такематыш атоморюм зыд ан. Эи омнэжквюы оффекйяж компрэхэнжам жят, апыирёан конкыптам ёнкорруптэ ючю ыт.
|
||||
|
||||
Жят алёа лэгыры ед, эи мацим оффэндйт вим. Нык хёнк льаборэж йн, зыд прима тимэам ан. Векж нужквюам инимёкюж ты, ыам эа омнеж ырант рэформйданч. Эрож оффекйяж эю вэл.
|
||||
|
||||
Ад нам ножтрюд долорюм, еюж ут вэрыар эюрйпйдяч. Квюач аффэрт тинкидюнт про экз, дёкант вольуптатибюж ат зыд. Ыт зыд экшырки констятюам. Квюо квюиж юрбанйтаж ометтантур экз, хёз экз мютат граэкы рыкючабо, нэ прё пюрто элитр пэрпэтюа. Но квюандо минемум ыам.
|
||||
|
||||
Амэт лыгимуз ометтантур кюм ан. Витюпырата котёдиэквюэ нам эю, эю вокынт алёквюам льебэравичсы жят. Экз пыртенакж янтэрэсщэт инзтруктеор нам, еюж ад дйкит каючаэ, шэа витаэ конжтетуто ут. Квюач мандамюч кюм ат, но ёнкорруптэ рэформйданч ючю, незл либриз аюдирэ зыд эи. Ты эож аугюэ иреуры льюкяльиюч, мэль алььтыра докэндё омнэжквюы ат. Анёмал жямиляквюы аккоммодары ыам нэ, экз пэрчёус дэфянятйоныс квюо. Эи дуо фюгит маиорюм.
|
||||
|
||||
Эвэртё партйэндо пытынтёюм ыюм ан, шэа ку промпта квюаырэндум. Агам дикунт вим ку. Мюкиуж аюдиам тамквюам про ут, ку мыа квюод квюот эррэм, вяш ад номинави зючкёпит янжольэнж. Нык эи пожжёт путант эффякиантур. Ку еюж нощтыр контынтёонэж. Кюм йужто харюм ёужто ад, ыюм оратио квюоджё экз.
|
||||
|
||||
Чонэт факэтэ кюм ан, вэре факэр зальютатуж мэя но. Ыюм ут зальы эффикеэнди, экз про алиё конжыквуюнтюр. Квуй ыльит хабымуч ты, алёа омнэжквюы мандамюч шэа ыт, пльакырат аккюжамюз нэ мэль. Хаж нэ партым нюмквуам прёнкипыз, ат импэрдеэт форынчйбюж кончэктэтюыр шэа. Пльакырат рэформйданч эи векж, ючю дюиж фюйзчыт эи.
|
||||
|
||||
Экз квюо ажжюм аугюэ, ат нык мёнём анёмал кытэрож. Кюм выльёт эрюдитя эа. Йн порро малйж кончэктэтюыр хёз, жят кашы эрюдитя ат. Эа вяш мацим пыртенакж, но порро утамюр дяшзынтиыт кюм. Ыт мютат зючкёпит эож, нэ про еракюндйа котёдиэквюэ. Квуй лаудым плььатонэм ед, ку вим ножтрюм лаборамюз.
|
||||
|
||||
Вёжи янвыняры хаж ед, ты нолюёжжэ индоктум квуй. Квюач тебиквюэ ут жят, тальэ адхюк убяквюэ йн эож. Ыррор бландит вяш ан, ютроквюы нолюёжжэ констятюам йн ыюм, жят эи прима нобёз тхэопхражтуз. Ты дёкант дэльэнйт нолюёжжэ пэр, молыжтйаы модыратиюз интыллыгам ку мэль.
|
||||
|
||||
Ад ылаборарэт конжыквуюнтюр ентырпрытаряш прё, факэтэ лыгэндоч окюррырэт вим ад, элитр рэформйданч квуй ед. Жюмо зальы либриз мэя ты. Незл зюаз видишчы ан ыюм, но пожжэ молыжтйаы мэль. Фиэрэнт адипижкй ометтантур квюо экз. Ут мольлиз пырикюлёз квуй. Ыт квюиж граэко рыпудяары жят, вим магна обльйквюэ контынтёонэж эю, ты шэа эним компльыктётюр.
|
||||
";
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
#![feature(test)]
|
||||
extern crate test;
|
||||
|
||||
use std::mem::{size_of, size_of_val};
|
||||
use test::Bencher;
|
||||
|
||||
extern crate odds;
|
||||
use odds::slice::split_aligned_for;
|
||||
use odds::slice::unalign::UnalignedIter;
|
||||
|
||||
fn count_ones(data: &[u8]) -> u32 {
|
||||
let mut total = 0;
|
||||
let (head, mid, tail) = split_aligned_for::<[u64; 2]>(data);
|
||||
total += head.iter().map(|x| x.count_ones()).sum();
|
||||
total += mid.iter().map(|x| x[0].count_ones() + x[1].count_ones()).sum();
|
||||
total += tail.iter().map(|x| x.count_ones()).sum();
|
||||
total
|
||||
}
|
||||
|
||||
fn unalign_count_ones(data: &[u8]) -> u32 {
|
||||
let mut total = 0;
|
||||
let mut iter = UnalignedIter::<u64>::from_slice(data);
|
||||
total += (&mut iter).map(|x| x.count_ones()).sum();
|
||||
total += iter.tail().map(|x| x.count_ones()).sum();
|
||||
total
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn split_count_ones(b: &mut Bencher) {
|
||||
let v = vec![3u8; 127];
|
||||
b.iter(|| {
|
||||
count_ones(&v)
|
||||
});
|
||||
b.bytes = size_of_val(&v[..]) as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_unalign_count_ones(b: &mut Bencher) {
|
||||
let v = vec![3u8; 127];
|
||||
b.iter(|| {
|
||||
unalign_count_ones(&v)
|
||||
});
|
||||
b.bytes = size_of_val(&v[..]) as u64;
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
|
||||
#![feature(test)]
|
||||
extern crate test;
|
||||
|
||||
extern crate odds;
|
||||
extern crate itertools;
|
||||
|
||||
use itertools::{cloned};
|
||||
|
||||
use std::mem::size_of_val;
|
||||
|
||||
use odds::slice::SliceFindSplit;
|
||||
|
||||
use test::Bencher;
|
||||
//use test::black_box;
|
||||
|
||||
#[bench]
|
||||
fn find_split(bench: &mut Bencher) {
|
||||
let mut b = vec![0; 64 * 1024];
|
||||
const OFF: usize = 32 * 1024;
|
||||
b[OFF] = 1;
|
||||
|
||||
bench.iter(|| {
|
||||
b.find_split(&1)
|
||||
});
|
||||
bench.bytes = OFF as u64 * size_of_val(&b[0]) as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn find_split_short_i32(bench: &mut Bencher) {
|
||||
let mut b = vec![0; 64 ];
|
||||
const OFF: usize = 32 ;
|
||||
b[OFF] = 1;
|
||||
|
||||
bench.iter(|| {
|
||||
b.find_split(&1)
|
||||
});
|
||||
bench.bytes = OFF as u64 * size_of_val(&b[0]) as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn find_split_short_u8(bench: &mut Bencher) {
|
||||
let mut b = vec![0u8; 128 ];
|
||||
const OFF: usize = 64;
|
||||
b[OFF] = 1;
|
||||
|
||||
bench.iter(|| {
|
||||
b.find_split(&1)
|
||||
});
|
||||
bench.bytes = OFF as u64 * size_of_val(&b[0]) as u64;
|
||||
}
|
||||
const FIND_SKIP: &'static [usize] = &[3, 9, 4, 16, 3, 2, 1];
|
||||
|
||||
// The loop bench wants to test a find/scan loop where there are many
|
||||
// short intervals
|
||||
#[bench]
|
||||
fn find_split_loop_u8(bench: &mut Bencher) {
|
||||
let mut b = vec![0u8; 512];
|
||||
|
||||
for i in cloned(FIND_SKIP).cycle().scan(0, |st, x| { *st += x; Some(*st) }) {
|
||||
if i >= b.len() { break; }
|
||||
b[i] = 1;
|
||||
}
|
||||
|
||||
bench.iter(|| {
|
||||
let mut nfind = 0;
|
||||
let mut slc = &b[..];
|
||||
loop {
|
||||
let (_, tail) = slc.find_split(&1);
|
||||
if tail.len() == 0 {
|
||||
break;
|
||||
}
|
||||
nfind += 1;
|
||||
slc = &tail[1..];
|
||||
}
|
||||
nfind
|
||||
});
|
||||
bench.bytes = size_of_val(&b[..]) as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn rfind_split(bench: &mut Bencher) {
|
||||
let mut b = vec![0; 64 * 1024];
|
||||
const OFF: usize = 32 * 1024;
|
||||
b[OFF] = 1;
|
||||
|
||||
bench.iter(|| {
|
||||
b.rfind_split(&1)
|
||||
});
|
||||
bench.bytes = OFF as u64 * size_of_val(&b[0]) as u64;
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn rfind_split_loop_u8(bench: &mut Bencher) {
|
||||
let mut b = vec![0u8; 512];
|
||||
|
||||
for i in cloned(FIND_SKIP).cycle().scan(0, |st, x| { *st += x; Some(*st) }) {
|
||||
if i >= b.len() { break; }
|
||||
b[i] = 1;
|
||||
}
|
||||
|
||||
bench.iter(|| {
|
||||
let mut nfind = 0;
|
||||
let mut slc = &b[..];
|
||||
loop {
|
||||
let (head, _) = slc.rfind_split(&1);
|
||||
if head.len() == 0 {
|
||||
break;
|
||||
}
|
||||
nfind += 1;
|
||||
slc = &head[..head.len() - 1];
|
||||
}
|
||||
nfind
|
||||
});
|
||||
bench.bytes = size_of_val(&b[..]) as u64;
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution and at
|
||||
// http://rust-lang.org/COPYRIGHT.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
//
|
||||
// Original authors: alexchrichton
|
||||
|
||||
//! Extra functions for `char`
|
||||
|
||||
// UTF-8 ranges and tags for encoding characters
|
||||
const TAG_CONT: u8 = 0b1000_0000;
|
||||
const TAG_TWO_B: u8 = 0b1100_0000;
|
||||
const TAG_THREE_B: u8 = 0b1110_0000;
|
||||
const TAG_FOUR_B: u8 = 0b1111_0000;
|
||||
const MAX_ONE_B: u32 = 0x80;
|
||||
const MAX_TWO_B: u32 = 0x800;
|
||||
const MAX_THREE_B: u32 = 0x10000;
|
||||
|
||||
/// Placeholder
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct EncodeUtf8Error(());
|
||||
|
||||
/// Encode a char into buf using UTF-8.
|
||||
///
|
||||
/// On success, return the byte length of the encoding (1, 2, 3 or 4).<br>
|
||||
/// On error, return `EncodeUtf8Error` if the buffer was too short for the char.
|
||||
#[inline]
|
||||
pub fn encode_utf8(ch: char, buf: &mut [u8]) -> Result<usize, EncodeUtf8Error>
|
||||
{
|
||||
let code = ch as u32;
|
||||
if code < MAX_ONE_B && buf.len() >= 1 {
|
||||
buf[0] = code as u8;
|
||||
return Ok(1);
|
||||
} else if code < MAX_TWO_B && buf.len() >= 2 {
|
||||
buf[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
|
||||
buf[1] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
return Ok(2);
|
||||
} else if code < MAX_THREE_B && buf.len() >= 3 {
|
||||
buf[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
|
||||
buf[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
return Ok(3);
|
||||
} else if buf.len() >= 4 {
|
||||
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
|
||||
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
return Ok(4);
|
||||
};
|
||||
Err(EncodeUtf8Error(()))
|
||||
}
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
|
||||
/// Fixpoint combinator for rust closures, generalized over the return type.
|
||||
///
|
||||
/// In **Fix\<T, R\>**, **T** is the argument type, and **R** is the return type,
|
||||
/// **R** defaults to **T**.
|
||||
///
|
||||
/// Calling the `Fix` value only supports function call notation with the nightly
|
||||
/// channel and the crate feature ‘unstable’ enabled; use the .call() method otherwise.
|
||||
///
|
||||
/// Use this best through the `fix` function.
|
||||
///
|
||||
/// ```
|
||||
/// use odds::Fix;
|
||||
/// use odds::fix;
|
||||
///
|
||||
/// let c = |f: Fix<i32>, x| if x == 0 { 1 } else { x * f.call(x - 1) };
|
||||
/// let fact = Fix(&c);
|
||||
/// assert_eq!(fact.call(5), 120);
|
||||
///
|
||||
/// let data = [true, false];
|
||||
/// assert!(!fix(&data[..], |f, x| {
|
||||
/// x.len() == 0 || x[0] && f.call(&x[1..])
|
||||
/// }));
|
||||
///
|
||||
/// ```
|
||||
#[cfg_attr(feature="unstable", doc="
|
||||
```
|
||||
// using feature `unstable`
|
||||
use odds::Fix;
|
||||
|
||||
let c = |f: Fix<i32>, x| if x == 0 { 1 } else { x * f(x - 1) };
|
||||
let fact = Fix(&c);
|
||||
assert_eq!(fact(5), 120);
|
||||
```
|
||||
"
|
||||
)]
|
||||
pub struct Fix<'a, T: 'a, R: 'a = T>(pub &'a Fn(Fix<T, R>, T) -> R);
|
||||
|
||||
/// Fixpoint combinator for rust closures, generalized over the return type.
|
||||
///
|
||||
/// This is a wrapper function that uses the `Fix` type. The recursive closure
|
||||
/// has two arguments, `Fix` and the argument type `T`.
|
||||
///
|
||||
/// In **Fix\<T, R\>**, **T** is the argument type, and **R** is the return type,
|
||||
/// **R** defaults to **T**.
|
||||
///
|
||||
/// Calling the `Fix` value only supports function call notation with the nightly
|
||||
/// channel and the crate feature ‘unstable’ enabled; use the .call() method otherwise.
|
||||
///
|
||||
/// This helper function makes the type inference work out well.
|
||||
///
|
||||
/// ```
|
||||
/// use odds::fix;
|
||||
///
|
||||
/// assert_eq!(120, fix(5, |f, x| if x == 0 { 1 } else { x * f.call(x - 1) }));
|
||||
///
|
||||
/// let data = [true, false];
|
||||
/// assert!(!fix(&data[..], |f, x| {
|
||||
/// x.len() == 0 || x[0] && f.call(&x[1..])
|
||||
/// }));
|
||||
///
|
||||
/// ```
|
||||
#[cfg_attr(feature="unstable", doc="
|
||||
```
|
||||
// using feature `unstable`
|
||||
use odds::fix;
|
||||
|
||||
assert_eq!(120, fix(5, |f, x| if x == 0 { 1 } else { x * f(x - 1) }));
|
||||
```
|
||||
"
|
||||
)]
|
||||
pub fn fix<T, R, F>(init: T, closure: F) -> R
|
||||
where F: Fn(Fix<T, R>, T) -> R
|
||||
{
|
||||
Fix(&closure).call(init)
|
||||
}
|
||||
|
||||
impl<'a, T, R> Fix<'a, T, R> {
|
||||
pub fn call(&self, arg: T) -> R {
|
||||
let f = *self;
|
||||
f.0(f, arg)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, R> Clone for Fix<'a, T, R> {
|
||||
fn clone(&self) -> Self { *self }
|
||||
}
|
||||
|
||||
impl<'a, T, R> Copy for Fix<'a, T, R> { }
|
||||
|
||||
#[cfg(feature="unstable")]
|
||||
impl<'a, T, R> FnOnce<(T,)> for Fix<'a, T, R> {
|
||||
type Output = R;
|
||||
#[inline]
|
||||
extern "rust-call" fn call_once(self, x: (T,)) -> R {
|
||||
self.call(x.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature="unstable")]
|
||||
impl<'a, T, R> FnMut<(T,)> for Fix<'a, T, R> {
|
||||
#[inline]
|
||||
extern "rust-call" fn call_mut(&mut self, x: (T,)) -> R {
|
||||
self.call(x.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature="unstable")]
|
||||
impl<'a, T, R> Fn<(T,)> for Fix<'a, T, R> {
|
||||
#[inline]
|
||||
extern "rust-call" fn call(&self, x: (T,)) -> R {
|
||||
self.call(x.0)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,197 @@
|
|||
//! Odds and ends — collection miscellania.
|
||||
//!
|
||||
//! - Utilities for debug-checked, release-unchecked indexing and slicing
|
||||
//! - Fixpoint combinator for closures
|
||||
//! - String and Vec extensions
|
||||
//!
|
||||
//! The **odds** crate has the following crate feature flags:
|
||||
//!
|
||||
//! - `std`
|
||||
//! - Default
|
||||
//! - Requires Rust 1.6 *to opt out of*
|
||||
//! - Use libstd and std features.
|
||||
//! - `unstable`.
|
||||
//! - Optional.
|
||||
//! - Requires nightly channel.
|
||||
//! - Implement the closure traits for **Fix**.
|
||||
//!
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/odds/0.2/")]
|
||||
#![cfg_attr(feature="unstable", feature(unboxed_closures, fn_traits))]
|
||||
|
||||
#![cfg_attr(not(feature="std"), no_std)]
|
||||
|
||||
#[cfg(not(feature="std"))]
|
||||
extern crate core as std;
|
||||
|
||||
mod range;
|
||||
#[path = "fix.rs"]
|
||||
mod fix_impl;
|
||||
pub mod char;
|
||||
pub mod string;
|
||||
pub mod vec;
|
||||
pub mod slice;
|
||||
pub mod stride;
|
||||
|
||||
pub use fix_impl::Fix;
|
||||
pub use fix_impl::fix;
|
||||
pub use range::IndexRange;
|
||||
|
||||
use std::mem;
|
||||
|
||||
/// prelude of often used traits and functions
|
||||
pub mod prelude {
|
||||
pub use slice::SliceFind;
|
||||
pub use slice::SliceIterExt;
|
||||
pub use string::StrExt;
|
||||
#[cfg(feature="std")]
|
||||
pub use string::StrChunksWindows;
|
||||
#[cfg(feature="std")]
|
||||
pub use string::StringExt;
|
||||
#[cfg(feature="std")]
|
||||
pub use vec::{vec, VecExt};
|
||||
#[doc(no_inline)]
|
||||
pub use IndexRange;
|
||||
#[doc(no_inline)]
|
||||
pub use fix;
|
||||
}
|
||||
|
||||
/// Compare if **a** and **b** are equal *as pointers*.
|
||||
#[inline]
|
||||
pub fn ref_eq<T>(a: &T, b: &T) -> bool {
|
||||
ptr_eq(a, b)
|
||||
}
|
||||
|
||||
/// Compare if **a** and **b** are equal pointers.
|
||||
#[inline]
|
||||
pub fn ptr_eq<T>(a: *const T, b: *const T) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// Safe to use with any wholly initialized memory `ptr`
|
||||
#[inline]
|
||||
pub unsafe fn raw_byte_repr<T: ?Sized>(ptr: &T) -> &[u8] {
|
||||
std::slice::from_raw_parts(
|
||||
ptr as *const _ as *const u8,
|
||||
mem::size_of_val(ptr),
|
||||
)
|
||||
}
|
||||
|
||||
/// Use `debug_assert!` to check indexing in debug mode. In release mode, no checks are done.
|
||||
#[inline]
|
||||
pub unsafe fn get_unchecked<T>(data: &[T], index: usize) -> &T {
|
||||
debug_assert!(index < data.len());
|
||||
data.get_unchecked(index)
|
||||
}
|
||||
|
||||
/// Use `debug_assert!` to check indexing in debug mode. In release mode, no checks are done.
|
||||
#[inline]
|
||||
pub unsafe fn get_unchecked_mut<T>(data: &mut [T], index: usize) -> &mut T {
|
||||
debug_assert!(index < data.len());
|
||||
data.get_unchecked_mut(index)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
unsafe fn unreachable() -> ! {
|
||||
enum Void { }
|
||||
match *(1 as *const Void) {
|
||||
/* unreachable */
|
||||
}
|
||||
}
|
||||
|
||||
/// Act as `debug_assert!` in debug mode, asserting that this point is not reached.
|
||||
///
|
||||
/// In release mode, no checks are done, and it acts like the `unreachable` intrinsic.
|
||||
#[inline(always)]
|
||||
pub unsafe fn debug_assert_unreachable() -> ! {
|
||||
debug_assert!(false, "Entered unreachable section, this is a bug!");
|
||||
unreachable()
|
||||
}
|
||||
|
||||
/// Check slicing bounds in debug mode, otherwise just act as an unchecked
|
||||
/// slice call.
|
||||
#[inline]
|
||||
pub unsafe fn slice_unchecked<T>(data: &[T], from: usize, to: usize) -> &[T] {
|
||||
debug_assert!((&data[from..to], true).1);
|
||||
std::slice::from_raw_parts(data.as_ptr().offset(from as isize), to - from)
|
||||
}
|
||||
|
||||
/// Check slicing bounds in debug mode, otherwise just act as an unchecked
|
||||
/// slice call.
|
||||
#[inline]
|
||||
pub unsafe fn slice_unchecked_mut<T>(data: &mut [T], from: usize, to: usize) -> &mut [T] {
|
||||
debug_assert!((&data[from..to], true).1);
|
||||
std::slice::from_raw_parts_mut(data.as_mut_ptr().offset(from as isize), to - from)
|
||||
}
|
||||
|
||||
/// Create a length 1 slice out of a reference
|
||||
pub fn ref_slice<T>(ptr: &T) -> &[T] {
|
||||
unsafe {
|
||||
std::slice::from_raw_parts(ptr, 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a length 1 mutable slice out of a reference
|
||||
pub fn ref_slice_mut<T>(ptr: &mut T) -> &mut [T] {
|
||||
unsafe {
|
||||
std::slice::from_raw_parts_mut(ptr, 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_repr() {
|
||||
unsafe {
|
||||
assert_eq!(raw_byte_repr(&17u8), &[17]);
|
||||
assert_eq!(raw_byte_repr("abc"), "abc".as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_get_unchecked_1() {
|
||||
if cfg!(not(debug_assertions)) {
|
||||
panic!();
|
||||
}
|
||||
unsafe {
|
||||
get_unchecked(&[1, 2, 3], 3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_slice_unchecked_1() {
|
||||
// These tests only work in debug mode
|
||||
if cfg!(not(debug_assertions)) {
|
||||
panic!();
|
||||
}
|
||||
unsafe {
|
||||
slice_unchecked(&[1, 2, 3], 0, 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_slice_unchecked_2() {
|
||||
if cfg!(not(debug_assertions)) {
|
||||
panic!();
|
||||
}
|
||||
unsafe {
|
||||
slice_unchecked(&[1, 2, 3], 4, 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slice_unchecked_3() {
|
||||
// This test only works in release mode
|
||||
// test some benign unchecked slicing
|
||||
let data = [1, 2, 3, 4];
|
||||
let sl = &data[0..0];
|
||||
if cfg!(debug_assertions) {
|
||||
/* silent */
|
||||
} else {
|
||||
unsafe {
|
||||
assert_eq!(slice_unchecked(sl, 0, 4), &[1, 2, 3, 4]);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
|
||||
use std::ops::{
|
||||
RangeFull,
|
||||
RangeFrom,
|
||||
RangeTo,
|
||||
Range,
|
||||
};
|
||||
|
||||
/// **IndexRange** is implemented by Rust's built-in range types, produced
|
||||
/// by range syntax like `..`, `a..`, `..b` or `c..d`.
|
||||
pub trait IndexRange<T=usize> {
|
||||
#[inline]
|
||||
/// Start index (inclusive)
|
||||
fn start(&self) -> Option<T> { None }
|
||||
#[inline]
|
||||
/// End index (exclusive)
|
||||
fn end(&self) -> Option<T> { None }
|
||||
}
|
||||
|
||||
|
||||
impl<T> IndexRange<T> for RangeFull {}
|
||||
|
||||
impl<T: Copy> IndexRange<T> for RangeFrom<T> {
|
||||
#[inline]
|
||||
fn start(&self) -> Option<T> { Some(self.start) }
|
||||
}
|
||||
|
||||
impl<T: Copy> IndexRange<T> for RangeTo<T> {
|
||||
#[inline]
|
||||
fn end(&self) -> Option<T> { Some(self.end) }
|
||||
}
|
||||
|
||||
impl<T: Copy> IndexRange<T> for Range<T> {
|
||||
#[inline]
|
||||
fn start(&self) -> Option<T> { Some(self.start) }
|
||||
#[inline]
|
||||
fn end(&self) -> Option<T> { Some(self.end) }
|
||||
}
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
|
||||
use std::mem::size_of;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
/// Slice (contiguous data) iterator.
|
||||
///
|
||||
/// Iterator element type is `T` (by value).
|
||||
/// This iterator exists mainly to have the constructor from a pair
|
||||
/// of raw pointers available, which the libcore slice iterator does not allow.
|
||||
///
|
||||
/// Implementation note: Aliasing/optimization issues disappear if we use
|
||||
/// non-pointer iterator element type, so we use `T`. (The libcore slice
|
||||
/// iterator has `assume` and other tools available to combat it).
|
||||
///
|
||||
/// `T` must not be a zero sized type.
|
||||
#[derive(Debug)]
|
||||
pub struct SliceCopyIter<'a, T: 'a> {
|
||||
ptr: *const T,
|
||||
end: *const T,
|
||||
ty: PhantomData<&'a T>,
|
||||
}
|
||||
|
||||
impl<'a, T> Copy for SliceCopyIter<'a, T> { }
|
||||
impl<'a, T> Clone for SliceCopyIter<'a, T> {
|
||||
fn clone(&self) -> Self { *self }
|
||||
}
|
||||
|
||||
impl<'a, T> SliceCopyIter<'a, T>
|
||||
where T: Copy
|
||||
{
|
||||
#[inline]
|
||||
pub unsafe fn new(ptr: *const T, end: *const T) -> Self {
|
||||
assert!(size_of::<T>() != 0);
|
||||
SliceCopyIter {
|
||||
ptr: ptr,
|
||||
end: end,
|
||||
ty: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the start, end pointer of the iterator
|
||||
pub fn into_raw(self) -> (*const T, *const T) {
|
||||
(self.ptr, self.end)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Iterator for SliceCopyIter<'a, T>
|
||||
where T: Copy,
|
||||
{
|
||||
type Item = T;
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.ptr != self.end {
|
||||
unsafe {
|
||||
let elt = Some(*self.ptr);
|
||||
self.ptr = self.ptr.offset(1);
|
||||
elt
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = (self.end as usize - self.ptr as usize) / size_of::<T>();
|
||||
(len, Some(len))
|
||||
}
|
||||
|
||||
fn count(self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn last(mut self) -> Option<Self::Item> {
|
||||
self.next_back()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> DoubleEndedIterator for SliceCopyIter<'a, T>
|
||||
where T: Copy
|
||||
{
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<Self::Item> {
|
||||
if self.ptr != self.end {
|
||||
unsafe {
|
||||
self.end = self.end.offset(-1);
|
||||
let elt = Some(*self.end);
|
||||
elt
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> ExactSizeIterator for SliceCopyIter<'a, T> where T: Copy { }
|
||||
|
||||
impl<'a, T> From<&'a [T]> for SliceCopyIter<'a, T>
|
||||
where T: Copy
|
||||
{
|
||||
fn from(slice: &'a [T]) -> Self {
|
||||
assert!(size_of::<T>() != 0);
|
||||
unsafe {
|
||||
let ptr = slice.as_ptr();
|
||||
let end = ptr.offset(slice.len() as isize);
|
||||
SliceCopyIter::new(ptr, end)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Default for SliceCopyIter<'a, T>
|
||||
where T: Copy
|
||||
{
|
||||
/// Create an empty `SliceCopyIter`.
|
||||
fn default() -> Self {
|
||||
unsafe {
|
||||
SliceCopyIter::new(0x1 as *const T, 0x1 as *const T)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,985 @@
|
|||
//! Extra functions for slices
|
||||
|
||||
pub mod unalign;
|
||||
pub mod iter;
|
||||
|
||||
use {get_unchecked, get_unchecked_mut};
|
||||
use IndexRange;
|
||||
use {slice_unchecked, slice_unchecked_mut};
|
||||
|
||||
use std::ptr;
|
||||
use std::cmp::min;
|
||||
use std::mem::transmute;
|
||||
use std::mem::{self, align_of, size_of};
|
||||
use std::hash::{Hasher, Hash};
|
||||
use std::slice::from_raw_parts;
|
||||
use std::iter::Rev;
|
||||
use std::slice::{Iter, IterMut};
|
||||
|
||||
use std::ops::{Index, IndexMut};
|
||||
|
||||
/// Unaligned load of a u64 at index `i` in `buf`
|
||||
unsafe fn load_u64(buf: &[u8], i: usize) -> u64 {
|
||||
debug_assert!(i + 8 <= buf.len());
|
||||
let mut data = 0u64;
|
||||
ptr::copy_nonoverlapping(buf.get_unchecked(i), &mut data as *mut _ as *mut u8, 8);
|
||||
data
|
||||
}
|
||||
|
||||
/// Return the end index of the longest shared (equal) prefix of `a` and `b`.
|
||||
pub fn shared_prefix(a: &[u8], b: &[u8]) -> usize {
|
||||
let len = min(a.len(), b.len());
|
||||
let mut a = &a[..len];
|
||||
let mut b = &b[..len];
|
||||
let mut offset = 0;
|
||||
while a.len() >= 16 {
|
||||
unsafe {
|
||||
let a0 = load_u64(a, 0);
|
||||
let a1 = load_u64(a, 8);
|
||||
let b0 = load_u64(b, 0);
|
||||
let b1 = load_u64(b, 8);
|
||||
let d0 = a0 ^ b0;
|
||||
let d1 = a1 ^ b1;
|
||||
if d0 ^ d1 != 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
offset += 16;
|
||||
a = &a[16..];
|
||||
b = &b[16..];
|
||||
}
|
||||
for i in 0..a.len() {
|
||||
if a[i] != b[i] {
|
||||
return offset + i;
|
||||
}
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
/// Rotate `steps` towards lower indices.
|
||||
///
|
||||
/// The steps to rotate is computed modulo the length of `data`,
|
||||
/// so any step value is acceptable. This function does not panic.
|
||||
///
|
||||
/// ```
|
||||
/// use odds::slice::rotate_left;
|
||||
///
|
||||
/// let mut data = [1, 2, 3, 4];
|
||||
/// rotate_left(&mut data, 1);
|
||||
/// assert_eq!(&data, &[2, 3, 4, 1]);
|
||||
/// rotate_left(&mut data, 2);
|
||||
/// assert_eq!(&data, &[4, 1, 2, 3]);
|
||||
/// ```
|
||||
pub fn rotate_left<T>(data: &mut [T], steps: usize) {
|
||||
//return rotate_alt(data, steps);
|
||||
// no bounds checks in this method in this version
|
||||
if data.len() == 0 {
|
||||
return;
|
||||
}
|
||||
let steps = steps % data.len();
|
||||
|
||||
data[..steps].reverse();
|
||||
data[steps..].reverse();
|
||||
data.reverse();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn correct() {
|
||||
let mut a = [0xff; 1024];
|
||||
let b = [0xff; 1024];
|
||||
for byte in 0..255 { // don't test byte 255
|
||||
for i in 0..a.len() {
|
||||
a[i] = byte;
|
||||
let ans = shared_prefix(&a, &b);
|
||||
assert!(ans == i, "failed for index {} and byte {:x} (got ans={})",
|
||||
i, byte, ans);
|
||||
a[i] = 0xff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Element-finding methods for slices
|
||||
pub trait SliceFind {
|
||||
type Item;
|
||||
/// Linear search for the first occurrence `elt` in the slice.
|
||||
///
|
||||
/// Return its index if it is found, or None.
|
||||
fn find<U: ?Sized>(&self, elt: &U) -> Option<usize>
|
||||
where Self::Item: PartialEq<U>;
|
||||
|
||||
/// Linear search for the last occurrence `elt` in the slice.
|
||||
///
|
||||
/// Return its index if it is found, or None.
|
||||
fn rfind<U: ?Sized>(&self, elt: &U) -> Option<usize>
|
||||
where Self::Item: PartialEq<U>;
|
||||
}
|
||||
|
||||
macro_rules! foreach {
|
||||
($i:pat in $($e:expr),* => $b:expr) => {{
|
||||
$(
|
||||
let $i = $e;
|
||||
$b;
|
||||
)*
|
||||
}}
|
||||
}
|
||||
|
||||
impl<T> SliceFind for [T] {
|
||||
type Item = T;
|
||||
fn find<U: ?Sized>(&self, elt: &U) -> Option<usize>
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
let mut xs = self;
|
||||
let mut i = 0;
|
||||
const C: usize = 8;
|
||||
while xs.len() >= C {
|
||||
foreach!(j in 0, 1, 2, 3, 4, 5, 6, 7 => {
|
||||
if xs[j] == *elt { return Some(i + j); }
|
||||
});
|
||||
i += C;
|
||||
xs = &xs[C..];
|
||||
}
|
||||
for j in 0..xs.len() {
|
||||
if xs[j] == *elt {
|
||||
return Some(i + j);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn rfind<U: ?Sized>(&self, elt: &U) -> Option<usize>
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
let mut xs = self;
|
||||
const C: usize = 8;
|
||||
while xs.len() >= C {
|
||||
let l = xs.len();
|
||||
foreach!(j in 0, 1, 2, 3, 4, 5, 6, 7 => {
|
||||
if xs[l - 1 - j] == *elt { return Some(l - 1 - j); }
|
||||
});
|
||||
xs = &xs[..l - C];
|
||||
}
|
||||
xs.iter().rposition(|x| *x == *elt)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> SliceFind for RevSlice<T> {
|
||||
type Item = T;
|
||||
fn find<U: ?Sized>(&self, elt: &U) -> Option<usize>
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
self.0.rfind(elt).map(move |i| self.raw_index_no_wrap(i))
|
||||
}
|
||||
|
||||
fn rfind<U: ?Sized>(&self, elt: &U) -> Option<usize>
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
self.0.find(elt).map(move |i| self.raw_index_no_wrap(i))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Element-finding methods for slices
|
||||
pub trait SliceFindSplit {
|
||||
type Item;
|
||||
/// Linear search for the first occurrence `elt` in the slice.
|
||||
///
|
||||
/// Return the part before and the part including and after the element.
|
||||
/// If the element is not found, the second half is empty.
|
||||
fn find_split<U: ?Sized>(&self, elt: &U) -> (&Self, &Self)
|
||||
where Self::Item: PartialEq<U>;
|
||||
|
||||
/// Linear search for the last occurrence `elt` in the slice.
|
||||
///
|
||||
/// Return the part before and the part including and after the element.
|
||||
/// If the element is not found, the first half is empty.
|
||||
fn rfind_split<U: ?Sized>(&self, elt: &U) -> (&Self, &Self)
|
||||
where Self::Item: PartialEq<U>;
|
||||
|
||||
/// Linear search for the first occurrence `elt` in the slice.
|
||||
///
|
||||
/// Return the part before and the part including and after the element.
|
||||
/// If the element is not found, the second half is empty.
|
||||
fn find_split_mut<U: ?Sized>(&mut self, elt: &U) -> (&mut Self, &mut Self)
|
||||
where Self::Item: PartialEq<U>;
|
||||
|
||||
/// Linear search for the last occurrence `elt` in the slice.
|
||||
///
|
||||
/// Return the part before and the part including and after the element.
|
||||
/// If the element is not found, the first half is empty.
|
||||
fn rfind_split_mut<U: ?Sized>(&mut self, elt: &U) -> (&mut Self, &mut Self)
|
||||
where Self::Item: PartialEq<U>;
|
||||
}
|
||||
|
||||
|
||||
/// Unchecked version of `xs.split_at(i)`.
|
||||
unsafe fn split_at_unchecked<T>(xs: &[T], i: usize) -> (&[T], &[T]) {
|
||||
(slice_unchecked(xs, 0, i),
|
||||
slice_unchecked(xs, i, xs.len()))
|
||||
}
|
||||
|
||||
impl<T> SliceFindSplit for [T] {
|
||||
type Item = T;
|
||||
fn find_split<U: ?Sized>(&self, elt: &U) -> (&Self, &Self)
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
let i = self.find(elt).unwrap_or(self.len());
|
||||
unsafe {
|
||||
split_at_unchecked(self, i)
|
||||
}
|
||||
}
|
||||
|
||||
fn find_split_mut<U: ?Sized>(&mut self, elt: &U) -> (&mut Self, &mut Self)
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
let i = self.find(elt).unwrap_or(self.len());
|
||||
self.split_at_mut(i)
|
||||
}
|
||||
|
||||
fn rfind_split<U: ?Sized>(&self, elt: &U) -> (&Self, &Self)
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
let i = self.rfind(elt).unwrap_or(0);
|
||||
unsafe {
|
||||
split_at_unchecked(self, i)
|
||||
}
|
||||
}
|
||||
|
||||
fn rfind_split_mut<U: ?Sized>(&mut self, elt: &U) -> (&mut Self, &mut Self)
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
let i = self.rfind(elt).unwrap_or(0);
|
||||
self.split_at_mut(i)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Extra iterator adaptors for iterators of slice elements.
|
||||
pub trait SliceIterExt : Iterator {
|
||||
/// Return an iterator adaptor that joins together adjacent slices if possible.
|
||||
///
|
||||
/// Only implemented for iterators with slice or string slice elements.
|
||||
/// Only slices that are contiguous together can be joined.
|
||||
///
|
||||
/// ```
|
||||
/// use odds::slice::SliceIterExt;
|
||||
///
|
||||
/// // Split a string into a slice per letter, filter out whitespace,
|
||||
/// // and join into words again by mending adjacent slices.
|
||||
/// let text = String::from("Warning: γ-radiation (ionizing)");
|
||||
/// let char_slices = text.char_indices()
|
||||
/// .map(|(index, ch)| &text[index..index + ch.len_utf8()]);
|
||||
/// let words = char_slices.filter(|s| !s.chars().any(char::is_whitespace))
|
||||
/// .mend_slices();
|
||||
///
|
||||
/// assert!(words.eq(vec!["Warning:", "γ-radiation", "(ionizing)"]));
|
||||
/// ```
|
||||
fn mend_slices(self) -> MendSlices<Self>
|
||||
where Self: Sized,
|
||||
Self::Item: MendSlice
|
||||
{
|
||||
MendSlices::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: ?Sized> SliceIterExt for I where I: Iterator { }
|
||||
|
||||
/// An iterator adaptor that glues together adjacent contiguous slices.
|
||||
///
|
||||
/// See [`.mend_slices()`](../trait.Itertools.html#method.mend_slices) for more information.
|
||||
pub struct MendSlices<I>
|
||||
where I: Iterator
|
||||
{
|
||||
last: Option<I::Item>,
|
||||
iter: I,
|
||||
}
|
||||
|
||||
impl<I: Clone> Clone for MendSlices<I>
|
||||
where I: Iterator,
|
||||
I::Item: Clone
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
MendSlices {
|
||||
last: self.last.clone(),
|
||||
iter: self.iter.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> MendSlices<I>
|
||||
where I: Iterator
|
||||
{
|
||||
/// Create a new `MendSlices`.
|
||||
pub fn new(mut iter: I) -> Self {
|
||||
MendSlices {
|
||||
last: iter.next(),
|
||||
iter: iter,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> Iterator for MendSlices<I>
|
||||
where I: Iterator,
|
||||
I::Item: MendSlice
|
||||
{
|
||||
type Item = I::Item;
|
||||
|
||||
fn next(&mut self) -> Option<I::Item> {
|
||||
// this fuses the iterator
|
||||
let mut last = match self.last.take() {
|
||||
None => return None,
|
||||
Some(x) => x,
|
||||
};
|
||||
for next in &mut self.iter {
|
||||
match MendSlice::mend(last, next) {
|
||||
Ok(joined) => last = joined,
|
||||
Err((last_, next_)) => {
|
||||
self.last = Some(next_);
|
||||
return Some(last_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(last)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for items that can *maybe* be joined together.
|
||||
pub trait MendSlice
|
||||
{
|
||||
#[doc(hidden)]
|
||||
/// If the slices are contiguous, return them joined into one.
|
||||
fn mend(Self, Self) -> Result<Self, (Self, Self)>
|
||||
where Self: Sized;
|
||||
}
|
||||
|
||||
impl<'a, T> MendSlice for &'a [T] {
|
||||
#[inline]
|
||||
fn mend(a: Self, b: Self) -> Result<Self, (Self, Self)> {
|
||||
unsafe {
|
||||
let a_end = a.as_ptr().offset(a.len() as isize);
|
||||
if a_end == b.as_ptr() {
|
||||
Ok(::std::slice::from_raw_parts(a.as_ptr(), a.len() + b.len()))
|
||||
} else {
|
||||
Err((a, b))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> MendSlice for &'a mut [T] {
|
||||
#[inline]
|
||||
fn mend(a: Self, b: Self) -> Result<Self, (Self, Self)> {
|
||||
unsafe {
|
||||
let a_end = a.as_ptr().offset(a.len() as isize);
|
||||
if a_end == b.as_ptr() {
|
||||
Ok(::std::slice::from_raw_parts_mut(a.as_mut_ptr(), a.len() + b.len()))
|
||||
} else {
|
||||
Err((a, b))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> MendSlice for &'a str {
|
||||
#[inline]
|
||||
fn mend(a: Self, b: Self) -> Result<Self, (Self, Self)> {
|
||||
unsafe { mem::transmute(MendSlice::mend(a.as_bytes(), b.as_bytes())) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// "plain old data": Types that we can stick arbitrary bit patterns into,
|
||||
/// and thus use them as blocks in `split_aligned_for` or in `UnalignedIter`.
|
||||
pub unsafe trait Pod : Copy { }
|
||||
macro_rules! impl_pod {
|
||||
(@array $($e:expr),+) => {
|
||||
$(
|
||||
unsafe impl<T> Pod for [T; $e] where T: Pod { }
|
||||
)+
|
||||
};
|
||||
($($t:ty)+) => {
|
||||
$(
|
||||
unsafe impl Pod for $t { }
|
||||
)+
|
||||
};
|
||||
}
|
||||
impl_pod!{u8 u16 u32 u64 usize i8 i16 i32 i64 isize}
|
||||
impl_pod!{@array 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
|
||||
|
||||
|
||||
/// Split the input slice into three chunks,
|
||||
/// so that the middle chunk is a slice of a larger "block size"
|
||||
/// (for example T could be u64) that is correctly aligned for `T`.
|
||||
///
|
||||
/// The first and last returned slices are the remaining head and tail
|
||||
/// parts that could not be baked into `&[T]`
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// extern crate odds;
|
||||
/// use odds::slice::split_aligned_for;
|
||||
///
|
||||
/// fn count_ones(data: &[u8]) -> u32 {
|
||||
/// let mut total = 0;
|
||||
/// let (head, mid, tail) = split_aligned_for::<[u64; 2]>(data);
|
||||
/// total += head.iter().map(|x| x.count_ones()).sum();
|
||||
/// total += mid.iter().map(|x| x[0].count_ones() + x[1].count_ones()).sum();
|
||||
/// total += tail.iter().map(|x| x.count_ones()).sum();
|
||||
/// total
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// assert_eq!(count_ones(&vec![3u8; 127]), 127 * 2);
|
||||
/// }
|
||||
/// ```
|
||||
pub fn split_aligned_for<T: Pod>(data: &[u8]) -> (&[u8], &[T], &[u8]) {
|
||||
let ptr = data.as_ptr();
|
||||
let align_t = align_of::<T>();
|
||||
let size_t = size_of::<T>();
|
||||
let align_ptr = ptr as usize & (align_t - 1);
|
||||
let prefix = if align_ptr == 0 { 0 } else { align_t - align_ptr };
|
||||
let t_len;
|
||||
|
||||
if prefix > data.len() {
|
||||
t_len = 0;
|
||||
} else {
|
||||
t_len = (data.len() - prefix) / size_t;
|
||||
}
|
||||
unsafe {
|
||||
(from_raw_parts(ptr, prefix),
|
||||
from_raw_parts(ptr.offset(prefix as isize) as *const T, t_len),
|
||||
from_raw_parts(ptr.offset((prefix + t_len * size_t) as isize),
|
||||
data.len() - t_len * size_t - prefix))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_split_aligned() {
|
||||
let data = vec![0; 1024];
|
||||
assert_eq!(data.as_ptr() as usize & 7, 0);
|
||||
let (a, b, c) = split_aligned_for::<u8>(&data);
|
||||
assert_eq!(a.len(), 0);
|
||||
assert_eq!(b.len(), data.len());
|
||||
assert_eq!(c.len(), 0);
|
||||
|
||||
let (a, b, c) = split_aligned_for::<u64>(&data);
|
||||
assert_eq!(a.len(), 0);
|
||||
assert_eq!(b.len(), data.len() / 8);
|
||||
assert_eq!(c.len(), 0);
|
||||
|
||||
let offset1 = &data[1..data.len() - 2];
|
||||
let (a, b, c) = split_aligned_for::<u64>(offset1);
|
||||
assert_eq!(a.len(), 7);
|
||||
assert_eq!(b.len(), data.len() / 8 - 2);
|
||||
assert_eq!(c.len(), 6);
|
||||
|
||||
let data = [0; 7];
|
||||
let (a, b, c) = split_aligned_for::<u64>(&data);
|
||||
assert_eq!(a.len() + c.len(), 7);
|
||||
assert_eq!(b.len(), 0);
|
||||
}
|
||||
|
||||
|
||||
/* All of these use this trick:
|
||||
*
|
||||
for i in 0..4 {
|
||||
if i < data.len() {
|
||||
f(&data[i]);
|
||||
}
|
||||
}
|
||||
* The intention is that the range makes sure the compiler
|
||||
* sees that the loop is not autovectorized or something that generates
|
||||
* a lot of code in vain that does not pay off when it's only 3 elements or less.
|
||||
*/
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn unroll_2<'a, T, F>(data: &'a [T], mut f: F)
|
||||
where F: FnMut(&'a T)
|
||||
{
|
||||
let mut data = data;
|
||||
while data.len() >= 2 {
|
||||
f(&data[0]);
|
||||
f(&data[1]);
|
||||
data = &data[2..];
|
||||
}
|
||||
// tail
|
||||
if 0 < data.len() {
|
||||
f(&data[0]);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn unroll_4<'a, T, F>(data: &'a [T], mut f: F)
|
||||
where F: FnMut(&'a T)
|
||||
{
|
||||
let mut data = data;
|
||||
while data.len() >= 4 {
|
||||
f(&data[0]);
|
||||
f(&data[1]);
|
||||
f(&data[2]);
|
||||
f(&data[3]);
|
||||
data = &data[4..];
|
||||
}
|
||||
// tail
|
||||
for i in 0..3 {
|
||||
if i < data.len() {
|
||||
f(&data[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn unroll_8<'a, T, F>(data: &'a [T], mut f: F)
|
||||
where F: FnMut(&'a T)
|
||||
{
|
||||
let mut data = data;
|
||||
while data.len() >= 8 {
|
||||
f(&data[0]);
|
||||
f(&data[1]);
|
||||
f(&data[2]);
|
||||
f(&data[3]);
|
||||
f(&data[4]);
|
||||
f(&data[5]);
|
||||
f(&data[6]);
|
||||
f(&data[7]);
|
||||
data = &data[8..];
|
||||
}
|
||||
// tail
|
||||
for i in 0..7 {
|
||||
if i < data.len() {
|
||||
f(&data[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn zip_unroll_4<'a, 'b, A, B, F>(a: &'a [A], b: &'b [B], mut f: F)
|
||||
where F: FnMut(usize, &'a A, &'b B)
|
||||
{
|
||||
let len = min(a.len(), b.len());
|
||||
let mut a = &a[..len];
|
||||
let mut b = &b[..len];
|
||||
while a.len() >= 4 {
|
||||
f(0, &a[0], &b[0]);
|
||||
f(1, &a[1], &b[1]);
|
||||
f(2, &a[2], &b[2]);
|
||||
f(3, &a[3], &b[3]);
|
||||
a = &a[4..];
|
||||
b = &b[4..];
|
||||
}
|
||||
// tail
|
||||
for i in 0..3 {
|
||||
if i < a.len() {
|
||||
f(0, &a[i], &b[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn zip_unroll_8<'a, 'b, A, B, F>(a: &'a [A], b: &'b [B], mut f: F)
|
||||
where F: FnMut(usize, &'a A, &'b B)
|
||||
{
|
||||
let len = min(a.len(), b.len());
|
||||
let mut a = &a[..len];
|
||||
let mut b = &b[..len];
|
||||
while a.len() >= 8 {
|
||||
f(0, &a[0], &b[0]);
|
||||
f(1, &a[1], &b[1]);
|
||||
f(2, &a[2], &b[2]);
|
||||
f(3, &a[3], &b[3]);
|
||||
f(4, &a[4], &b[4]);
|
||||
f(5, &a[5], &b[5]);
|
||||
f(6, &a[6], &b[6]);
|
||||
f(7, &a[7], &b[7]);
|
||||
a = &a[8..];
|
||||
b = &b[8..];
|
||||
}
|
||||
|
||||
// tail
|
||||
for i in 0..7 {
|
||||
if i < a.len() {
|
||||
f(0, &a[i], &b[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn f64_dot(xs: &[f64], ys: &[f64]) -> f64 {
|
||||
let mut sum = [0.; 8];
|
||||
zip_unroll_8(xs, ys, |i, x, y| sum[i] += x * y);
|
||||
sum[0] += sum[4];
|
||||
sum[1] += sum[5];
|
||||
sum[2] += sum[6];
|
||||
sum[3] += sum[7];
|
||||
sum[0] += sum[2];
|
||||
sum[1] += sum[3];
|
||||
sum[0] + sum[1]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find() {
|
||||
let v = [0, 1, 7, 0, 0, 2, 3, 5, 1, 5, 3, 1, 2, 1];
|
||||
assert_eq!(v.find_split(&7), v.split_at(2));
|
||||
assert_eq!(v.rfind_split(&7), v.split_at(2));
|
||||
assert_eq!(v.rfind_split(&2), v.split_at(v.len() - 2));
|
||||
}
|
||||
|
||||
/// A reversed view of a slice.
|
||||
///
|
||||
/// The `RevSlice` is a random accessible range of elements;
|
||||
/// it wraps a regular slice but presents the underlying elements in
|
||||
/// reverse order.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// use odds::slice::RevSlice;
|
||||
///
|
||||
/// let mut data = [0; 8];
|
||||
///
|
||||
/// {
|
||||
/// let mut rev = <&mut RevSlice<_>>::from(&mut data);
|
||||
/// for (i, elt) in rev.iter_mut().enumerate() {
|
||||
/// *elt = i;
|
||||
/// }
|
||||
///
|
||||
/// assert_eq!(&rev[..4], &[0, 1, 2, 3][..]);
|
||||
/// }
|
||||
/// assert_eq!(&data, &[7, 6, 5, 4, 3, 2, 1, 0]);
|
||||
/// ```
|
||||
///
|
||||
/// Not visible in rustdoc:
|
||||
///
|
||||
/// - A boxed slice can be reversed too:
|
||||
/// `impl<T> From<Box<[T]>> for Box<RevSlice<T>>`.
|
||||
#[derive(Debug, Eq)]
|
||||
#[repr(C)]
|
||||
pub struct RevSlice<T>([T]);
|
||||
|
||||
impl<T> RevSlice<T> {
|
||||
/// Return the length of the slice.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
// arithmetic overflow checked in debug builds
|
||||
#[inline]
|
||||
fn raw_index_no_wrap(&self, i: usize) -> usize {
|
||||
self.len() - (1 + i)
|
||||
}
|
||||
|
||||
/// Return the index into the underlying slice, if it's in bounds
|
||||
fn raw_index(&self, i: usize) -> Option<usize> {
|
||||
if i < self.len() {
|
||||
Some(self.raw_index_no_wrap(i))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get element at index `i`.
|
||||
///
|
||||
/// See also indexing notation: `&foo[i]`.
|
||||
pub fn get(&self, i: usize) -> Option<&T> {
|
||||
unsafe {
|
||||
self.raw_index(i).map(move |ri| get_unchecked(&self.0, ri))
|
||||
}
|
||||
}
|
||||
|
||||
/// Get element at index `i`.
|
||||
///
|
||||
/// See also indexing notation: `&mut foo[i]`.
|
||||
pub fn get_mut(&mut self, i: usize) -> Option<&mut T> {
|
||||
unsafe {
|
||||
self.raw_index(i).map(move |ri| get_unchecked_mut(&mut self.0, ri))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn inner_ref(&self) -> &[T] {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn inner_mut(&mut self) -> &mut [T] {
|
||||
&mut self.0
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub fn into_boxed_slice(self: Box<Self>) -> Box<[T]> {
|
||||
unsafe {
|
||||
transmute(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a by-reference iterator
|
||||
pub fn iter(&self) -> Rev<Iter<T>> {
|
||||
self.into_iter()
|
||||
}
|
||||
|
||||
/// Return a by-mutable-reference iterator
|
||||
pub fn iter_mut(&mut self) -> Rev<IterMut<T>> {
|
||||
self.into_iter()
|
||||
}
|
||||
|
||||
pub fn split_at(&self, i: usize) -> (&Self, &Self) {
|
||||
assert!(i <= self.len());
|
||||
let ri = self.len() - i;
|
||||
let (a, b) = self.0.split_at(ri);
|
||||
(<_>::from(b), <_>::from(a))
|
||||
}
|
||||
|
||||
pub fn split_at_mut(&mut self, i: usize) -> (&mut Self, &mut Self) {
|
||||
assert!(i <= self.len());
|
||||
let ri = self.len() - i;
|
||||
let (a, b) = self.0.split_at_mut(ri);
|
||||
(<_>::from(b), <_>::from(a))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> PartialEq<RevSlice<U>> for RevSlice<T>
|
||||
where T: PartialEq<U>,
|
||||
{
|
||||
fn eq(&self, rhs: &RevSlice<U>) -> bool {
|
||||
self.0 == rhs.0
|
||||
}
|
||||
}
|
||||
|
||||
/// `RevSlice` compares by logical element sequence.
|
||||
impl<T, U> PartialEq<[U]> for RevSlice<T>
|
||||
where T: PartialEq<U>,
|
||||
{
|
||||
fn eq(&self, rhs: &[U]) -> bool {
|
||||
if self.len() != rhs.len() {
|
||||
return false;
|
||||
}
|
||||
for (x, y) in self.into_iter().zip(rhs) {
|
||||
if x != y {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Hash for RevSlice<T>
|
||||
where T: Hash,
|
||||
{
|
||||
fn hash<H: Hasher>(&self, h: &mut H) {
|
||||
// hash like a slice of the same logical sequence
|
||||
self.len().hash(h);
|
||||
for elt in self {
|
||||
elt.hash(h)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, Slice: ?Sized> From<&'a Slice> for &'a RevSlice<T>
|
||||
where Slice: AsRef<[T]>
|
||||
{
|
||||
fn from(slc: &'a Slice) -> Self {
|
||||
unsafe {
|
||||
transmute(slc.as_ref())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, Slice: ?Sized> From<&'a mut Slice> for &'a mut RevSlice<T>
|
||||
where Slice: AsMut<[T]>
|
||||
{
|
||||
fn from(slc: &'a mut Slice) -> Self {
|
||||
unsafe {
|
||||
transmute(slc.as_mut())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T> From<Box<[T]>> for Box<RevSlice<T>> {
|
||||
fn from(slc: Box<[T]>) -> Self {
|
||||
unsafe {
|
||||
transmute(slc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Index<usize> for RevSlice<T> {
|
||||
type Output = T;
|
||||
fn index(&self, i: usize) -> &T {
|
||||
if let Some(x) = self.get(i) {
|
||||
x
|
||||
} else {
|
||||
panic!("Index {} is out of bounds for RevSlice of length {}", i, self.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IndexMut<usize> for RevSlice<T> {
|
||||
fn index_mut(&mut self, i: usize) -> &mut T {
|
||||
let len = self.len();
|
||||
if let Some(x) = self.get_mut(i) {
|
||||
return x;
|
||||
} else {
|
||||
panic!("Index {} is out of bounds for RevSlice of length {}", i, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Default for &'a RevSlice<T> {
|
||||
fn default() -> Self {
|
||||
Self::from(&[])
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Default for &'a mut RevSlice<T> {
|
||||
fn default() -> Self {
|
||||
Self::from(&mut [])
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, R> Index<R> for RevSlice<T>
|
||||
where R: IndexRange,
|
||||
{
|
||||
type Output = RevSlice<T>;
|
||||
fn index(&self, index: R) -> &RevSlice<T> {
|
||||
// [0 1 2 3 4]
|
||||
// 4 3 2 1 0
|
||||
// [ ] <- rev 1..5 is 0..4
|
||||
let start = index.start().unwrap_or(0);
|
||||
let end = index.end().unwrap_or(self.len());
|
||||
assert!(start <= end && end <= self.len());
|
||||
let end_r = self.len() - start;
|
||||
let start_r = self.len() - end;
|
||||
unsafe {
|
||||
<&RevSlice<_>>::from(slice_unchecked(&self.0, start_r, end_r))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, R> IndexMut<R> for RevSlice<T>
|
||||
where R: IndexRange,
|
||||
{
|
||||
fn index_mut(&mut self, index: R) -> &mut RevSlice<T> {
|
||||
// [0 1 2 3 4]
|
||||
// 4 3 2 1 0
|
||||
// [ ] <- rev 1..5 is 0..4
|
||||
let start = index.start().unwrap_or(0);
|
||||
let end = index.end().unwrap_or(self.len());
|
||||
assert!(start <= end && end <= self.len());
|
||||
let end_r = self.len() - start;
|
||||
let start_r = self.len() - end;
|
||||
unsafe {
|
||||
<&mut RevSlice<_>>::from(slice_unchecked_mut(&mut self.0, start_r, end_r))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoIterator for &'a RevSlice<T> {
|
||||
type Item = &'a T;
|
||||
type IntoIter = Rev<Iter<'a, T>>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.0.iter().rev()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoIterator for &'a mut RevSlice<T> {
|
||||
type Item = &'a mut T;
|
||||
type IntoIter = Rev<IterMut<'a, T>>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.0.iter_mut().rev()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rev_slice_1() {
|
||||
let data = [1, 2, 3, 4];
|
||||
let rev = [4, 3, 2, 1];
|
||||
|
||||
assert_eq!(<&RevSlice<_>>::from(&data[..]), &rev[..]);
|
||||
assert!(<&RevSlice<_>>::from(&data[..]) != &data[..]);
|
||||
let r = <&RevSlice<_>>::from(&data[..]);
|
||||
assert_eq!(r[0], rev[0]);
|
||||
assert_eq!(r[3], rev[3]);
|
||||
}
|
||||
|
||||
#[should_panic]
|
||||
#[test]
|
||||
fn test_rev_slice_2() {
|
||||
let data = [1, 2, 3, 4];
|
||||
|
||||
let r = <&RevSlice<_>>::from(&data[..]);
|
||||
r[4];
|
||||
}
|
||||
|
||||
#[should_panic]
|
||||
#[test]
|
||||
fn test_rev_slice_3() {
|
||||
let data = [1, 2, 3, 4];
|
||||
|
||||
let r = <&RevSlice<_>>::from(&data[..]);
|
||||
r[!0];
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rev_slice_slice() {
|
||||
let data = [1, 2, 3, 4];
|
||||
let rev = [4, 3, 2, 1];
|
||||
|
||||
let r = <&RevSlice<_>>::from(&data[..]);
|
||||
|
||||
for i in 0..r.len() {
|
||||
for j in i..r.len() {
|
||||
println!("{:?}, {:?}", &r[i..j], &rev[i..j]);
|
||||
assert_eq!(&r[i..j], &rev[i..j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rev_slice_find() {
|
||||
let data = [1, 2, 3, 4];
|
||||
|
||||
let r = <&RevSlice<_>>::from(&data[..]);
|
||||
|
||||
for (i, elt) in r.into_iter().enumerate() {
|
||||
assert_eq!(r.find(elt), Some(i));
|
||||
}
|
||||
for (i, elt) in r.into_iter().enumerate() {
|
||||
assert_eq!(r.rfind(elt), Some(i));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rev_slice_split() {
|
||||
let data = [1, 2, 3, 4];
|
||||
|
||||
let r = <&RevSlice<_>>::from(&data[..]);
|
||||
|
||||
for i in 0..r.len() {
|
||||
let (a, b) = r.split_at(i);
|
||||
assert_eq!(a, &r[..i]);
|
||||
assert_eq!(b, &r[i..]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rev_slice_hash() {
|
||||
let data = [1, 2, 3, 4];
|
||||
let rev = [4, 3, 2, 1];
|
||||
|
||||
let r = <&RevSlice<_>>::from(&data[..]);
|
||||
|
||||
#[allow(deprecated)]
|
||||
fn hash<T: ?Sized + Hash>(value: &T) -> u64 {
|
||||
use std::hash::SipHasher;
|
||||
let mut h = SipHasher::new();
|
||||
value.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
for i in 0..r.len() {
|
||||
for j in i..r.len() {
|
||||
assert_eq!(hash(&r[i..j]), hash(&rev[i..j]));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,121 @@
|
|||
|
||||
|
||||
use std::mem::size_of;
|
||||
use std::mem::uninitialized;
|
||||
use std::marker::PhantomData;
|
||||
use std::ptr;
|
||||
|
||||
use slice::Pod;
|
||||
use slice::iter::SliceCopyIter;
|
||||
|
||||
/// An iterator of `T` (by value) where each value read using an
|
||||
/// unaligned load.
|
||||
///
|
||||
/// See also the method `.tail()`.
|
||||
#[derive(Debug)]
|
||||
pub struct UnalignedIter<'a, T: 'a> {
|
||||
ptr: *const u8,
|
||||
end: *const u8,
|
||||
tail_end: *const u8,
|
||||
ty: PhantomData<&'a T>,
|
||||
}
|
||||
|
||||
impl<'a, T> Copy for UnalignedIter<'a, T> { }
|
||||
impl<'a, T> Clone for UnalignedIter<'a, T> {
|
||||
fn clone(&self) -> Self { *self }
|
||||
}
|
||||
|
||||
impl<'a, T> UnalignedIter<'a, T> {
|
||||
/// Create an `UnalignedIter` from `ptr` and `end`, which must be spaced
|
||||
/// an whole number of `T` offsets apart.
|
||||
pub unsafe fn from_raw_parts(ptr: *const u8, end: *const u8) -> Self {
|
||||
let len = end as usize - ptr as usize;
|
||||
debug_assert_eq!(len % size_of::<T>(), 0);
|
||||
UnalignedIter {
|
||||
ptr: ptr,
|
||||
end: end,
|
||||
tail_end: end,
|
||||
ty: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an `UnalignedIter` out of the slice of data, which
|
||||
/// iterates first in blocks of `T` (unaligned loads), and
|
||||
/// then leaves a tail of the remaining bytes.
|
||||
pub fn from_slice(data: &'a [u8]) -> Self where T: Pod {
|
||||
unsafe {
|
||||
let ptr = data.as_ptr();
|
||||
let len = data.len();
|
||||
let sz = size_of::<T>() as isize;
|
||||
let end_block = ptr.offset(len as isize / sz * sz);
|
||||
let end = ptr.offset(len as isize);
|
||||
UnalignedIter {
|
||||
ptr: ptr,
|
||||
end: end_block,
|
||||
tail_end: end,
|
||||
ty: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a byte iterator of the remaining tail of the iterator;
|
||||
/// this can be called at any time, but in particular when the iterator
|
||||
/// has returned None.
|
||||
pub fn tail(&self) -> SliceCopyIter<'a, u8> {
|
||||
unsafe {
|
||||
SliceCopyIter::new(self.ptr, self.tail_end)
|
||||
}
|
||||
}
|
||||
|
||||
/// Return `true` if the tail is not empty.
|
||||
pub fn has_tail(&self) -> bool {
|
||||
self.ptr != self.tail_end
|
||||
}
|
||||
|
||||
/// Return the next iterator element, without stepping the iterator.
|
||||
pub fn peek_next(&self) -> Option<T> where T: Copy {
|
||||
if self.ptr != self.end {
|
||||
unsafe {
|
||||
Some(load_unaligned(self.ptr))
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn load_unaligned<T>(p: *const u8) -> T where T: Copy {
|
||||
let mut x = uninitialized();
|
||||
ptr::copy_nonoverlapping(p, &mut x as *mut _ as *mut u8, size_of::<T>());
|
||||
x
|
||||
}
|
||||
|
||||
impl<'a, T> Iterator for UnalignedIter<'a, T>
|
||||
where T: Copy,
|
||||
{
|
||||
type Item = T;
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.ptr != self.end {
|
||||
unsafe {
|
||||
let elt = Some(load_unaligned::<T>(self.ptr));
|
||||
self.ptr = self.ptr.offset(size_of::<T>() as isize);
|
||||
elt
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_unalign() {
|
||||
let data = [0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
let mut iter = UnalignedIter::<u32>::from_slice(&data);
|
||||
assert_eq!(iter.next(), Some(u32::from_be(0x00010203)));
|
||||
assert_eq!(iter.next(), Some(u32::from_be(0x04050607)));
|
||||
let mut tail = iter.tail();
|
||||
assert_eq!(tail.next(), Some(8));
|
||||
assert_eq!(tail.next(), Some(9));
|
||||
assert_eq!(tail.next(), None);
|
||||
}
|
|
@ -0,0 +1,303 @@
|
|||
//! Slice iterator with custom step size
|
||||
//!
|
||||
//! Performance note: Using stable Rust features, these iterators
|
||||
//! don't quite live up to the efficiency that they should have,
|
||||
//! unfortunately.
|
||||
//!
|
||||
//! Licensed under the Apache License, Version 2.0
|
||||
//! http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
|
||||
//! http://opensource.org/licenses/MIT, at your
|
||||
//! option. This file may not be copied, modified, or distributed
|
||||
//! except according to those terms.
|
||||
|
||||
use std::fmt;
|
||||
use std::marker;
|
||||
use std::mem;
|
||||
use std::ops::{Index, IndexMut};
|
||||
|
||||
|
||||
/// (the stride) skipped per iteration.
|
||||
///
|
||||
/// `Stride` does not support zero-sized types for `A`.
|
||||
///
|
||||
/// Iterator element type is `&'a A`.
|
||||
pub struct Stride<'a, A: 'a> {
|
||||
/// base pointer -- does not change during iteration
|
||||
begin: *const A,
|
||||
/// current offset from begin
|
||||
offset: isize,
|
||||
/// offset where we end (exclusive end).
|
||||
end: isize,
|
||||
stride: isize,
|
||||
life: marker::PhantomData<&'a A>,
|
||||
}
|
||||
|
||||
impl<'a, A> Copy for Stride<'a, A> {}
|
||||
unsafe impl<'a, A> Send for Stride<'a, A> where A: Sync {}
|
||||
unsafe impl<'a, A> Sync for Stride<'a, A> where A: Sync {}
|
||||
|
||||
/// The mutable equivalent of Stride.
|
||||
///
|
||||
/// `StrideMut` does not support zero-sized types for `A`.
|
||||
///
|
||||
/// Iterator element type is `&'a mut A`.
|
||||
pub struct StrideMut<'a, A: 'a> {
|
||||
begin: *mut A,
|
||||
offset: isize,
|
||||
end: isize,
|
||||
stride: isize,
|
||||
life: marker::PhantomData<&'a mut A>,
|
||||
}
|
||||
|
||||
unsafe impl<'a, A> Send for StrideMut<'a, A> where A: Send {}
|
||||
unsafe impl<'a, A> Sync for StrideMut<'a, A> where A: Sync {}
|
||||
|
||||
impl<'a, A> Stride<'a, A> {
|
||||
/// Create a Stride iterator from a raw pointer.
|
||||
pub unsafe fn from_ptr_len(begin: *const A, nelem: usize, stride: isize) -> Stride<'a, A>
|
||||
{
|
||||
Stride {
|
||||
begin: begin,
|
||||
offset: 0,
|
||||
end: stride * nelem as isize,
|
||||
stride: stride,
|
||||
life: marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A> StrideMut<'a, A>
|
||||
{
|
||||
/// Create a StrideMut iterator from a raw pointer.
|
||||
pub unsafe fn from_ptr_len(begin: *mut A, nelem: usize, stride: isize) -> StrideMut<'a, A>
|
||||
{
|
||||
StrideMut {
|
||||
begin: begin,
|
||||
offset: 0,
|
||||
end: stride * nelem as isize,
|
||||
stride: stride,
|
||||
life: marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn div_rem(x: usize, d: usize) -> (usize, usize) {
|
||||
(x / d, x % d)
|
||||
}
|
||||
|
||||
macro_rules! stride_impl {
|
||||
(struct $name:ident -> $slice:ty, $getptr:ident, $ptr:ty, $elem:ty) => {
|
||||
impl<'a, A> $name<'a, A>
|
||||
{
|
||||
/// Create Stride iterator from a slice and the element step count.
|
||||
///
|
||||
/// If `step` is negative, start from the back.
|
||||
///
|
||||
/// ```
|
||||
/// use odds::stride::Stride;
|
||||
///
|
||||
/// let xs = [0, 1, 2, 3, 4, 5];
|
||||
///
|
||||
/// let front = Stride::from_slice(&xs, 2);
|
||||
/// assert_eq!(front[0], 0);
|
||||
/// assert_eq!(front[1], 2);
|
||||
///
|
||||
/// let back = Stride::from_slice(&xs, -2);
|
||||
/// assert_eq!(back[0], 5);
|
||||
/// assert_eq!(back[1], 3);
|
||||
/// ```
|
||||
///
|
||||
/// **Panics** if values of type `A` are zero-sized. <br>
|
||||
/// **Panics** if `step` is 0.
|
||||
#[inline]
|
||||
pub fn from_slice(xs: $slice, step: isize) -> $name<'a, A>
|
||||
{
|
||||
assert!(mem::size_of::<A>() != 0);
|
||||
let ustep = if step < 0 { -step } else { step } as usize;
|
||||
let nelem = if ustep <= 1 {
|
||||
xs.len()
|
||||
} else {
|
||||
let (d, r) = div_rem(xs.len(), ustep);
|
||||
d + if r > 0 { 1 } else { 0 }
|
||||
};
|
||||
let mut begin = xs. $getptr ();
|
||||
unsafe {
|
||||
if step > 0 {
|
||||
$name::from_ptr_len(begin, nelem, step)
|
||||
} else {
|
||||
if nelem != 0 {
|
||||
begin = begin.offset(xs.len() as isize - 1)
|
||||
}
|
||||
$name::from_ptr_len(begin, nelem, step)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create Stride iterator from an existing Stride iterator
|
||||
///
|
||||
/// **Panics** if `step` is 0.
|
||||
#[inline]
|
||||
pub fn from_stride(mut it: $name<'a, A>, mut step: isize) -> $name<'a, A>
|
||||
{
|
||||
assert!(step != 0);
|
||||
if step < 0 {
|
||||
it.swap_ends();
|
||||
step = -step;
|
||||
}
|
||||
let len = (it.end - it.offset) / it.stride;
|
||||
let newstride = it.stride * step;
|
||||
let (d, r) = div_rem(len as usize, step as usize);
|
||||
let len = d + if r > 0 { 1 } else { 0 };
|
||||
unsafe {
|
||||
$name::from_ptr_len(it.begin, len, newstride)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swap the begin and end and reverse the stride,
|
||||
/// in effect reversing the iterator.
|
||||
#[inline]
|
||||
pub fn swap_ends(&mut self) {
|
||||
let len = (self.end - self.offset) / self.stride;
|
||||
if len > 0 {
|
||||
unsafe {
|
||||
let endptr = self.begin.offset((len - 1) * self.stride);
|
||||
*self = $name::from_ptr_len(endptr, len as usize, -self.stride);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the number of elements in the iterator.
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize {
|
||||
((self.end - self.offset) / self.stride) as usize
|
||||
}
|
||||
|
||||
/// Return a reference to the element of a stride at the
|
||||
/// given index, or None if the index is out of bounds.
|
||||
#[inline]
|
||||
pub fn get<'b>(&'b self, i: usize) -> Option<&'b A> {
|
||||
if i >= self.len() {
|
||||
None
|
||||
} else {
|
||||
unsafe {
|
||||
let ptr = self.begin.offset(self.offset + self.stride * (i as isize));
|
||||
Some(mem::transmute(ptr))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A> Iterator for $name<'a, A>
|
||||
{
|
||||
type Item = $elem;
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<$elem>
|
||||
{
|
||||
if self.offset == self.end {
|
||||
None
|
||||
} else {
|
||||
unsafe {
|
||||
let elt: $elem =
|
||||
mem::transmute(self.begin.offset(self.offset));
|
||||
self.offset += self.stride;
|
||||
Some(elt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len();
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A> DoubleEndedIterator for $name<'a, A>
|
||||
{
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<$elem>
|
||||
{
|
||||
if self.offset == self.end {
|
||||
None
|
||||
} else {
|
||||
unsafe {
|
||||
self.end -= self.stride;
|
||||
let elt = mem::transmute(self.begin.offset(self.end));
|
||||
Some(elt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A> ExactSizeIterator for $name<'a, A> { }
|
||||
|
||||
impl<'a, A> Index<usize> for $name<'a, A>
|
||||
{
|
||||
type Output = A;
|
||||
/// Return a reference to the element at a given index.
|
||||
///
|
||||
/// **Panics** if the index is out of bounds.
|
||||
fn index<'b>(&'b self, i: usize) -> &'b A
|
||||
{
|
||||
assert!(i < self.len());
|
||||
unsafe {
|
||||
let ptr = self.begin.offset(self.offset + self.stride * (i as isize));
|
||||
mem::transmute(ptr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A> fmt::Debug for $name<'a, A>
|
||||
where A: fmt::Debug
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
|
||||
{
|
||||
try!(write!(f, "["));
|
||||
for i in 0..self.len() {
|
||||
if i != 0 {
|
||||
try!(write!(f, ", "));
|
||||
}
|
||||
try!(write!(f, "{:?}", (*self)[i]));
|
||||
}
|
||||
write!(f, "]")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stride_impl!{struct Stride -> &'a [A], as_ptr, *const A, &'a A}
|
||||
stride_impl!{struct StrideMut -> &'a mut [A], as_mut_ptr, *mut A, &'a mut A}
|
||||
|
||||
impl<'a, A> Clone for Stride<'a, A> {
|
||||
fn clone(&self) -> Stride<'a, A> {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A> StrideMut<'a, A> {
|
||||
/// Return a mutable reference to the element of a stride at the
|
||||
/// given index, or None if the index is out of bounds.
|
||||
pub fn get_mut<'b>(&'b mut self, i: usize) -> Option<&'b mut A> {
|
||||
if i >= self.len() {
|
||||
None
|
||||
} else {
|
||||
unsafe {
|
||||
let ptr = self.begin.offset(self.offset + self.stride * (i as isize));
|
||||
Some(&mut *ptr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A> IndexMut<usize> for StrideMut<'a, A> {
|
||||
/// Return a mutable reference to the element at a given index.
|
||||
///
|
||||
/// **Panics** if the index is out of bounds.
|
||||
fn index_mut<'b>(&'b mut self, i: usize) -> &'b mut A {
|
||||
assert!(i < self.len());
|
||||
unsafe {
|
||||
let ptr = self.begin.offset(self.offset + self.stride * (i as isize));
|
||||
&mut *ptr
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,375 @@
|
|||
//! Extensions to `&str` and `String`
|
||||
//!
|
||||
use std::iter;
|
||||
#[cfg(feature="std")]
|
||||
use std::ptr;
|
||||
use std::str;
|
||||
use std::ops::Deref;
|
||||
|
||||
use IndexRange;
|
||||
|
||||
/// Extra methods for `str`
|
||||
pub trait StrExt {
|
||||
#[cfg(feature="std")]
|
||||
/// Repeat the string `n` times.
|
||||
///
|
||||
/// Requires `feature="std"`
|
||||
fn rep(&self, n: usize) -> String;
|
||||
|
||||
#[cfg(feature="std")]
|
||||
/// Requires `feature="std"`
|
||||
fn append(&self, s: &str) -> String;
|
||||
|
||||
/// All non-empty prefixes
|
||||
fn prefixes(&self) -> Prefixes;
|
||||
|
||||
/// All non-empty suffixes
|
||||
fn suffixes(&self) -> Suffixes;
|
||||
|
||||
/// Produce all non-empty substrings
|
||||
fn substrings(&self) -> Substrings;
|
||||
|
||||
/// Return `true` if `index` is acceptable for slicing the string.
|
||||
///
|
||||
/// Acceptable indices are byte offsets from the start of the string
|
||||
/// that mark the start of an encoded utf-8 sequence, or an index equal
|
||||
/// to `self.len()`.
|
||||
///
|
||||
/// Return `false` if the index is out of bounds.
|
||||
///
|
||||
/// For example the string `"Abcαβγ"` has length is 9 and the acceptable
|
||||
/// indices are *0, 1, 2, 3, 5, 7,* and *9*.
|
||||
///
|
||||
/// ```
|
||||
/// use odds::string::StrExt;
|
||||
/// for &ix in &[0, 1, 2, 3, 5, 7, 9] {
|
||||
/// assert!("Abcαβγ".is_acceptable_index(ix));
|
||||
/// }
|
||||
/// ```
|
||||
fn is_acceptable_index(&self, index: usize) -> bool;
|
||||
}
|
||||
|
||||
/// Extension trait for `str` for string slicing without panicking
|
||||
pub trait StrSlice {
|
||||
/// Return a slice of the string, if it is in bounds /and on character boundaries/,
|
||||
/// otherwise return `None`
|
||||
fn get_slice<R>(&self, r: R) -> Option<&str> where R: IndexRange;
|
||||
}
|
||||
|
||||
impl StrExt for str {
|
||||
#[cfg(feature="std")]
|
||||
fn rep(&self, n: usize) -> String {
|
||||
let mut s = String::with_capacity(self.len() * n);
|
||||
s.extend((0..n).map(|_| self));
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(feature="std")]
|
||||
fn append(&self, s: &str) -> String {
|
||||
String::from(self) + s
|
||||
}
|
||||
|
||||
fn prefixes(&self) -> Prefixes {
|
||||
Prefixes { s: self, iter: self.char_indices() }
|
||||
}
|
||||
|
||||
fn suffixes(&self) -> Suffixes {
|
||||
Suffixes { s: self, iter: self.char_indices() }
|
||||
}
|
||||
|
||||
fn substrings(&self) -> Substrings {
|
||||
Substrings { iter: self.prefixes().flat_map(str::suffixes) }
|
||||
}
|
||||
|
||||
fn is_acceptable_index(&self, index: usize) -> bool {
|
||||
if index == 0 || index == self.len() {
|
||||
true
|
||||
} else {
|
||||
self.as_bytes().get(index).map_or(false, |byte| {
|
||||
// check it's not a continuation byte
|
||||
*byte as i8 >= -0x40
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StrSlice for str {
|
||||
fn get_slice<R>(&self, r: R) -> Option<&str> where R: IndexRange {
|
||||
let start = r.start().unwrap_or(0);
|
||||
let end = r.end().unwrap_or(self.len());
|
||||
if start <= end && self.is_acceptable_index(start) && self.is_acceptable_index(end) {
|
||||
Some(&self[start..end])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator of all non-empty prefixes
|
||||
#[derive(Clone)]
|
||||
pub struct Prefixes<'a> {
|
||||
s: &'a str,
|
||||
iter: str::CharIndices<'a>,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Prefixes<'a> {
|
||||
type Item = &'a str;
|
||||
|
||||
fn next(&mut self) -> Option<&'a str> {
|
||||
self.iter.next().map(|(i, ch)| &self.s[..i + ch.len_utf8()])
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator of all non-empty suffixes
|
||||
#[derive(Clone)]
|
||||
pub struct Suffixes<'a> {
|
||||
s: &'a str,
|
||||
iter: str::CharIndices<'a>,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Suffixes<'a> {
|
||||
type Item = &'a str;
|
||||
|
||||
fn next(&mut self) -> Option<&'a str> {
|
||||
self.iter.next().map(|(i, _)| &self.s[i..])
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator of all non-empty substrings
|
||||
#[derive(Clone)]
|
||||
pub struct Substrings<'a> {
|
||||
iter: iter::FlatMap<Prefixes<'a>, Suffixes<'a>, fn(&'a str) -> Suffixes<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Substrings<'a> {
|
||||
type Item = &'a str;
|
||||
|
||||
fn next(&mut self) -> Option<&'a str> {
|
||||
self.iter.next()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature="std")]
|
||||
/// Extra methods for `String`
|
||||
///
|
||||
/// Requires `feature="std"`
|
||||
pub trait StringExt {
|
||||
/// **Panics** if `index` is out of bounds.
|
||||
fn insert_str(&mut self, index: usize, s: &str);
|
||||
}
|
||||
|
||||
#[cfg(feature="std")]
|
||||
impl StringExt for String {
|
||||
/// **Panics** if `index` is out of bounds.
|
||||
fn insert_str(&mut self, index: usize, s: &str) {
|
||||
assert!(self.is_acceptable_index(index));
|
||||
self.reserve(s.len());
|
||||
// move the tail, then copy in the string
|
||||
unsafe {
|
||||
let v = self.as_mut_vec();
|
||||
let ptr = v.as_mut_ptr();
|
||||
ptr::copy(ptr.offset(index as isize),
|
||||
ptr.offset((index + s.len()) as isize),
|
||||
v.len() - index);
|
||||
ptr::copy_nonoverlapping(s.as_ptr(),
|
||||
ptr.offset(index as isize),
|
||||
s.len());
|
||||
let new_len = v.len() + s.len();
|
||||
v.set_len(new_len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension traits for the `char_chunks` and `char_windows` methods
|
||||
pub trait StrChunksWindows {
|
||||
/// Return an iterator that splits the string in substrings of each `n`
|
||||
/// `char` per substring. The last item will contain the remainder if
|
||||
/// `n` does not divide the char length of the string evenly.
|
||||
fn char_chunks(&self, n: usize) -> CharChunks;
|
||||
|
||||
/// Return an iterator that produces substrings of each `n`
|
||||
/// `char` per substring in a sliding window that advances one char at a time.
|
||||
///
|
||||
/// ***Panics*** if `n` is zero.
|
||||
fn char_windows(&self, n: usize) -> CharWindows;
|
||||
}
|
||||
|
||||
impl StrChunksWindows for str {
|
||||
fn char_chunks(&self, n: usize) -> CharChunks {
|
||||
CharChunks::new(self, n)
|
||||
}
|
||||
|
||||
fn char_windows(&self, n: usize) -> CharWindows {
|
||||
CharWindows::new(self, n)
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator that splits the string in substrings of each `n`
|
||||
/// `char` per substring. The last item will contain the remainder if
|
||||
/// `n` does not divide the char length of the string evenly.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CharChunks<'a> {
|
||||
s: &'a str,
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl<'a> CharChunks<'a> {
|
||||
fn new(s: &'a str, n: usize) -> Self {
|
||||
CharChunks { s: s, n: n }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for CharChunks<'a> {
|
||||
type Item = &'a str;
|
||||
fn next(&mut self) -> Option<&'a str> {
|
||||
let s = self.s;
|
||||
if s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
for (i, (j, ch)) in s.char_indices().enumerate() {
|
||||
if i + 1 == self.n {
|
||||
// FIXME: Use .split_at() when rust version allows
|
||||
let mid = j + ch.len_utf8();
|
||||
let (part, tail) = (&s[..mid], &s[mid..]);
|
||||
self.s = tail;
|
||||
return Some(part);
|
||||
}
|
||||
}
|
||||
self.s = "";
|
||||
Some(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator that produces substrings of each `n`
|
||||
/// `char` per substring in a sliding window that advances one char at a time.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CharWindows<'a> {
|
||||
s: &'a str,
|
||||
a: usize,
|
||||
b: usize,
|
||||
}
|
||||
|
||||
impl<'a> CharWindows<'a> {
|
||||
fn new(s: &'a str, n: usize) -> Self {
|
||||
assert!(n != 0);
|
||||
match s.char_indices().nth(n - 1) {
|
||||
None => CharWindows { s: s, a: s.len(), b: s.len() },
|
||||
Some((i, ch)) => CharWindows { s: s, a: 0, b: i + ch.len_utf8() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn char_get(s: &str, i: usize) -> Option<char> {
|
||||
s[i..].chars().next()
|
||||
}
|
||||
|
||||
impl<'a> Iterator for CharWindows<'a> {
|
||||
type Item = &'a str;
|
||||
fn next(&mut self) -> Option<&'a str> {
|
||||
let elt;
|
||||
// `a` is out of bounds when we are done
|
||||
if let Some(c) = char_get(self.s, self.a) {
|
||||
elt = &self.s[self.a..self.b];
|
||||
self.a += c.len_utf8();
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
if let Some(c) = char_get(self.s, self.b) {
|
||||
self.b += c.len_utf8();
|
||||
} else {
|
||||
self.a = self.s.len();
|
||||
}
|
||||
Some(elt)
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-char string.
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct CharStr {
|
||||
buf: [u8; 4],
|
||||
len: u32,
|
||||
}
|
||||
|
||||
impl CharStr {
|
||||
/// Create a new string from `c`.
|
||||
pub fn new(c: char) -> CharStr {
|
||||
let mut self_ = CharStr {
|
||||
buf: [0; 4],
|
||||
len: c.len_utf8() as u32,
|
||||
};
|
||||
let _ = ::char::encode_utf8(c, &mut self_.buf);
|
||||
self_
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for CharStr {
|
||||
type Target = str;
|
||||
fn deref(&self) -> &str {
|
||||
unsafe {
|
||||
str::from_utf8_unchecked(&self.buf[..self.len as usize])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_char_str() {
|
||||
let s = CharStr::new('α');
|
||||
assert_eq!(&s[..], "α");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn str_windows() {
|
||||
assert_eq!(CharWindows::new("abc", 4).next(), None);
|
||||
assert_eq!(CharWindows::new("abc", 3).next(), Some("abc"));
|
||||
assert_eq!(CharWindows::new("abc", 3).count(), 1);
|
||||
assert_eq!(CharWindows::new("αbγ", 2).nth(0), Some("αb"));
|
||||
assert_eq!(CharWindows::new("αbγ", 2).nth(1), Some("bγ"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn str_windows_not_0() {
|
||||
CharWindows::new("abc", 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_acc_index() {
|
||||
let s = "Abcαβγ";
|
||||
for (ix, ch) in s.char_indices() {
|
||||
assert!(s.is_acceptable_index(ix));
|
||||
// check the continuation bytes
|
||||
for j in 1..ch.len_utf8() {
|
||||
assert!(!s.is_acceptable_index(ix + j));
|
||||
}
|
||||
}
|
||||
assert!(s.is_acceptable_index(s.len()));
|
||||
let indices = [0, 1, 2, 3, 5, 7, 9];
|
||||
|
||||
for &ix in &indices {
|
||||
assert!(s.is_acceptable_index(ix));
|
||||
}
|
||||
|
||||
let t = "";
|
||||
assert!(t.is_acceptable_index(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_ext() {
|
||||
let mut s = String::new();
|
||||
let t = "αβγabc";
|
||||
StringExt::insert_str(&mut s, 0, t);
|
||||
assert_eq!(s, t);
|
||||
StringExt::insert_str(&mut s, 2, "x");
|
||||
assert_eq!(s, "αxβγabc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slice() {
|
||||
let t = "αβγabc";
|
||||
assert_eq!(t.get_slice(..), Some(t));
|
||||
assert_eq!(t.get_slice(0..t.len()), Some(t));
|
||||
assert_eq!(t.get_slice(1..), None);
|
||||
assert_eq!(t.get_slice(0..t.len()+1), None);
|
||||
assert_eq!(t.get_slice(t.len()+1..), None);
|
||||
assert_eq!(t.get_slice(t.len()..), Some(""));
|
||||
}
|
|
@ -0,0 +1,215 @@
|
|||
//! Extensions to `Vec`
|
||||
//!
|
||||
//! Requires `feature="std"`
|
||||
#![cfg(feature="std")]
|
||||
|
||||
use range::IndexRange;
|
||||
use std::ptr;
|
||||
use std::slice;
|
||||
|
||||
use slice::SliceFind;
|
||||
|
||||
|
||||
/// Create a new vec from the iterable
|
||||
pub fn vec<I>(iterable: I) -> Vec<I::Item>
|
||||
where I: IntoIterator
|
||||
{
|
||||
iterable.into_iter().collect()
|
||||
}
|
||||
|
||||
|
||||
/// Extra methods for `Vec<T>`
|
||||
///
|
||||
/// Requires `feature="std"`
|
||||
pub trait VecExt<T> {
|
||||
/// Remove elements in a range, and insert from an iterator in their place.
|
||||
///
|
||||
/// The removed and inserted ranges don't have to match in length.
|
||||
///
|
||||
/// **Panics** if range `r` is out of bounds.
|
||||
///
|
||||
/// **Panics** if iterator `iter` is not of exact length.
|
||||
fn splice<R, I>(&mut self, r: R, iter: I)
|
||||
where I: IntoIterator<Item=T>,
|
||||
I::IntoIter: ExactSizeIterator,
|
||||
R: IndexRange;
|
||||
|
||||
/// Retains only the elements specified by the predicate.
|
||||
///
|
||||
/// In other words, remove all elements `e` such that `f(&mut e)` returns false.
|
||||
/// This method operates in place and preserves the order of the retained
|
||||
/// elements.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use odds::vec::VecExt;
|
||||
/// let mut vec = vec![1, 2, 3, 4];
|
||||
/// vec.retain_mut(|x| {
|
||||
/// let keep = *x % 2 == 0;
|
||||
/// *x *= 10;
|
||||
/// keep
|
||||
/// });
|
||||
/// assert_eq!(vec, [20, 40]);
|
||||
/// ```
|
||||
fn retain_mut<F>(&mut self, f: F)
|
||||
where F: FnMut(&mut T) -> bool;
|
||||
}
|
||||
|
||||
/// `Vec::splice`: Remove elements in a range, and insert from an iterator
|
||||
/// in their place.
|
||||
///
|
||||
/// The removed and inserted ranges don't have to match in length.
|
||||
///
|
||||
/// **Panics** if range `r` is out of bounds.
|
||||
///
|
||||
/// **Panics** if iterator `iter` is not of exact length.
|
||||
impl<T> VecExt<T> for Vec<T> {
|
||||
fn splice<R, I>(&mut self, r: R, iter: I)
|
||||
where I: IntoIterator<Item=T>,
|
||||
I::IntoIter: ExactSizeIterator,
|
||||
R: IndexRange,
|
||||
{
|
||||
let v = self;
|
||||
let mut iter = iter.into_iter();
|
||||
let (input_len, _) = iter.size_hint();
|
||||
let old_len = v.len();
|
||||
let r = r.start().unwrap_or(0)..r.end().unwrap_or(old_len);
|
||||
assert!(r.start <= r.end);
|
||||
assert!(r.end <= v.len());
|
||||
let rm_len = r.end - r.start;
|
||||
v.reserve(input_len.saturating_sub(rm_len));
|
||||
|
||||
unsafe {
|
||||
let ptr = v.as_mut_ptr();
|
||||
v.set_len(r.start);
|
||||
|
||||
// drop all elements in `r`
|
||||
{
|
||||
let mslc = slice::from_raw_parts_mut(ptr.offset(r.start as isize), rm_len);
|
||||
for elt_ptr in mslc {
|
||||
ptr::read(elt_ptr); // Possible panic
|
||||
}
|
||||
}
|
||||
|
||||
if rm_len != input_len {
|
||||
// move tail elements
|
||||
ptr::copy(ptr.offset(r.end as isize),
|
||||
ptr.offset((r.start + input_len) as isize),
|
||||
old_len - r.end);
|
||||
}
|
||||
|
||||
// fill in elements from the iterator
|
||||
// FIXME: On panic, drop tail properly too (using panic guard)
|
||||
{
|
||||
let grow_slc = slice::from_raw_parts_mut(ptr.offset(r.start as isize), input_len);
|
||||
let mut len = r.start;
|
||||
for slot_ptr in grow_slc {
|
||||
if let Some(input_elt) = iter.next() { // Possible Panic
|
||||
ptr::write(slot_ptr, input_elt);
|
||||
} else {
|
||||
// FIXME: Skip check with trusted iterators
|
||||
panic!("splice: iterator too short");
|
||||
}
|
||||
// update length to drop as much as possible on panic
|
||||
len += 1;
|
||||
v.set_len(len);
|
||||
}
|
||||
v.set_len(old_len - rm_len + input_len);
|
||||
}
|
||||
}
|
||||
//assert!(iter.next().is_none(), "splice: iterator not exact size");
|
||||
}
|
||||
|
||||
// Adapted from libcollections/vec.rs in Rust
|
||||
// Primary author in Rust: Michael Darakananda
|
||||
fn retain_mut<F>(&mut self, mut f: F)
|
||||
where F: FnMut(&mut T) -> bool
|
||||
{
|
||||
let len = self.len();
|
||||
let mut del = 0;
|
||||
{
|
||||
let v = &mut **self;
|
||||
|
||||
for i in 0..len {
|
||||
if !f(&mut v[i]) {
|
||||
del += 1;
|
||||
} else if del > 0 {
|
||||
v.swap(i - del, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
if del > 0 {
|
||||
self.truncate(len - del);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait VecFindRemove {
|
||||
type Item;
|
||||
/// Linear search for the first element equal to `elt` and remove
|
||||
/// it if found.
|
||||
///
|
||||
/// Return its index and the value itself.
|
||||
fn find_remove<U>(&mut self, elt: &U) -> Option<(usize, Self::Item)>
|
||||
where Self::Item: PartialEq<U>;
|
||||
|
||||
/// Linear search for the last element equal to `elt` and remove
|
||||
/// it if found.
|
||||
///
|
||||
/// Return its index and the value itself.
|
||||
fn rfind_remove<U>(&mut self, elt: &U) -> Option<(usize, Self::Item)>
|
||||
where Self::Item: PartialEq<U>;
|
||||
}
|
||||
|
||||
impl<T> VecFindRemove for Vec<T> {
|
||||
type Item = T;
|
||||
fn find_remove<U>(&mut self, elt: &U) -> Option<(usize, Self::Item)>
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
self.find(elt).map(|i| (i, self.remove(i)))
|
||||
}
|
||||
fn rfind_remove<U>(&mut self, elt: &U) -> Option<(usize, Self::Item)>
|
||||
where Self::Item: PartialEq<U>
|
||||
{
|
||||
self.rfind(elt).map(|i| (i, self.remove(i)))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice() {
|
||||
use std::iter::once;
|
||||
|
||||
let mut v = vec![1, 2, 3, 4];
|
||||
v.splice(1..1, vec![9, 9]);
|
||||
assert_eq!(v, &[1, 9, 9, 2, 3, 4]);
|
||||
|
||||
let mut v = vec![1, 2, 3, 4];
|
||||
v.splice(1..2, vec![9, 9]);
|
||||
assert_eq!(v, &[1, 9, 9, 3, 4]);
|
||||
|
||||
let mut v = vec![1, 2, 3, 4, 5];
|
||||
v.splice(1..4, vec![9, 9]);
|
||||
assert_eq!(v, &[1, 9, 9, 5]);
|
||||
|
||||
let mut v = vec![1, 2, 3, 4];
|
||||
v.splice(0..4, once(9));
|
||||
assert_eq!(v, &[9]);
|
||||
|
||||
let mut v = vec![1, 2, 3, 4];
|
||||
v.splice(0..4, None);
|
||||
assert_eq!(v, &[]);
|
||||
|
||||
let mut v = vec![1, 2, 3, 4];
|
||||
v.splice(1.., Some(9));
|
||||
assert_eq!(v, &[1, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find() {
|
||||
let mut v = vec![0, 1, 2, 3, 1, 2, 1];
|
||||
assert_eq!(v.rfind_remove(&1), Some((6, 1)));
|
||||
assert_eq!(v.find_remove(&2), Some((2, 2)));
|
||||
assert_eq!(v.find_remove(&7), None);
|
||||
assert_eq!(&v, &[0, 1, 3, 1, 2]);
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
|
||||
extern crate itertools;
|
||||
extern crate odds;
|
||||
|
||||
use odds::slice::SliceIterExt;
|
||||
use itertools::Itertools;
|
||||
|
||||
#[test]
|
||||
fn mend_slices() {
|
||||
let text = "α-toco (and) β-toco";
|
||||
let full_text = CharSlices::new(text).map(|(_, s)| s).mend_slices().join("");
|
||||
assert_eq!(text, full_text);
|
||||
|
||||
// join certain different pieces together again
|
||||
let words = CharSlices::new(text).map(|(_, s)| s)
|
||||
.filter(|s| !s.chars().any(char::is_whitespace))
|
||||
.mend_slices().collect::<Vec<_>>();
|
||||
assert_eq!(words, vec!["α-toco", "(and)", "β-toco"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mend_slices_mut() {
|
||||
let mut data = [1, 2, 3];
|
||||
let mut copy = data.to_vec();
|
||||
{
|
||||
let slc = data.chunks_mut(1).mend_slices().next().unwrap();
|
||||
assert_eq!(slc, &mut copy[..]);
|
||||
}
|
||||
{
|
||||
let slc = data.chunks_mut(2).mend_slices().next().unwrap();
|
||||
assert_eq!(slc, &mut copy[..]);
|
||||
}
|
||||
{
|
||||
let mut iter = data.chunks_mut(1).filter(|c| c[0] != 2).mend_slices();
|
||||
assert_eq!(iter.next(), Some(&mut [1][..]));
|
||||
assert_eq!(iter.next(), Some(&mut [3][..]));
|
||||
assert_eq!(iter.next(), None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Like CharIndices iterator, except it yields slices instead
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
struct CharSlices<'a> {
|
||||
slice: &'a str,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
impl<'a> CharSlices<'a>
|
||||
{
|
||||
pub fn new(s: &'a str) -> Self
|
||||
{
|
||||
CharSlices {
|
||||
slice: s,
|
||||
offset: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for CharSlices<'a>
|
||||
{
|
||||
type Item = (usize, &'a str);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item>
|
||||
{
|
||||
if self.slice.len() == 0 {
|
||||
return None
|
||||
}
|
||||
// count continuation bytes
|
||||
let mut char_len = 1;
|
||||
let mut bytes = self.slice.bytes();
|
||||
bytes.next();
|
||||
for byte in bytes {
|
||||
if (byte & 0xC0) != 0x80 {
|
||||
break
|
||||
}
|
||||
char_len += 1;
|
||||
}
|
||||
let ch_slice;
|
||||
unsafe {
|
||||
ch_slice = self.slice.slice_unchecked(0, char_len);
|
||||
self.slice = self.slice.slice_unchecked(char_len, self.slice.len());
|
||||
}
|
||||
let off = self.offset;
|
||||
self.offset += char_len;
|
||||
Some((off, ch_slice))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
|
||||
extern crate odds;
|
||||
|
||||
use odds::stride::Stride;
|
||||
use odds::stride::StrideMut;
|
||||
|
||||
#[test]
|
||||
fn mut_stride() {
|
||||
let mut xs = vec![1, 1, 1, 1, 1, 1];
|
||||
for x in StrideMut::from_slice(&mut *xs, 2) {
|
||||
*x = 0;
|
||||
}
|
||||
assert_eq!(xs, vec![0, 1, 0, 1, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mut_stride_compose() {
|
||||
let mut xs = vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
|
||||
{
|
||||
let iter1 = StrideMut::from_slice(&mut *xs, 2);
|
||||
let iter2 = StrideMut::from_stride(iter1, 3);
|
||||
for x in iter2 {
|
||||
*x = 0;
|
||||
}
|
||||
}
|
||||
assert_eq!(xs, vec![0, 1, 1, 1, 1, 1, 0, 1, 1, 1]);
|
||||
|
||||
let mut vs = vec![1, 2, 3];
|
||||
let mut it = StrideMut::from_slice(&mut *vs, 1);
|
||||
{
|
||||
assert_eq!(it.get_mut(3), None);
|
||||
assert_eq!(it.get_mut(1), Some(&mut 2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stride_uneven() {
|
||||
let xs = &[7, 9, 8];
|
||||
let it = Stride::from_slice(xs, 2);
|
||||
assert!(it.size_hint() == (2, Some(2)));
|
||||
assert!(it.eq(&[7, 8]));
|
||||
|
||||
let xs = &[7, 9, 8, 10];
|
||||
let it = Stride::from_slice(&xs[1..], 2);
|
||||
assert!(it.size_hint() == (2, Some(2)));
|
||||
assert!(it.eq(&[9, 10]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stride_compose() {
|
||||
let xs = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
let odds = Stride::from_slice(xs, 2);
|
||||
let it = Stride::from_stride(odds, 2);
|
||||
assert!(it.eq(&[1, 5, 9]));
|
||||
|
||||
let xs = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
let evens = Stride::from_slice(&xs[1..], 2);
|
||||
let it = Stride::from_stride(evens, 2);
|
||||
assert!(it.eq( &[2, 6]));
|
||||
|
||||
let xs = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
let evens = Stride::from_slice(&xs[1..], 2);
|
||||
let it = Stride::from_stride(evens, 1);
|
||||
assert!(it.eq( &[2, 4, 6, 8]));
|
||||
|
||||
let xs = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
let mut odds = Stride::from_slice(xs, 2);
|
||||
odds.swap_ends();
|
||||
let it = Stride::from_stride(odds, 2);
|
||||
assert!(it.eq( &[9, 5, 1]));
|
||||
|
||||
let xs = &[1, 2, 3];
|
||||
let every = Stride::from_slice(xs, 1);
|
||||
assert_eq!(every.len(), 3);
|
||||
assert_eq!(every.get(1), Some(&2));
|
||||
let odds = Stride::from_stride(every, 2);
|
||||
assert_eq!(odds.len(), 2);
|
||||
assert_eq!(odds.get(0), Some(&1));
|
||||
assert_eq!(odds.get(1), Some(&3));
|
||||
assert_eq!(odds.get(2), None);
|
||||
assert!(odds.eq( &[1, 3]));
|
||||
|
||||
let xs = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
let evens = Stride::from_slice(&xs[1..], 2);
|
||||
let it = Stride::from_stride(evens, -2);
|
||||
assert!(it.eq( &[8, 4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_stride_empty()
|
||||
{
|
||||
let xs = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
let mut odds = Stride::from_slice(xs, 2);
|
||||
odds.by_ref().count();
|
||||
assert!(odds.len() == 0);
|
||||
assert!(odds.next().is_none());
|
||||
let mut it = Stride::from_stride(odds, 2);
|
||||
assert!(it.len() == 0);
|
||||
assert!(it.next().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stride() {
|
||||
let xs: &[u8] = &[];
|
||||
let mut it = Stride::from_slice(xs, 1);
|
||||
assert!(it.size_hint() == (0, Some(0)));
|
||||
assert!(it.next().is_none());
|
||||
|
||||
let xs = &[7, 9, 8, 10];
|
||||
let it = Stride::from_slice(xs, 2);
|
||||
assert!(it.size_hint() == (2, Some(2)));
|
||||
assert!(it.eq( &[7, 8]));
|
||||
|
||||
let it = Stride::from_slice(xs, 2).rev();
|
||||
assert!(it.size_hint() == (2, Some(2)));
|
||||
assert!(it.eq( &[8, 7]));
|
||||
|
||||
let xs = &[7, 9, 8, 10];
|
||||
let it = Stride::from_slice(xs, 1);
|
||||
assert!(it.size_hint() == (4, Some(4)));
|
||||
assert!(it.eq( &[7, 9, 8, 10]));
|
||||
|
||||
let it = Stride::from_slice(xs, 1).rev();
|
||||
assert!(it.size_hint() == (4, Some(4)));
|
||||
assert!(it.eq( &[10, 8, 9, 7]));
|
||||
|
||||
let mut it = Stride::from_slice(xs, 2);
|
||||
it.swap_ends();
|
||||
assert!(it.size_hint() == (2, Some(2)));
|
||||
assert!(it.eq( &[8, 7]));
|
||||
|
||||
let it = Stride::from_slice(xs, -2);
|
||||
assert_eq!(it.size_hint(), (2, Some(2)));
|
||||
assert!(it.eq( &[10, 9]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stride_index() {
|
||||
let xs = &[7, 9, 8, 10];
|
||||
let it = Stride::from_slice(xs, 2);
|
||||
assert_eq!(it[0], 7);
|
||||
assert_eq!(it[1], 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn stride_index_fail() {
|
||||
let xs = &[7, 9, 8, 10];
|
||||
let it = Stride::from_slice(xs, 2);
|
||||
let _ = it[2];
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
|
||||
extern crate odds;
|
||||
extern crate itertools;
|
||||
|
||||
use odds::string::StrExt;
|
||||
|
||||
#[test]
|
||||
fn rep() {
|
||||
assert_eq!("".rep(0), "");
|
||||
assert_eq!("xy".rep(0), "");
|
||||
assert_eq!("xy".rep(3), "xyxyxy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixes() {
|
||||
itertools::assert_equal(
|
||||
"".prefixes(),
|
||||
Vec::<&str>::new());
|
||||
itertools::assert_equal(
|
||||
"x".prefixes(),
|
||||
vec!["x"]);
|
||||
itertools::assert_equal(
|
||||
"abc".prefixes(),
|
||||
vec!["a", "ab", "abc"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substrings() {
|
||||
itertools::assert_equal(
|
||||
"αβγ".substrings(),
|
||||
vec!["α", "αβ", "β", "αβγ", "βγ", "γ"]);
|
||||
}
|
|
@ -31,6 +31,15 @@ dependencies = [
|
|||
"serde 0.9.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayvec"
|
||||
version = "0.3.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"odds 0.2.25 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aster"
|
||||
version = "0.41.0"
|
||||
|
@ -455,6 +464,14 @@ dependencies = [
|
|||
"num-traits 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nodrop"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"odds 0.2.25 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "1.2.4"
|
||||
|
@ -503,6 +520,11 @@ dependencies = [
|
|||
"libc 0.2.20 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "odds"
|
||||
version = "0.2.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "ordered-float"
|
||||
version = "0.4.0"
|
||||
|
@ -781,6 +803,7 @@ name = "style"
|
|||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"app_units 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bindgen 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bit-vec 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
|
@ -1089,6 +1112,7 @@ dependencies = [
|
|||
"checksum aho-corasick 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0638fd549427caa90c499814196d1b9e3725eb4d15d7339d6de073a680ed0ca2"
|
||||
"checksum ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "23ac7c30002a5accbf7e8987d0632fa6de155b7c3d39d0067317a391e00a2ef6"
|
||||
"checksum app_units 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5a0c3b5be4ed53affe3e1a162b2e7ef9979bcaac80daa9026e9d7988c41e0e83"
|
||||
"checksum arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)" = "699e63a93b79d717e8c3b5eb1b28b7780d0d6d9e59a72eb769291c83b0c8dc67"
|
||||
"checksum aster 0.41.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4ccfdf7355d9db158df68f976ed030ab0f6578af811f5a7bb6dcf221ec24e0e0"
|
||||
"checksum atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb2dcb6e6d35f20276943cc04bb98e538b348d525a04ac79c10021561d202f21"
|
||||
"checksum binary-space-partition 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88ceb0d16c4fd0e42876e298d7d3ce3780dd9ebdcbe4199816a32c77e08597ff"
|
||||
|
@ -1133,10 +1157,12 @@ dependencies = [
|
|||
"checksum log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ab83497bf8bf4ed2a74259c1c802351fcd67a65baa86394b6ba73c36f4838054"
|
||||
"checksum matches 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "efd7622e3022e1a6eaa602c4cea8912254e5582c9c692e9167714182244801b1"
|
||||
"checksum memchr 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1dbccc0e46f1ea47b9f17e6d67c5a96bd27030519c519c9c91327e31275a47b4"
|
||||
"checksum nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "52cd74cd09beba596430cc6e3091b74007169a56246e1262f0ba451ea95117b2"
|
||||
"checksum nom 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a5b8c256fd9471521bcb84c3cdba98921497f1a331cbc15b8030fc63b82050ce"
|
||||
"checksum num-integer 0.1.33 (registry+https://github.com/rust-lang/crates.io-index)" = "21e4df1098d1d797d27ef0c69c178c3fab64941559b290fcae198e0825c9c8b5"
|
||||
"checksum num-traits 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)" = "e1cbfa3781f3fe73dc05321bed52a06d2d491eaa764c52335cf4399f046ece99"
|
||||
"checksum num_cpus 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a225d1e2717567599c24f88e49f00856c6e825a12125181ee42c4257e3688d39"
|
||||
"checksum odds 0.2.25 (registry+https://github.com/rust-lang/crates.io-index)" = "c3df9b730298cea3a1c3faa90b7e2f9df3a9c400d0936d6015e6165734eefcba"
|
||||
"checksum ordered-float 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "da12c96037889ae0be29dd2bdd260e5a62a7df24e6466d5a15bb8131c1c200a8"
|
||||
"checksum owning_ref 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "9d52571ddcb42e9c900c901a18d8d67e393df723fcd51dd59c5b1a85d0acb6cc"
|
||||
"checksum parking_lot 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "fa12d706797d42551663426a45e2db2e0364bd1dbf6aeada87e89c5f981f43e9"
|
||||
|
|
|
@ -29,6 +29,15 @@ dependencies = [
|
|||
"serde 0.9.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayvec"
|
||||
version = "0.3.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"odds 0.2.25 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aster"
|
||||
version = "0.41.0"
|
||||
|
@ -449,6 +458,14 @@ dependencies = [
|
|||
"num-traits 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nodrop"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"odds 0.2.25 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "1.2.4"
|
||||
|
@ -490,6 +507,11 @@ dependencies = [
|
|||
"libc 0.2.20 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "odds"
|
||||
version = "0.2.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "ordered-float"
|
||||
version = "0.4.0"
|
||||
|
@ -768,6 +790,7 @@ name = "style"
|
|||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"app_units 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bindgen 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bit-vec 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
|
@ -1076,6 +1099,7 @@ dependencies = [
|
|||
"checksum aho-corasick 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0638fd549427caa90c499814196d1b9e3725eb4d15d7339d6de073a680ed0ca2"
|
||||
"checksum ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "23ac7c30002a5accbf7e8987d0632fa6de155b7c3d39d0067317a391e00a2ef6"
|
||||
"checksum app_units 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5a0c3b5be4ed53affe3e1a162b2e7ef9979bcaac80daa9026e9d7988c41e0e83"
|
||||
"checksum arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)" = "699e63a93b79d717e8c3b5eb1b28b7780d0d6d9e59a72eb769291c83b0c8dc67"
|
||||
"checksum aster 0.41.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4ccfdf7355d9db158df68f976ed030ab0f6578af811f5a7bb6dcf221ec24e0e0"
|
||||
"checksum atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb2dcb6e6d35f20276943cc04bb98e538b348d525a04ac79c10021561d202f21"
|
||||
"checksum binary-space-partition 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88ceb0d16c4fd0e42876e298d7d3ce3780dd9ebdcbe4199816a32c77e08597ff"
|
||||
|
@ -1120,10 +1144,12 @@ dependencies = [
|
|||
"checksum log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ab83497bf8bf4ed2a74259c1c802351fcd67a65baa86394b6ba73c36f4838054"
|
||||
"checksum matches 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "efd7622e3022e1a6eaa602c4cea8912254e5582c9c692e9167714182244801b1"
|
||||
"checksum memchr 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1dbccc0e46f1ea47b9f17e6d67c5a96bd27030519c519c9c91327e31275a47b4"
|
||||
"checksum nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "52cd74cd09beba596430cc6e3091b74007169a56246e1262f0ba451ea95117b2"
|
||||
"checksum nom 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a5b8c256fd9471521bcb84c3cdba98921497f1a331cbc15b8030fc63b82050ce"
|
||||
"checksum num-integer 0.1.33 (registry+https://github.com/rust-lang/crates.io-index)" = "21e4df1098d1d797d27ef0c69c178c3fab64941559b290fcae198e0825c9c8b5"
|
||||
"checksum num-traits 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)" = "e1cbfa3781f3fe73dc05321bed52a06d2d491eaa764c52335cf4399f046ece99"
|
||||
"checksum num_cpus 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a225d1e2717567599c24f88e49f00856c6e825a12125181ee42c4257e3688d39"
|
||||
"checksum odds 0.2.25 (registry+https://github.com/rust-lang/crates.io-index)" = "c3df9b730298cea3a1c3faa90b7e2f9df3a9c400d0936d6015e6165734eefcba"
|
||||
"checksum ordered-float 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "da12c96037889ae0be29dd2bdd260e5a62a7df24e6466d5a15bb8131c1c200a8"
|
||||
"checksum owning_ref 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "9d52571ddcb42e9c900c901a18d8d67e393df723fcd51dd59c5b1a85d0acb6cc"
|
||||
"checksum parking_lot 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "fa12d706797d42551663426a45e2db2e0364bd1dbf6aeada87e89c5f981f43e9"
|
||||
|
|
Загрузка…
Ссылка в новой задаче