No bug - Revendor rust dependencies manually on a CLOSED TREE. r=me

MozReview-Commit-ID: C0KKGL9FbRd
This commit is contained in:
Emilio Cobos Álvarez 2017-12-08 01:17:46 +01:00
parent 1750c2726f
commit fc0d2c8a68
50 changed files with 1850 additions and 3959 deletions

View File

@ -1 +1 @@
{"files":{".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"}
{"files":{".travis.yml":"f46144bac95afc5c195460b982a6fbe01d7408d2437c08d55e1d4f3c29f602f6","Cargo.toml":"992a91fe1967332d461d3abe0274fdc9ef3c40c79d3b2234b8a0b28df0f569ca","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7576269ea71f767b99297934c0b2367532690f8c4badc695edf8e04ab6a1e545","README.rst":"567d3109630c6daae23d24a9fb0f3de9261303a1ce7a63869234504665798eed","benches/arraystring.rs":"f12b890977117ebde4ca42bcd6b91f2a6a087f2b235aaca6d15e30d125ae9f67","benches/extend.rs":"8c8f78df7e90b62c7e160cf5ea6c61b90bc4035a9704b6a179a1e01d8fafe2e9","custom.css":"e6f2cd299392337b4e2959c52f422e5b7be11920ea98d10db44d10ddef5ed47c","src/array.rs":"9e73f982e33e5ff6dfa86ec139cab9edf17e117563f2595cb263461c1ace3adb","src/array_string.rs":"af240c1194725e382e8d21e07ccb9aa5e9b18f6160c207d8b587002e812bae51","src/char.rs":"64a08f6a743b67bf2c96483f91c2fdaea79f6e91df5cd752f770b16a6b1d5b1e","src/errors.rs":"dde99bffaddfd45396aab7e07642cc018ef5435fe60c4f26a2c05a36555be18c","src/lib.rs":"da52b3555850c3f8f601458494db91cb7039ceef2e6911e4dd57b21a515d45eb","src/range.rs":"65744ab7def208a1ab155ea2448fe9ea7fc14f33211361b1041f540125b32efd","tests/serde.rs":"ef3986a82656b09f3fbb14358e767051ffabe09592c61e69ea695cb88760e8ba","tests/tests.rs":"0d8d54f5f33ed9cb83d8b18fcbce4ee74ae85f1a2d9f65d22ad4a487498534e6"},"package":"2f0ef4a9820019a0c91d918918c93dc71d469f581a49b47ddc1d285d4270bbe2"}

View File

@ -1,12 +1,14 @@
language: rust
sudo: false
env:
- FEATURES='serde-1'
matrix:
include:
- rust: 1.2.0
- rust: 1.14.0
- rust: stable
env:
- FEATURES="use_generic_array"
- NODEFAULT=1
- NODROP_FEATURES='use_needs_drop'
- rust: beta
- rust: nightly
env:
@ -16,7 +18,7 @@ matrix:
- NODROP_FEATURES='use_needs_drop'
- rust: nightly
env:
- FEATURES='use_union use_generic_array'
- FEATURES='serde use_union'
- NODROP_FEATURES='use_union'
branches:
only:

View File

@ -1,30 +1,57 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g. crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
name = "arrayvec"
version = "0.3.23"
version = "0.4.6"
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."
description = "A vector with fixed capacity, backed by an array (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"]
categories = ["data-structures", "no-std"]
license = "MIT/Apache-2.0"
repository = "https://github.com/bluss/arrayvec"
[package.metadata.docs.rs]
features = ["serde-1"]
[dependencies.odds]
version = "0.2.23"
default-features = false
[package.metadata.release]
no-dev-version = true
[[bench]]
name = "extend"
harness = false
[[bench]]
name = "arraystring"
harness = false
[dependencies.nodrop]
version = "0.1.8"
path = "nodrop"
version = "0.1.12"
default-features = false
[dependencies.generic-array]
version = "0.5.1"
[dependencies.serde]
version = "1.0"
optional = true
default-features = false
[dev-dependencies.bencher]
version = "0.1.4"
[dev-dependencies.matches]
version = "0.1"
[dev-dependencies.serde_test]
version = "1.0"
[features]
default = ["std"]
std = ["odds/std", "nodrop/std"]
use_union = ["nodrop/use_union"]
use_generic_array = ["generic-array"]
serde-1 = ["serde"]
std = []
use_union = []

View File

@ -1,22 +0,0 @@
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.

201
third_party/rust/arrayvec/LICENSE-APACHE vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
third_party/rust/arrayvec/LICENSE-MIT vendored Normal file
View File

@ -0,0 +1,25 @@
Copyright (c) 2015
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.

View File

@ -1,35 +0,0 @@
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)

View File

@ -2,11 +2,11 @@
arrayvec
========
A vector with fixed capacity. Requires Rust 1.2+.
A vector with fixed capacity.
Please read the `API documentation here`__
__ https://bluss.github.io/arrayvec
__ https://docs.rs/arrayvec
|build_status|_ |crates|_ |crates2|_
@ -22,6 +22,64 @@ __ https://bluss.github.io/arrayvec
Recent Changes (arrayvec)
-------------------------
- 0.4.6
- Fix compilation on 16-bit targets. This means, the 65536 array size is not
included on these targets.
- 0.3.24
- Fix compilation on 16-bit targets. This means, the 65536 array size is not
included on these targets.
- Fix license files so that they are both included (was fixed in 0.4 before)
- 0.4.5
- Add methods to ``ArrayString`` by @DenialAdams:
- ``.pop() -> Option<char>``
- ``.truncate(new_len)``
- ``.remove(index) -> char``
- Remove dependency on crate odds
- Document debug assertions in unsafe methods better
- 0.4.4
- Add method ``ArrayVec::truncate()`` by @niklasf
- 0.4.3
- Improve performance for ``ArrayVec::extend`` with a lower level
implementation (#74)
- Small cleanup in dependencies (use no std for crates where we don't need more)
- 0.4.2
- Add constructor method ``new`` to ``CapacityError``.
- 0.4.1
- Add ``Default`` impl to ``ArrayString`` by @tbu-
- 0.4.0
- Reformed signatures and error handling by @bluss and @tbu-:
- ``ArrayVec``'s ``push, insert, remove, swap_remove`` now match ``Vec``'s
corresponding signature and panic on capacity errors where applicable.
- Add fallible methods ``try_push, insert`` and checked methods
``pop_at, swap_pop``.
- Similar changes to ``ArrayString``'s push methods.
- Use a local version of the ``RangeArgument`` trait
- Add array sizes 50, 150, 200 by @daboross
- Support serde 1.0 by @daboross
- New method ``.push_unchecked()`` by @niklasf
- ``ArrayString`` implements ``PartialOrd, Ord`` by @tbu-
- Require Rust 1.14
- crate feature ``use_generic_array`` was dropped.
- 0.3.23
- Implement ``PartialOrd, Ord`` as well as ``PartialOrd<str>`` for
@ -101,47 +159,6 @@ Recent Changes (arrayvec)
- 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
=======

View File

@ -0,0 +1,90 @@
extern crate arrayvec;
#[macro_use] extern crate bencher;
use arrayvec::ArrayString;
use bencher::Bencher;
fn try_push_c(b: &mut Bencher) {
let mut v = ArrayString::<[u8; 512]>::new();
b.iter(|| {
v.clear();
while v.try_push('c').is_ok() {
}
v.len()
});
b.bytes = v.capacity() as u64;
}
fn try_push_alpha(b: &mut Bencher) {
let mut v = ArrayString::<[u8; 512]>::new();
b.iter(|| {
v.clear();
while v.try_push('α').is_ok() {
}
v.len()
});
b.bytes = v.capacity() as u64;
}
// Yes, pushing a string char-by-char is slow. Use .push_str.
fn try_push_string(b: &mut Bencher) {
let mut v = ArrayString::<[u8; 512]>::new();
let input = "abcαβγ“”";
b.iter(|| {
v.clear();
for ch in input.chars().cycle() {
if !v.try_push(ch).is_ok() {
break;
}
}
v.len()
});
b.bytes = v.capacity() as u64;
}
fn push_c(b: &mut Bencher) {
let mut v = ArrayString::<[u8; 512]>::new();
b.iter(|| {
v.clear();
while !v.is_full() {
v.push('c');
}
v.len()
});
b.bytes = v.capacity() as u64;
}
fn push_alpha(b: &mut Bencher) {
let mut v = ArrayString::<[u8; 512]>::new();
b.iter(|| {
v.clear();
while !v.is_full() {
v.push('α');
}
v.len()
});
b.bytes = v.capacity() as u64;
}
fn push_string(b: &mut Bencher) {
let mut v = ArrayString::<[u8; 512]>::new();
let input = "abcαβγ“”";
b.iter(|| {
v.clear();
for ch in input.chars().cycle() {
if !v.is_full() {
v.push(ch);
} else {
break;
}
}
v.len()
});
b.bytes = v.capacity() as u64;
}
benchmark_group!(benches, try_push_c, try_push_alpha, try_push_string, push_c,
push_alpha, push_string);
benchmark_main!(benches);

View File

@ -0,0 +1,43 @@
extern crate arrayvec;
#[macro_use] extern crate bencher;
use arrayvec::ArrayVec;
use bencher::Bencher;
fn extend_with_constant(b: &mut Bencher) {
let mut v = ArrayVec::<[u8; 512]>::new();
let cap = v.capacity();
b.iter(|| {
v.clear();
v.extend((0..cap).map(|_| 1));
v[0]
});
b.bytes = v.capacity() as u64;
}
fn extend_with_range(b: &mut Bencher) {
let mut v = ArrayVec::<[u8; 512]>::new();
let cap = v.capacity();
b.iter(|| {
v.clear();
v.extend((0..cap).map(|x| x as _));
v[0]
});
b.bytes = v.capacity() as u64;
}
fn extend_with_slice(b: &mut Bencher) {
let mut v = ArrayVec::<[u8; 512]>::new();
let data = [1; 512];
b.iter(|| {
v.clear();
v.extend(data.iter().cloned());
v[0]
});
b.bytes = v.capacity() as u64;
}
benchmark_group!(benches, extend_with_constant, extend_with_range, extend_with_slice);
benchmark_main!(benches);

View File

@ -1,7 +1,7 @@
/// Trait for fixed size arrays.
pub unsafe trait Array {
/// The array's element type
/// The arrays element type
type Item;
#[doc(hidden)]
/// The smallest index type that indexes the array.
@ -32,24 +32,6 @@ pub trait ArrayExt : Array {
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 }
@ -103,7 +85,9 @@ macro_rules! fix_array_impl_recursive {
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,);
32, 40, 48, 50, 56, 64, 72, 96, 100, 128, 160, 192, 200, 224,);
fix_array_impl_recursive!(u16, 256, 384, 512, 768, 1024, 2048, 4096, 8192, 16384, 32768,);
// This array size doesn't exist on 16-bit
#[cfg(any(target_pointer_width="32", target_pointer_width="64"))]
fix_array_impl_recursive!(u32, 1 << 16,);

View File

@ -12,7 +12,10 @@ use std::slice;
use array::{Array, ArrayExt};
use array::Index;
use CapacityError;
use odds::char::encode_utf8;
use char::encode_utf8;
#[cfg(feature="serde-1")]
use serde::{Serialize, Deserialize, Serializer, Deserializer};
/// A string with a fixed capacity.
///
@ -27,6 +30,13 @@ pub struct ArrayString<A: Array<Item=u8>> {
len: A::Index,
}
impl<A: Array<Item=u8>> Default for ArrayString<A> {
/// Return an empty `ArrayString`
fn default() -> ArrayString<A> {
ArrayString::new()
}
}
impl<A: Array<Item=u8>> ArrayString<A> {
/// Create a new empty `ArrayString`.
///
@ -65,7 +75,7 @@ impl<A: Array<Item=u8>> ArrayString<A> {
/// ```
pub fn from(s: &str) -> Result<Self, CapacityError<&str>> {
let mut arraystr = Self::new();
try!(arraystr.push_str(s));
arraystr.try_push_str(s)?;
Ok(arraystr)
}
@ -81,7 +91,7 @@ impl<A: Array<Item=u8>> ArrayString<A> {
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);
let _result = arraystr.try_push_str(s);
debug_assert!(_result.is_ok());
Ok(arraystr)
}
@ -109,6 +119,24 @@ impl<A: Array<Item=u8>> ArrayString<A> {
/// ```
pub fn is_full(&self) -> bool { self.len() == self.capacity() }
/// Adds the given char to the end of the string.
///
/// ***Panics*** 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');
/// string.push('b');
///
/// assert_eq!(&string[..], "ab");
/// ```
pub fn push(&mut self, c: char) {
self.try_push(c).unwrap();
}
/// Adds the given char to the end of the string.
///
/// Returns `Ok` if the push succeeds.
@ -120,14 +148,14 @@ impl<A: Array<Item=u8>> ArrayString<A> {
///
/// let mut string = ArrayString::<[_; 2]>::new();
///
/// string.push('a').unwrap();
/// string.push('b').unwrap();
/// let overflow = string.push('c');
/// string.try_push('a').unwrap();
/// string.try_push('b').unwrap();
/// let overflow = string.try_push('c');
///
/// assert_eq!(&string[..], "ab");
/// assert_eq!(overflow.unwrap_err().element(), 'c');
/// ```
pub fn push(&mut self, c: char) -> Result<(), CapacityError<char>> {
pub fn try_push(&mut self, c: char) -> Result<(), CapacityError<char>> {
let len = self.len();
unsafe {
match encode_utf8(c, &mut self.raw_mut_bytes()[len..]) {
@ -140,6 +168,24 @@ impl<A: Array<Item=u8>> ArrayString<A> {
}
}
/// Adds the given string slice to the end of the string.
///
/// ***Panics*** 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");
/// string.push_str("d");
///
/// assert_eq!(&string[..], "ad");
/// ```
pub fn push_str(&mut self, s: &str) {
self.try_push_str(s).unwrap()
}
/// Adds the given string slice to the end of the string.
///
/// Returns `Ok` if the push succeeds.
@ -151,16 +197,16 @@ impl<A: Array<Item=u8>> ArrayString<A> {
///
/// 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");
/// string.try_push_str("a").unwrap();
/// let overflow1 = string.try_push_str("bc");
/// string.try_push_str("d").unwrap();
/// let overflow2 = string.try_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>> {
pub fn try_push_str<'a>(&mut self, s: &'a str) -> Result<(), CapacityError<&'a str>> {
if s.len() > self.capacity() - self.len() {
return Err(CapacityError::new(s));
}
@ -174,6 +220,99 @@ impl<A: Array<Item=u8>> ArrayString<A> {
Ok(())
}
/// Removes the last character from the string and returns it.
///
/// Returns `None` if this `ArrayString` is empty.
///
/// ```
/// use arrayvec::ArrayString;
///
/// let mut s = ArrayString::<[_; 3]>::from("foo").unwrap();
///
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('f'));
///
/// assert_eq!(s.pop(), None);
/// ```
#[inline]
pub fn pop(&mut self) -> Option<char> {
let ch = match self.chars().rev().next() {
Some(ch) => ch,
None => return None,
};
let new_len = self.len() - ch.len_utf8();
unsafe {
self.set_len(new_len);
}
Some(ch)
}
/// Shortens this `ArrayString` to the specified length.
///
/// If `new_len` is greater than the strings current length, this has no
/// effect.
///
/// ***Panics*** if `new_len` does not lie on a `char` boundary.
///
/// ```
/// use arrayvec::ArrayString;
///
/// let mut string = ArrayString::<[_; 6]>::from("foobar").unwrap();
/// string.truncate(3);
/// assert_eq!(&string[..], "foo");
/// string.truncate(4);
/// assert_eq!(&string[..], "foo");
/// ```
#[inline]
pub fn truncate(&mut self, new_len: usize) {
if new_len <= self.len() {
assert!(self.is_char_boundary(new_len));
unsafe {
// In libstd truncate is called on the underlying vector,
// which in turns drops each element.
// As we know we don't have to worry about Drop,
// we can just set the length (a la clear.)
self.set_len(new_len);
}
}
}
/// Removes a `char` from this `ArrayString` at a byte position and returns it.
///
/// This is an `O(n)` operation, as it requires copying every element in the
/// array.
///
/// ***Panics*** if `idx` is larger than or equal to the `ArrayString`s length,
/// or if it does not lie on a `char` boundary.
///
/// ```
/// use arrayvec::ArrayString;
///
/// let mut s = ArrayString::<[_; 3]>::from("foo").unwrap();
///
/// assert_eq!(s.remove(0), 'f');
/// assert_eq!(s.remove(1), 'o');
/// assert_eq!(s.remove(0), 'o');
/// ```
#[inline]
pub fn remove(&mut self, idx: usize) -> char {
let ch = match self[idx..].chars().next() {
Some(ch) => ch,
None => panic!("cannot remove a char from the end of a string"),
};
let next = idx + ch.len_utf8();
let len = self.len();
unsafe {
ptr::copy(self.xs.as_ptr().offset(next as isize),
self.xs.as_mut_ptr().offset(idx as isize),
len - next);
self.set_len(len - (next - idx));
}
ch
}
/// Make the string empty.
pub fn clear(&mut self) {
unsafe {
@ -181,12 +320,13 @@ impl<A: Array<Item=u8>> ArrayString<A> {
}
}
/// Set the strings's length.
///
/// May panic if `length` is greater than the capacity.
/// Set the stringss length.
///
/// This function is `unsafe` because it changes the notion of the
/// number of “valid” bytes in the string. Use with care.
///
/// This method uses *debug assertions* to check the validity of `length`
/// and may use other debug assertions.
#[inline]
pub unsafe fn set_len(&mut self, length: usize) {
debug_assert!(length <= self.capacity());
@ -198,7 +338,7 @@ impl<A: Array<Item=u8>> ArrayString<A> {
self
}
/// Return a mutable slice of the whole string's buffer
/// Return a mutable slice of the whole strings buffer
unsafe fn raw_mut_bytes(&mut self) -> &mut [u8] {
slice::from_raw_parts_mut(self.xs.as_mut_ptr(), self.capacity())
}
@ -271,10 +411,11 @@ impl<A: Array<Item=u8>> fmt::Display for ArrayString<A> {
/// `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)
self.try_push(c).map_err(|_| fmt::Error)
}
fn write_str(&mut self, s: &str) -> fmt::Result {
self.push_str(s).map_err(|_| fmt::Error)
self.try_push_str(s).map_err(|_| fmt::Error)
}
}
@ -285,7 +426,7 @@ impl<A: Array<Item=u8> + Copy> Clone for ArrayString<A> {
fn clone_from(&mut self, rhs: &Self) {
// guaranteed to fit due to types matching.
self.clear();
self.push_str(rhs).ok();
self.try_push_str(rhs).ok();
}
}
@ -324,3 +465,50 @@ impl<A: Array<Item=u8>> Ord for ArrayString<A> {
(**self).cmp(&**rhs)
}
}
#[cfg(feature="serde-1")]
/// Requires crate feature `"serde-1"`
impl<A: Array<Item=u8>> Serialize for ArrayString<A> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&*self)
}
}
#[cfg(feature="serde-1")]
/// Requires crate feature `"serde-1"`
impl<'de, A: Array<Item=u8>> Deserialize<'de> for ArrayString<A> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
use serde::de::{self, Visitor};
use std::marker::PhantomData;
struct ArrayStringVisitor<A: Array<Item=u8>>(PhantomData<A>);
impl<'de, A: Array<Item=u8>> Visitor<'de> for ArrayStringVisitor<A> {
type Value = ArrayString<A>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a string no more than {} bytes long", A::capacity())
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: de::Error,
{
ArrayString::from(v).map_err(|_| E::invalid_length(v.len(), &self))
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where E: de::Error,
{
let s = try!(str::from_utf8(v).map_err(|_| E::invalid_value(de::Unexpected::Bytes(v), &self)));
ArrayString::from(s).map_err(|_| E::invalid_length(s.len(), &self))
}
}
deserializer.deserialize_str(ArrayStringVisitor::<A>(PhantomData))
}
}

View File

@ -8,9 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// Original authors: alexchrichton
//! Extra functions for `char`
// Original authors: alexchrichton, bluss
// UTF-8 ranges and tags for encoding characters
const TAG_CONT: u8 = 0b1000_0000;
@ -22,8 +20,7 @@ const MAX_TWO_B: u32 = 0x800;
const MAX_THREE_B: u32 = 0x10000;
/// Placeholder
#[derive(Debug, Copy, Clone)]
pub struct EncodeUtf8Error(());
pub struct EncodeUtf8Error;
/// Encode a char into buf using UTF-8.
///
@ -52,6 +49,6 @@ pub fn encode_utf8(ch: char, buf: &mut [u8]) -> Result<usize, EncodeUtf8Error>
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
return Ok(4);
};
Err(EncodeUtf8Error(()))
Err(EncodeUtf8Error)
}

53
third_party/rust/arrayvec/src/errors.rs vendored Normal file
View File

@ -0,0 +1,53 @@
use std::fmt;
#[cfg(feature="std")]
use std::any::Any;
#[cfg(feature="std")]
use std::error::Error;
/// Error value indicating insufficient capacity
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
pub struct CapacityError<T = ()> {
element: T,
}
impl<T> CapacityError<T> {
/// Create a new `CapacityError` from `element`.
pub 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)
}
}

View File

@ -1,31 +1,33 @@
//! **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:
//! The arrayvec package has the following cargo features:
//!
//! - `std`
//! - Optional, enabled by default
//! - Requires Rust 1.6 *to disable*
//! - Use libstd
//! - Use libstd; disable to use `no_std` instead.
//!
//! - `use_union`
//! - Optional
//! - Requires Rust nightly channel
//! - Experimental: This flag uses nightly so it *may break* unexpectedly
//! at some point; since it doesn't change API this flag may also change
//! to do nothing in the future.
//! - Use the unstable feature untagged unions for the internal implementation,
//! which has reduced space overhead
//!
//! - `use_generic_array`
//! which may have reduced space overhead
//! - `serde-1`
//! - 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/")]
//! - Enable serialization for ArrayVec and ArrayString using serde 1.0
//!
//! ## Rust Version
//!
//! This version of arrayvec requires Rust 1.14 or later.
//!
#![doc(html_root_url="https://docs.rs/arrayvec/0.4/")]
#![cfg_attr(not(feature="std"), no_std)]
extern crate odds;
extern crate nodrop;
#[cfg(feature = "use_generic_array")]
extern crate generic_array;
#[cfg(feature="serde-1")]
extern crate serde;
#[cfg(not(feature="std"))]
extern crate core as std;
@ -47,20 +49,27 @@ 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
#[cfg(not(feature="use_union"))]
use nodrop::NoDrop;
#[cfg(feature="use_union")]
use std::mem::ManuallyDrop as NoDrop;
#[cfg(feature="serde-1")]
use serde::{Serialize, Deserialize, Serializer, Deserializer};
mod array;
mod array_string;
mod char;
mod range;
mod errors;
pub use array::Array;
pub use odds::IndexRange as RangeArgument;
pub use range::RangeArgument;
use array::Index;
pub use array_string::ArrayString;
pub use errors::CapacityError;
unsafe fn new_array<A: Array>() -> A {
@ -98,6 +107,13 @@ impl<A: Array> Drop for ArrayVec<A> {
}
}
macro_rules! panic_oob {
($method_name:expr, $index:expr, $len:expr) => {
panic!(concat!("ArrayVec::", $method_name, ": index {} is out of bounds in vector of length {}"),
$index, $len)
}
}
impl<A: Array> ArrayVec<A> {
/// Create a new empty `ArrayVec`.
///
@ -155,8 +171,7 @@ impl<A: Array> ArrayVec<A> {
/// Push `element` to the end of the vector.
///
/// Return `None` if the push succeeds, or and return `Some(` *element* `)`
/// if the vector is full.
/// ***Panics*** if the vector is already full.
///
/// ```
/// use arrayvec::ArrayVec;
@ -165,53 +180,125 @@ impl<A: Array> ArrayVec<A> {
///
/// 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)
}
pub fn push(&mut self, element: A::Item) {
self.try_push(element).unwrap()
}
/// Insert `element` in position `index`.
/// Push `element` to the end of the vector.
///
/// 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.
/// Return `Ok` if the push succeeds, or return an error if the vector
/// is already full.
///
/// ```
/// 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"]);
/// let push1 = array.try_push(1);
/// let push2 = array.try_push(2);
///
/// assert!(push1.is_ok());
/// assert!(push2.is_ok());
///
/// assert_eq!(&array[..], &[1, 2]);
///
/// let overflow = array.try_push(3);
///
/// assert!(overflow.is_err());
/// ```
pub fn try_push(&mut self, element: A::Item) -> Result<(), CapacityError<A::Item>> {
if self.len() < A::capacity() {
unsafe {
self.push_unchecked(element);
}
Ok(())
} else {
Err(CapacityError::new(element))
}
}
/// Push `element` to the end of the vector without checking the capacity.
///
/// It is up to the caller to ensure the capacity of the vector is
/// sufficiently large.
///
/// This method uses *debug assertions* to check that the arrayvec is not full.
///
/// ```
pub fn insert(&mut self, index: usize, element: A::Item) -> Option<A::Item> {
if index > self.len() || index == self.capacity() {
return Some(element);
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::<[_; 2]>::new();
///
/// if array.len() + 2 <= array.capacity() {
/// unsafe {
/// array.push_unchecked(1);
/// array.push_unchecked(2);
/// }
/// }
///
/// assert_eq!(&array[..], &[1, 2]);
/// ```
#[inline]
pub unsafe fn push_unchecked(&mut self, element: A::Item) {
let len = self.len();
debug_assert!(len < A::capacity());
ptr::write(self.get_unchecked_mut(len), element);
self.set_len(len + 1);
}
/// Insert `element` at position `index`.
///
/// Shift up all elements after `index`.
///
/// It is an error if the index is greater than the length or if the
/// arrayvec is full.
///
/// ***Panics*** on errors. See `try_result` for fallible version.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::<[_; 2]>::new();
///
/// array.insert(0, "x");
/// array.insert(0, "y");
/// assert_eq!(&array[..], &["y", "x"]);
///
/// ```
pub fn insert(&mut self, index: usize, element: A::Item) {
self.try_insert(index, element).unwrap()
}
/// Insert `element` at position `index`.
///
/// Shift up all elements after `index`; the `index` must be less than
/// or equal to the length.
///
/// Returns an error if vector is already at full capacity.
///
/// ***Panics*** `index` is out of bounds.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::<[_; 2]>::new();
///
/// assert!(array.try_insert(0, "x").is_ok());
/// assert!(array.try_insert(0, "y").is_ok());
/// assert!(array.try_insert(0, "z").is_err());
/// assert_eq!(&array[..], &["y", "x"]);
///
/// ```
pub fn try_insert(&mut self, index: usize, element: A::Item) -> Result<(), CapacityError<A::Item>> {
if index > self.len() {
panic_oob!("try_insert", index, self.len())
}
let mut ret = None;
if self.len() == self.capacity() {
ret = self.pop();
return Err(CapacityError::new(element));
}
let len = self.len();
@ -229,10 +316,10 @@ impl<A: Array> ArrayVec<A> {
}
self.set_len(len + 1);
}
ret
Ok(())
}
/// Remove the last element in the vector.
/// Remove the last element in the vector and return it.
///
/// Return `Some(` *element* `)` if the vector is non-empty, else `None`.
///
@ -261,6 +348,33 @@ impl<A: Array> ArrayVec<A> {
///
/// This operation is O(1).
///
/// Return the *element* if the index is in bounds, else panic.
///
/// ***Panics*** if the `index` is out of bounds.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::from([1, 2, 3]);
///
/// assert_eq!(array.swap_remove(0), 1);
/// assert_eq!(&array[..], &[3, 2]);
///
/// assert_eq!(array.swap_remove(1), 2);
/// assert_eq!(&array[..], &[3]);
/// ```
pub fn swap_remove(&mut self, index: usize) -> A::Item {
self.swap_pop(index)
.unwrap_or_else(|| {
panic_oob!("swap_remove", index, self.len())
})
}
/// Remove the element at `index` and swap the last element into its place.
///
/// This is a checked version of `.swap_remove`.
/// This operation is O(1).
///
/// Return `Some(` *element* `)` if the index is in bounds, else `None`.
///
/// ```
@ -268,15 +382,15 @@ impl<A: Array> ArrayVec<A> {
///
/// let mut array = ArrayVec::from([1, 2, 3]);
///
/// assert_eq!(array.swap_remove(0), Some(1));
/// assert_eq!(array.swap_pop(0), Some(1));
/// assert_eq!(&array[..], &[3, 2]);
///
/// assert_eq!(array.swap_remove(10), None);
/// assert_eq!(array.swap_pop(10), None);
/// ```
pub fn swap_remove(&mut self, index: usize) -> Option<A::Item> {
pub fn swap_pop(&mut self, index: usize) -> Option<A::Item> {
let len = self.len();
if index >= len {
return None
return None;
}
self.swap(index, len - 1);
self.pop()
@ -284,19 +398,43 @@ impl<A: Array> ArrayVec<A> {
/// Remove the element at `index` and shift down the following elements.
///
/// Return `Some(` *element* `)` if the index is in bounds, else `None`.
/// The `index` must be strictly less than the length of the vector.
///
/// ***Panics*** if the `index` is out of bounds.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::from([1, 2, 3]);
///
/// assert_eq!(array.remove(0), Some(1));
/// let removed_elt = array.remove(0);
/// assert_eq!(removed_elt, 1);
/// assert_eq!(&array[..], &[2, 3]);
/// ```
pub fn remove(&mut self, index: usize) -> A::Item {
self.pop_at(index)
.unwrap_or_else(|| {
panic_oob!("remove", index, self.len())
})
}
/// Remove the element at `index` and shift down the following elements.
///
/// This is a checked version of `.remove(index)`. Returns `None` if there
/// is no element at `index`. Otherwise, return the element inside `Some`.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::from([1, 2, 3]);
///
/// assert!(array.pop_at(0).is_some());
/// assert_eq!(&array[..], &[2, 3]);
///
/// assert_eq!(array.remove(10), None);
/// assert!(array.pop_at(2).is_none());
/// assert!(array.pop_at(10).is_none());
/// ```
pub fn remove(&mut self, index: usize) -> Option<A::Item> {
pub fn pop_at(&mut self, index: usize) -> Option<A::Item> {
if index >= self.len() {
None
} else {
@ -304,6 +442,25 @@ impl<A: Array> ArrayVec<A> {
}
}
/// Shortens the vector, keeping the first `len` elements and dropping
/// the rest.
///
/// If `len` is greater than the vectors current length this has no
/// effect.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::from([1, 2, 3, 4, 5]);
/// array.truncate(3);
/// assert_eq!(&array[..], &[1, 2, 3]);
/// array.truncate(4);
/// assert_eq!(&array[..], &[1, 2, 3]);
/// ```
pub fn truncate(&mut self, len: usize) {
while self.len() > len { self.pop(); }
}
/// Remove all elements in the vector.
pub fn clear(&mut self) {
while let Some(_) = self.pop() { }
@ -343,12 +500,13 @@ impl<A: Array> ArrayVec<A> {
}
}
/// Set the vector's length without dropping or moving out elements
/// Set the vectors 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
/// This method is `unsafe` because it changes the notion of the
/// number of “valid” elements in the vector. Use with care.
///
/// This method uses *debug assertions* to check that check that `length` is
/// not greater than the capacity.
#[inline]
pub unsafe fn set_len(&mut self, length: usize) {
debug_assert!(length <= self.capacity());
@ -370,7 +528,7 @@ impl<A: Array> ArrayVec<A> {
/// use arrayvec::ArrayVec;
///
/// let mut v = ArrayVec::from([1, 2, 3]);
/// let u: Vec<_> = v.drain(0..2).collect();
/// let u: ArrayVec<[_; 3]> = v.drain(0..2).collect();
/// assert_eq!(&v[..], &[3]);
/// assert_eq!(&u[..], &[1, 2]);
/// ```
@ -666,6 +824,21 @@ impl<'a, A: Array> Drop for Drain<'a, A>
}
}
struct ScopeExitGuard<T, Data, F>
where F: FnMut(&Data, &mut T)
{
value: T,
data: Data,
f: F,
}
impl<T, Data, F> Drop for ScopeExitGuard<T, Data, F>
where F: FnMut(&Data, &mut T)
{
fn drop(&mut self) {
(self.f)(&self.data, &mut self.value)
}
}
@ -676,8 +849,25 @@ impl<'a, A: Array> Drop for Drain<'a, A>
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);
unsafe {
let len = self.len();
let mut ptr = self.as_mut_ptr().offset(len as isize);
// Keep the length in a separate variable, write it back on scope
// exit. To help the compiler with alias analysis and stuff.
// We update the length to handle panic in the iteration of the
// user's iterator, without dropping any elements on the floor.
let mut guard = ScopeExitGuard {
value: self,
data: len,
f: |&len, self_| {
self_.set_len(len)
}
};
for elt in iter.into_iter().take(take) {
ptr::write(ptr, elt);
ptr = ptr.offset(1);
guard.data += 1;
}
}
}
}
@ -771,6 +961,7 @@ impl<A: Array> fmt::Debug for ArrayVec<A> where A::Item: fmt::Debug {
}
impl<A: Array> Default for ArrayVec<A> {
/// Return an empty array
fn default() -> ArrayVec<A> {
ArrayVec::new()
}
@ -829,48 +1020,49 @@ impl<A: Array<Item=u8>> io::Write for ArrayVec<A> {
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,
#[cfg(feature="serde-1")]
/// Requires crate feature `"serde-1"`
impl<T: Serialize, A: Array<Item=T>> Serialize for ArrayVec<A> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.collect_seq(self)
}
}
impl<T> CapacityError<T> {
fn new(element: T) -> CapacityError<T> {
CapacityError {
element: element,
#[cfg(feature="serde-1")]
/// Requires crate feature `"serde-1"`
impl<'de, T: Deserialize<'de>, A: Array<Item=T>> Deserialize<'de> for ArrayVec<A> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
use serde::de::{Visitor, SeqAccess, Error};
use std::marker::PhantomData;
struct ArrayVecVisitor<'de, T: Deserialize<'de>, A: Array<Item=T>>(PhantomData<(&'de (), T, A)>);
impl<'de, T: Deserialize<'de>, A: Array<Item=T>> Visitor<'de> for ArrayVecVisitor<'de, T, A> {
type Value = ArrayVec<A>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "an array with no more than {} items", A::capacity())
}
fn visit_seq<SA>(self, mut seq: SA) -> Result<Self::Value, SA::Error>
where SA: SeqAccess<'de>,
{
let mut values = ArrayVec::<A>::new();
while let Some(value) = try!(seq.next_element()) {
if let Err(_) = values.try_push(value) {
return Err(SA::Error::invalid_length(A::capacity() + 1, &self));
}
}
Ok(values)
}
}
}
/// 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)
deserializer.deserialize_seq(ArrayVecVisitor::<T, A>(PhantomData))
}
}

42
third_party/rust/arrayvec/src/range.rs vendored Normal file
View File

@ -0,0 +1,42 @@
use std::ops::{
RangeFull,
RangeFrom,
RangeTo,
Range,
};
/// `RangeArgument` is implemented by Rust's built-in range types, produced
/// by range syntax like `..`, `a..`, `..b` or `c..d`.
///
/// Note: This is arrayvec's provisional trait, waiting for stable Rust to
/// provide an equivalent.
pub trait RangeArgument {
#[inline]
/// Start index (inclusive)
fn start(&self) -> Option<usize> { None }
#[inline]
/// End index (exclusive)
fn end(&self) -> Option<usize> { None }
}
impl RangeArgument for RangeFull {}
impl RangeArgument for RangeFrom<usize> {
#[inline]
fn start(&self) -> Option<usize> { Some(self.start) }
}
impl RangeArgument for RangeTo<usize> {
#[inline]
fn end(&self) -> Option<usize> { Some(self.end) }
}
impl RangeArgument for Range<usize> {
#[inline]
fn start(&self) -> Option<usize> { Some(self.start) }
#[inline]
fn end(&self) -> Option<usize> { Some(self.end) }
}

View File

@ -1,23 +0,0 @@
#![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]);
}

View File

@ -0,0 +1,79 @@
#![cfg(feature = "serde-1")]
extern crate arrayvec;
extern crate serde_test;
mod array_vec {
use arrayvec::ArrayVec;
use serde_test::{Token, assert_tokens, assert_de_tokens_error};
#[test]
fn test_ser_de_empty() {
let vec = ArrayVec::<[u32; 0]>::new();
assert_tokens(&vec, &[
Token::Seq { len: Some(0) },
Token::SeqEnd,
]);
}
#[test]
fn test_ser_de() {
let mut vec = ArrayVec::<[u32; 3]>::new();
vec.push(20);
vec.push(55);
vec.push(123);
assert_tokens(&vec, &[
Token::Seq { len: Some(3) },
Token::U32(20),
Token::U32(55),
Token::U32(123),
Token::SeqEnd,
]);
}
#[test]
fn test_de_too_large() {
assert_de_tokens_error::<ArrayVec<[u32; 2]>>(&[
Token::Seq { len: Some(3) },
Token::U32(13),
Token::U32(42),
Token::U32(68),
], "invalid length 3, expected an array with no more than 2 items");
}
}
mod array_string {
use arrayvec::ArrayString;
use serde_test::{Token, assert_tokens, assert_de_tokens_error};
#[test]
fn test_ser_de_empty() {
let string = ArrayString::<[u8; 0]>::new();
assert_tokens(&string, &[
Token::Str(""),
]);
}
#[test]
fn test_ser_de() {
let string = ArrayString::<[u8; 9]>::from("1234 abcd")
.expect("expected exact specified capacity to be enough");
assert_tokens(&string, &[
Token::Str("1234 abcd"),
]);
}
#[test]
fn test_de_too_large() {
assert_de_tokens_error::<ArrayString<[u8; 2]>>(&[
Token::Str("afd")
], "invalid length 3, expected a string no more than 2 bytes long");
}
}

View File

@ -1,8 +1,10 @@
extern crate arrayvec;
#[macro_use] extern crate matches;
use arrayvec::ArrayVec;
use arrayvec::ArrayString;
use std::mem;
use arrayvec::CapacityError;
use std::collections::HashMap;
@ -30,9 +32,9 @@ 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.try_push(1u8).is_ok());
}
assert!(vec.push(0).is_some());
assert!(vec.try_push(0).is_err());
assert_eq!(vec.len(), N);
}
@ -77,7 +79,9 @@ fn test_drop() {
array.push(vec![Bump(flag)]);
array.push(vec![Bump(flag), Bump(flag)]);
array.push(vec![]);
array.push(vec![Bump(flag)]);
let push4 = array.try_push(vec![Bump(flag)]);
assert_eq!(flag.get(), 0);
drop(push4);
assert_eq!(flag.get(), 1);
drop(array.pop());
assert_eq!(flag.get(), 1);
@ -217,32 +221,25 @@ fn test_drop_panic_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));
assert_matches!(v.try_push(1), Err(_));
let mut v = ArrayVec::<[_; 3]>::new();
v.insert(0, 0);
v.insert(1, 1);
//let ret1 = v.try_insert(3, 3);
//assert_matches!(ret1, Err(InsertError::OutOfBounds(_)));
assert_eq!(&v[..], &[0, 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 ret2 = v.try_insert(1, 9);
assert_eq!(&v[..], &[0, 1, 2]);
assert_matches!(ret2, Err(_));
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());
assert_matches!(v.try_insert(0, 1), Err(CapacityError { .. }));
assert_matches!(v.try_insert(1, 1), Err(CapacityError { .. }));
//assert_matches!(v.try_insert(2, 1), Err(CapacityError { .. }));
}
#[test]
@ -310,7 +307,7 @@ fn test_string() {
let text = "hello world";
let mut s = ArrayString::<[_; 16]>::new();
s.push_str(text).unwrap();
s.try_push_str(text).unwrap();
assert_eq!(&s, text);
assert_eq!(text, &s);
@ -320,10 +317,10 @@ fn test_string() {
assert_eq!(map[text], 1);
let mut t = ArrayString::<[_; 2]>::new();
assert!(t.push_str(text).is_err());
assert!(t.try_push_str(text).is_err());
assert_eq!(&t, "");
t.push_str("ab").unwrap();
t.push_str("ab");
// DerefMut
let tmut: &mut str = &mut t;
assert_eq!(tmut, "ab");
@ -331,7 +328,7 @@ fn test_string() {
// Test Error trait / try
let t = || -> Result<(), Box<Error>> {
let mut t = ArrayString::<[_; 2]>::new();
try!(t.push_str(text));
try!(t.try_push_str(text));
Ok(())
}();
assert!(t.is_err());
@ -358,7 +355,7 @@ fn test_string_from_bytes() {
fn test_string_clone() {
let text = "hi";
let mut s = ArrayString::<[_; 4]>::new();
s.push_str("abcd").unwrap();
s.push_str("abcd");
let t = ArrayString::<[_; 4]>::from(text).unwrap();
s.clone_from(&t);
assert_eq!(&t, &s);
@ -369,42 +366,44 @@ fn test_string_push() {
let text = "abcαβγ";
let mut s = ArrayString::<[_; 8]>::new();
for c in text.chars() {
if let Err(_) = s.push(c) {
if let Err(_) = s.try_push(c) {
break;
}
}
assert_eq!("abcαβ", &s[..]);
s.push('x').ok();
s.push('x');
assert_eq!("abcαβx", &s[..]);
assert!(s.push('x').is_err());
assert!(s.try_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());
let result1 = v.try_insert(0, "a");
let result2 = v.try_insert(1, "b");
assert!(result1.is_ok() && result2.is_ok());
assert_eq!(&v[..], &["a", "b"]);
}
#[should_panic]
#[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));
let _ = v.try_insert(1, "test");
}
/*
* insert that pushes out the last
let mut u = ArrayVec::from([1, 2, 3, 4]);
let ret = u.try_insert(3, 99);
assert_eq!(&u[..], &[1, 2, 3, 99]);
assert_matches!(ret, Err(_));
let ret = u.try_insert(4, 77);
assert_eq!(&u[..], &[1, 2, 3, 99]);
assert_matches!(ret, Err(_));
*/
#[test]
fn test_drop_in_insert() {
use std::cell::Cell;
@ -427,17 +426,43 @@ fn test_drop_in_insert() {
array.push(Bump(flag));
array.insert(0, Bump(flag));
assert_eq!(flag.get(), 0);
let ret = array.insert(1, Bump(flag));
let ret = array.try_insert(1, Bump(flag));
assert_eq!(flag.get(), 0);
assert!(ret.is_some());
assert_matches!(ret, Err(_));
drop(ret);
assert_eq!(flag.get(), 1);
}
assert_eq!(flag.get(), 3);
}
#[test]
fn test_pop_at() {
let mut v = ArrayVec::<[String; 4]>::new();
let s = String::from;
v.push(s("a"));
v.push(s("b"));
v.push(s("c"));
v.push(s("d"));
assert_eq!(v.pop_at(4), None);
assert_eq!(v.pop_at(1), Some(s("b")));
assert_eq!(v.pop_at(1), Some(s("c")));
assert_eq!(v.pop_at(2), None);
assert_eq!(&v[..], &["a", "d"]);
}
#[test]
fn test_sizes() {
let v = ArrayVec::from([0u8; 1 << 16]);
assert_eq!(vec![0u8; v.len()], &v[..]);
}
#[test]
fn test_default() {
use std::net;
let s: ArrayString<[u8; 4]> = Default::default();
// Something without `Default` implementation.
let v: ArrayVec<[net::TcpStream; 4]> = Default::default();
assert_eq!(s.len(), 0);
assert_eq!(v.len(), 0);
}

View File

@ -1 +1 @@
{"files":{"Cargo.toml":"824532e5f3a5ae93bb793e596b027cb8d2f58081daf13338c2e38cf37c45eb3e","src/lib.rs":"af65dcd2a028bc4420bca139f8dd37922f9e101f717e117f4b0ef66a8d70711c"},"package":"52cd74cd09beba596430cc6e3091b74007169a56246e1262f0ba451ea95117b2"}
{"files":{"Cargo.toml":"518e2e6cea4cec4804a6fc04c8138a2db95783cbc13e0b49526553232f7b9699","README.rst":"68844a4fd6edead8ecd0c0053a8618f89fc5bbe8bc1ee000808358f6f0f4d8ff","src/lib.rs":"96d5ddaf03ccbdff8ddcd79b5fdc015aad4451a8d76d0b9a94dff14f49e2dcc9"},"package":"9a2228dca57108069a5262f2ed8bd2e82496d2e074a06d1ccc7ce1687b6ae0a2"}

View File

@ -1,35 +1,33 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g. crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
name = "nodrop"
version = "0.1.9"
version = "0.1.12"
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"
description = "A wrapper type to inhibit drop (destructor). Use std::mem::ManuallyDrop instead!"
documentation = "https://docs.rs/nodrop/"
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
categories = ["rust-patterns"]
license = "MIT/Apache-2.0"
repository = "https://github.com/bluss/arrayvec"
[package.metadata.release]
no-dev-version = true
[dependencies.nodrop-union]
path = "../nodrop-union"
version = "0.1.8"
optional = true
[features]
std = []
use_union = ["nodrop-union"]
use_needs_drop = []
default = ["std"]

58
third_party/rust/nodrop/README.rst vendored Normal file
View File

@ -0,0 +1,58 @@
nodrop
======
Recent Changes (nodrop)
-----------------------
- 0.1.12
- Remove dependency on crate odds.
- 0.1.11
- Remove erronous assertion in test (#77)
- 0.1.10
- Update for stable ``needs_drop`` (Rust 1.21, was nightly only)
- 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.
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.

View File

@ -3,11 +3,10 @@
//!
//! - `std`
//! - Optional, enabled by default
//! - Requires Rust 1.6 *to disable*
//! - Use libstd
//! - `use_needs_drop`
//! - Optional
//! - Requires nightly channel.
//! - Requires Rust 1.21
//! - Use `needs_drop` to skip overwriting if not necessary
//! - `use_union`
//! - Optional
@ -16,15 +15,10 @@
//! 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;
@ -33,7 +27,6 @@ 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};
@ -81,7 +74,7 @@ mod imp {
#[inline]
fn needs_drop<T>() -> bool {
unsafe {
::std::intrinsics::needs_drop::<T>()
::std::mem::needs_drop::<T>()
}
}
@ -127,7 +120,14 @@ mod imp {
// 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>>());
}
// copying this code saves us microcrate deps
#[inline]
unsafe fn debug_assert_unreachable() -> ! {
debug_assert!(false, "Reached unreachable section: this is a bug!");
enum Void { }
match *(1 as *const Void) { }
}
}

View File

@ -1 +0,0 @@
{"files":{".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"}

View File

@ -1,24 +0,0 @@
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"

View File

@ -1,28 +0,0 @@
[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

View File

@ -1,162 +0,0 @@
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.

View File

@ -1,400 +0,0 @@
#![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 = "\
Брутэ дольорэ компрэхэнжам йн эжт, ючю коммюны дылыктуч эа, квюо льаорыыт вёвындо мэнандря экз. Ед ыюм емпыдит аккюсам, нык дйкит ютенам ад. Хаж аппэтырэ хонэзтатёз нэ. Ад мовэт путант юрбанйтаж вяш.
Коммодо квюальизквюэ абхоррэант нэ ыюм, праэчынт еракюндйа ылаборарэт эю мыа. Нэ квуым жюмо вольуптатибюж вяш, про ыт бонорюм вёвындо, мэя юллюм новум ку. Пропрёаы такематыш атоморюм зыд ан. Эи омнэжквюы оффекйяж компрэхэнжам жят, апыирёан конкыптам ёнкорруптэ ючю ыт.
Жят алёа лэгыры ед, эи мацим оффэндйт вим. Нык хёнк льаборэж йн, зыд прима тимэам ан. Векж нужквюам инимёкюж ты, ыам эа омнеж ырант рэформйданч. Эрож оффекйяж эю вэл.
Ад нам ножтрюд долорюм, еюж ут вэрыар эюрйпйдяч. Квюач аффэрт тинкидюнт про экз, дёкант вольуптатибюж ат зыд. Ыт зыд экшырки констятюам. Квюо квюиж юрбанйтаж ометтантур экз, хёз экз мютат граэкы рыкючабо, нэ прё пюрто элитр пэрпэтюа. Но квюандо минемум ыам.
Амэт лыгимуз ометтантур кюм ан. Витюпырата котёдиэквюэ нам эю, эю вокынт алёквюам льебэравичсы жят. Экз пыртенакж янтэрэсщэт инзтруктеор нам, еюж ад дйкит каючаэ, шэа витаэ конжтетуто ут. Квюач мандамюч кюм ат, но ёнкорруптэ рэформйданч ючю, незл либриз аюдирэ зыд эи. Ты эож аугюэ иреуры льюкяльиюч, мэль алььтыра докэндё омнэжквюы ат. Анёмал жямиляквюы аккоммодары ыам нэ, экз пэрчёус дэфянятйоныс квюо. Эи дуо фюгит маиорюм.
Эвэртё партйэндо пытынтёюм ыюм ан, шэа ку промпта квюаырэндум. Агам дикунт вим ку. Мюкиуж аюдиам тамквюам про ут, ку мыа квюод квюот эррэм, вяш ад номинави зючкёпит янжольэнж. Нык эи пожжёт путант эффякиантур. Ку еюж нощтыр контынтёонэж. Кюм йужто харюм ёужто ад, ыюм оратио квюоджё экз.
Чонэт факэтэ кюм ан, вэре факэр зальютатуж мэя но. Ыюм ут зальы эффикеэнди, экз про алиё конжыквуюнтюр. Квуй ыльит хабымуч ты, алёа омнэжквюы мандамюч шэа ыт, пльакырат аккюжамюз нэ мэль. Хаж нэ партым нюмквуам прёнкипыз, ат импэрдеэт форынчйбюж кончэктэтюыр шэа. Пльакырат рэформйданч эи векж, ючю дюиж фюйзчыт эи.
Экз квюо ажжюм аугюэ, ат нык мёнём анёмал кытэрож. Кюм выльёт эрюдитя эа. Йн порро малйж кончэктэтюыр хёз, жят кашы эрюдитя ат. Эа вяш мацим пыртенакж, но порро утамюр дяшзынтиыт кюм. Ыт мютат зючкёпит эож, нэ про еракюндйа котёдиэквюэ. Квуй лаудым плььатонэм ед, ку вим ножтрюм лаборамюз.
Вёжи янвыняры хаж ед, ты нолюёжжэ индоктум квуй. Квюач тебиквюэ ут жят, тальэ адхюк убяквюэ йн эож. Ыррор бландит вяш ан, ютроквюы нолюёжжэ констятюам йн ыюм, жят эи прима нобёз тхэопхражтуз. Ты дёкант дэльэнйт нолюёжжэ пэр, молыжтйаы модыратиюз интыллыгам ку мэль.
Ад ылаборарэт конжыквуюнтюр ентырпрытаряш прё, факэтэ лыгэндоч окюррырэт вим ад, элитр рэформйданч квуй ед. Жюмо зальы либриз мэя ты. Незл зюаз видишчы ан ыюм, но пожжэ молыжтйаы мэль. Фиэрэнт адипижкй ометтантур квюо экз. Ут мольлиз пырикюлёз квуй. Ыт квюиж граэко рыпудяары жят, вим магна обльйквюэ контынтёонэж эю, ты шэа эним компльыктётюр.
";

View File

@ -1,44 +0,0 @@
#![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;
}

View File

@ -1,116 +0,0 @@
#![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;
}

View File

@ -1,115 +0,0 @@
/// 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)
}
}

View File

@ -1,197 +0,0 @@
//! 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]);
}
}
}

View File

@ -1,39 +0,0 @@
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) }
}

View File

@ -1,119 +0,0 @@
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)
}
}
}

View File

@ -1,985 +0,0 @@
//! 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]));
}
}
}

View File

@ -1,121 +0,0 @@
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);
}

View File

@ -1,303 +0,0 @@
//! 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
}
}
}

View File

@ -1,375 +0,0 @@
//! 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, "αγ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(""));
}

View File

@ -1,215 +0,0 @@
//! 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]);
}

View File

@ -1,88 +0,0 @@
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))
}
}

View File

@ -1,151 +0,0 @@
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];
}

View File

@ -1,32 +0,0 @@
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!["α", "αβ", "β", "αβγ", "βγ", "γ"]);
}

View File

@ -1 +1 @@
{"files":{"Cargo.toml":"72d1bc733f846bd09ec1388588a9f1235aa90984c3bbc36f019e325315787335","README.md":"190ef26732fa5c46032905dc3b4fa6bb27df3e6e7d7f6c924bdd59c389f1edbb","lib.rs":"2581cf44dadb6b1287478b30f5c41bdbe7acd165bd8dbd63b1a48e065c7b0dab"},"package":"cd28fce445fd48f4e2c10ab0d3d8f6a646b11fd2b05228fa94fc83cf69ad6e98"}
{"files":{"Cargo.toml":"7c10953d660c87fe16c4bf1936007deadebe6832ff81adadb962acf1a87c5432","LICENSE":"3db78572e8657cca9e9446ce56a057b8a981eb41af318c49a5fe08e7a10fa52a","README.md":"de12b77db6f2e0a9e8c3d0c16dc0e23e3d97d7b93010d522552339f619a5e4c1","lib.rs":"125207560eb1b29d06869e7c24da2daba6c19a5c51d33c2377e710de4fb553b0","tests.rs":"3bc80e05bdc7b95fc4443f0b2face27c9ce36a16ee697183328d441c82c7a951"},"package":"519130f0ea964ba540a9d8af1373738c2226f1d465eda07e61db29feb5479db9"}

View File

@ -12,13 +12,18 @@
[package]
name = "uluru"
version = "0.1.0"
version = "0.2.0"
authors = ["The Servo Project Developers"]
description = "A simple, fast, LRU cache implementation"
readme = "README.md"
keywords = ["cache", "linkedlist", "array", "no_std"]
categories = ["data-structures", "no-std"]
license = "MPL-2.0"
repository = "https://github.com/servo/uluru"
[lib]
name = "uluru"
path = "lib.rs"
[dependencies.arrayvec]
version = "0.3.20"
version = "0.4.6"
default-features = false

373
third_party/rust/uluru/LICENSE vendored Normal file
View File

@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@ -1,3 +1,3 @@
# uluru
A simple, fast, LRU cache implementation used for Servo's style system.
A simple, fast, least-recently-used (LRU) cache implementation used for Servo's style system.

View File

@ -2,18 +2,28 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A simple LRU cache.
#![no_std]
//! A simple least-recently-used (LRU) cache.
extern crate arrayvec;
use arrayvec::{Array, ArrayVec};
#[cfg(test)] mod tests;
/// A LRU cache using a statically-sized array for storage.
///
/// The most-recently-used entry is at index `head`. The entries form a linked list, linked to each
/// other by indices within the `entries` array. After an entry is added to the array, its index
/// never changes, so these links are never invalidated.
pub struct LRUCache<T, A: Array<Item=Entry<T>>> {
/// `LRUCache` uses a fixed-capacity array for storage. It provides `O(1)` insertion, and `O(n)`
/// lookup.
///
/// All items are stored inline within the `LRUCache`, so it does not impose any heap allocation or
/// indirection. A linked list is used to record the cache order, so the items themselves do not
/// need to be moved when the order changes. (This is important for speed if the items are large.)
pub struct LRUCache<A: Array> {
/// The most-recently-used entry is at index `head`. The entries form a linked list, linked to
/// each other by indices within the `entries` array. After an entry is added to the array,
/// its index never changes, so these links are never invalidated.
entries: ArrayVec<A>,
/// Index of the first entry. If the cache is empty, ignore this field.
head: u16,
@ -33,7 +43,7 @@ pub struct Entry<T> {
next: u16,
}
impl<T, A: Array<Item=Entry<T>>> Default for LRUCache<T, A> {
impl<A: Array> Default for LRUCache<A> {
fn default() -> Self {
let cache = LRUCache {
entries: ArrayVec::new(),
@ -45,7 +55,7 @@ impl<T, A: Array<Item=Entry<T>>> Default for LRUCache<T, A> {
}
}
impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> {
impl<T, A: Array<Item=Entry<T>>> LRUCache<A> {
/// Returns the number of elements in the cache.
pub fn num_entries(&self) -> usize {
self.entries.len()
@ -72,7 +82,7 @@ impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> {
/// Iterate over the contents of this cache, from more to less recently
/// used.
pub fn iter(&self) -> LRUCacheIterator<T, A> {
pub fn iter(&self) -> LRUCacheIterator<A> {
LRUCacheIterator {
pos: self.head,
done: self.entries.len() == 0,
@ -81,7 +91,7 @@ impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> {
}
/// Iterate mutably over the contents of this cache.
pub fn iter_mut(&mut self) -> LRUCacheMutIterator<T, A> {
pub fn iter_mut(&mut self) -> LRUCacheMutIterator<A> {
LRUCacheMutIterator {
pos: self.head,
done: self.entries.len() == 0,
@ -107,14 +117,30 @@ impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> {
None => None,
Some((i, r)) => {
self.touch(i);
let front = self.front_mut().unwrap();
debug_assert!(test_one(front).is_some());
Some(r)
}
}
}
/// Returns the first item in the cache that matches the given predicate.
/// Touches the result on a hit.
pub fn find<F>(&mut self, mut pred: F) -> Option<&mut T>
where
F: FnMut(&T) -> bool
{
match self.iter_mut().find(|&(_, ref x)| pred(x)) {
Some((i, _)) => {
self.touch(i);
self.front_mut()
}
None => None
}
}
/// Insert a given key in the cache.
///
/// This item becomes the front (most-recently-used) item in the cache. If the cache is full,
/// the back (least-recently-used) item will be removed.
pub fn insert(&mut self, val: T) {
let entry = Entry { val, prev: 0, next: 0 };
@ -131,7 +157,7 @@ impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> {
self.push_front(new_head);
}
/// Remove an from the linked list.
/// Remove an entry from the linked list.
///
/// Note: This only unlinks the entry from the list; it does not remove it from the array.
fn remove(&mut self, i: u16) {
@ -179,13 +205,13 @@ impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> {
}
/// Immutable iterator over values in an LRUCache, from most-recently-used to least-recently-used.
pub struct LRUCacheIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> {
cache: &'a LRUCache<T, A>,
pub struct LRUCacheIterator<'a, A: 'a + Array> {
cache: &'a LRUCache<A>,
pos: u16,
done: bool,
}
impl<'a, T, A> Iterator for LRUCacheIterator<'a, T, A>
impl<'a, T, A> Iterator for LRUCacheIterator<'a, A>
where T: 'a,
A: 'a + Array<Item=Entry<T>>
{
@ -207,13 +233,13 @@ where T: 'a,
}
/// Mutable iterator over values in an LRUCache, from most-recently-used to least-recently-used.
pub struct LRUCacheMutIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> {
cache: &'a mut LRUCache<T, A>,
pub struct LRUCacheMutIterator<'a, A: 'a + Array> {
cache: &'a mut LRUCache<A>,
pos: u16,
done: bool,
}
impl<'a, T, A> Iterator for LRUCacheMutIterator<'a, T, A>
impl<'a, T, A> Iterator for LRUCacheMutIterator<'a, A>
where T: 'a,
A: 'a + Array<Item=Entry<T>>
{

81
third_party/rust/uluru/tests.rs vendored Normal file
View File

@ -0,0 +1,81 @@
extern crate std;
use self::std::vec::Vec;
use super::*;
type TestCache = LRUCache<[Entry<i32>; 4]>;
/// Convenience function for test assertions
fn items<T, A>(cache: &LRUCache<A>) -> Vec<T>
where
T: Clone,
A: Array<Item=Entry<T>>
{
cache.iter().map(|(_, x)| x.clone()).collect()
}
#[test]
fn empty() {
let cache = TestCache::default();
assert_eq!(cache.num_entries(), 0);
assert_eq!(items(&cache), []);
}
#[test]
fn insert() {
let mut cache = TestCache::default();
cache.insert(1);
assert_eq!(cache.num_entries(), 1);
cache.insert(2);
assert_eq!(cache.num_entries(), 2);
cache.insert(3);
assert_eq!(cache.num_entries(), 3);
cache.insert(4);
assert_eq!(cache.num_entries(), 4);
assert_eq!(items(&cache), [4, 3, 2, 1], "Ordered from most- to least-recent.");
cache.insert(5);
assert_eq!(cache.num_entries(), 4);
assert_eq!(items(&cache), [5, 4, 3, 2], "Least-recently-used item evicted.");
cache.insert(6);
cache.insert(7);
cache.insert(8);
cache.insert(9);
assert_eq!(items(&cache), [9, 8, 7, 6], "Least-recently-used item evicted.");
}
#[test]
fn lookup() {
let mut cache = TestCache::default();
cache.insert(1);
cache.insert(2);
cache.insert(3);
cache.insert(4);
let result = cache.lookup(|x| if *x == 5 { Some(()) } else { None });
assert_eq!(result, None, "Cache miss.");
assert_eq!(items(&cache), [4, 3, 2, 1], "Order not changed.");
// Cache hit
let result = cache.lookup(|x| if *x == 3 { Some(*x * 2) } else { None });
assert_eq!(result, Some(6), "Cache hit.");
assert_eq!(items(&cache), [3, 4, 2, 1], "Matching item moved to front.");
}
#[test]
fn evict_all() {
let mut cache = TestCache::default();
cache.insert(1);
cache.evict_all();
assert_eq!(items(&cache), [], "all items evicted");
cache.insert(1);
cache.insert(2);
cache.insert(3);
cache.insert(4);
assert_eq!(items(&cache), [4, 3, 2, 1]);
cache.evict_all();
assert_eq!(items(&cache), [], "all items evicted again");
}

View File

@ -24,11 +24,10 @@ dependencies = [
[[package]]
name = "arrayvec"
version = "0.3.23"
version = "0.4.6"
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)",
"nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -866,11 +865,8 @@ dependencies = [
[[package]]
name = "nodrop"
version = "0.1.9"
version = "0.1.12"
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"
@ -919,11 +915,6 @@ dependencies = [
"libc 0.2.24 (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"
@ -1201,7 +1192,7 @@ dependencies = [
name = "servo_arc"
version = "0.0.1"
dependencies = [
"nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
"nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
"stable_deref_trait 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -1250,7 +1241,7 @@ name = "style"
version = "0.0.1"
dependencies = [
"app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
"arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
"arrayvec 0.4.6 (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.31.3 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
@ -1287,7 +1278,7 @@ dependencies = [
"style_traits 0.0.1",
"time 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)",
"toml 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"uluru 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"uluru 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-bidi 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-segmentation 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"walkdir 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
@ -1420,10 +1411,10 @@ dependencies = [
[[package]]
name = "uluru"
version = "0.1.0"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
"arrayvec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -1596,7 +1587,7 @@ dependencies = [
"checksum aho-corasick 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "500909c4f87a9e52355b26626d890833e9e1d53ac566db76c36faa984b889699"
"checksum ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "23ac7c30002a5accbf7e8987d0632fa6de155b7c3d39d0067317a391e00a2ef6"
"checksum app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ed0a4de09a3b8449515e649f3bb84f72ea15fc2d10639beb0776a09b7d308074"
"checksum arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)" = "699e63a93b79d717e8c3b5eb1b28b7780d0d6d9e59a72eb769291c83b0c8dc67"
"checksum arrayvec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2f0ef4a9820019a0c91d918918c93dc71d469f581a49b47ddc1d285d4270bbe2"
"checksum atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb2dcb6e6d35f20276943cc04bb98e538b348d525a04ac79c10021561d202f21"
"checksum atty 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d912da0db7fa85514874458ca3651fe2cddace8d0b0505571dbdcd41ab490159"
"checksum binary-space-partition 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88ceb0d16c4fd0e42876e298d7d3ce3780dd9ebdcbe4199816a32c77e08597ff"
@ -1670,12 +1661,11 @@ dependencies = [
"checksum mio-uds 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "1731a873077147b626d89cc6c2a0db6288d607496c5d10c0cfcf3adc697ec673"
"checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919"
"checksum net2 0.2.31 (registry+https://github.com/rust-lang/crates.io-index)" = "3a80f842784ef6c9a958b68b7516bc7e35883c614004dd94959a4dca1b716c09"
"checksum nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "52cd74cd09beba596430cc6e3091b74007169a56246e1262f0ba451ea95117b2"
"checksum nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "9a2228dca57108069a5262f2ed8bd2e82496d2e074a06d1ccc7ce1687b6ae0a2"
"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.39 (registry+https://github.com/rust-lang/crates.io-index)" = "1708c0628602a98b52fad936cf3edb9a107af06e52e49fdf0707e884456a6af6"
"checksum num_cpus 1.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "aec53c34f2d0247c5ca5d32cca1478762f301740468ee9ee6dcb7a0dd7a0c584"
"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.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "cdf84f41639e037b484f93433aa3897863b561ed65c6e59c7073d7c561710f37"
"checksum parking_lot 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "37f364e2ce5efa24c7d0b6646d5bb61145551a0112f107ffd7499f1a3e322fbd"
@ -1724,7 +1714,7 @@ dependencies = [
"checksum thread_profiler 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf947d192a9be60ef5131cc7a4648886ba89d712f16700ebbf80c8a69d05d48f"
"checksum time 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)" = "211b63c112206356ef1ff9b19355f43740fc3f85960c598a93d3a3d3ba7beade"
"checksum toml 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "736b60249cb25337bc196faa43ee12c705e426f3d55c214d73a4e7be06f92cb4"
"checksum uluru 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cd28fce445fd48f4e2c10ab0d3d8f6a646b11fd2b05228fa94fc83cf69ad6e98"
"checksum uluru 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "519130f0ea964ba540a9d8af1373738c2226f1d465eda07e61db29feb5479db9"
"checksum unicode-bidi 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a6a2c4e3710edd365cd7e78383153ed739fa31af19f9172f72d3575060f5a43a"
"checksum unicode-normalization 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "51ccda9ef9efa3f7ef5d91e8f9b83bbe6955f9bf86aec89d5cce2c874625920f"
"checksum unicode-segmentation 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "18127285758f0e2c6cf325bb3f3d138a12fee27de4f23e146cd6a179f26c2cf3"

View File

@ -24,11 +24,10 @@ dependencies = [
[[package]]
name = "arrayvec"
version = "0.3.23"
version = "0.4.6"
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)",
"nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -861,11 +860,8 @@ dependencies = [
[[package]]
name = "nodrop"
version = "0.1.9"
version = "0.1.12"
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"
@ -907,11 +903,6 @@ dependencies = [
"libc 0.2.24 (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"
@ -1189,7 +1180,7 @@ dependencies = [
name = "servo_arc"
version = "0.0.1"
dependencies = [
"nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
"nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
"stable_deref_trait 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -1242,7 +1233,7 @@ name = "style"
version = "0.0.1"
dependencies = [
"app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
"arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
"arrayvec 0.4.6 (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.31.3 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
@ -1279,7 +1270,7 @@ dependencies = [
"style_traits 0.0.1",
"time 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)",
"toml 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"uluru 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"uluru 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-bidi 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-segmentation 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"walkdir 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
@ -1432,10 +1423,10 @@ dependencies = [
[[package]]
name = "uluru"
version = "0.1.0"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
"arrayvec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -1608,7 +1599,7 @@ dependencies = [
"checksum aho-corasick 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "500909c4f87a9e52355b26626d890833e9e1d53ac566db76c36faa984b889699"
"checksum ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "23ac7c30002a5accbf7e8987d0632fa6de155b7c3d39d0067317a391e00a2ef6"
"checksum app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ed0a4de09a3b8449515e649f3bb84f72ea15fc2d10639beb0776a09b7d308074"
"checksum arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)" = "699e63a93b79d717e8c3b5eb1b28b7780d0d6d9e59a72eb769291c83b0c8dc67"
"checksum arrayvec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2f0ef4a9820019a0c91d918918c93dc71d469f581a49b47ddc1d285d4270bbe2"
"checksum atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb2dcb6e6d35f20276943cc04bb98e538b348d525a04ac79c10021561d202f21"
"checksum atty 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d912da0db7fa85514874458ca3651fe2cddace8d0b0505571dbdcd41ab490159"
"checksum binary-space-partition 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88ceb0d16c4fd0e42876e298d7d3ce3780dd9ebdcbe4199816a32c77e08597ff"
@ -1682,12 +1673,11 @@ dependencies = [
"checksum mio-uds 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "1731a873077147b626d89cc6c2a0db6288d607496c5d10c0cfcf3adc697ec673"
"checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919"
"checksum net2 0.2.31 (registry+https://github.com/rust-lang/crates.io-index)" = "3a80f842784ef6c9a958b68b7516bc7e35883c614004dd94959a4dca1b716c09"
"checksum nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "52cd74cd09beba596430cc6e3091b74007169a56246e1262f0ba451ea95117b2"
"checksum nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "9a2228dca57108069a5262f2ed8bd2e82496d2e074a06d1ccc7ce1687b6ae0a2"
"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.39 (registry+https://github.com/rust-lang/crates.io-index)" = "1708c0628602a98b52fad936cf3edb9a107af06e52e49fdf0707e884456a6af6"
"checksum num_cpus 1.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "aec53c34f2d0247c5ca5d32cca1478762f301740468ee9ee6dcb7a0dd7a0c584"
"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.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "cdf84f41639e037b484f93433aa3897863b561ed65c6e59c7073d7c561710f37"
"checksum parking_lot 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "37f364e2ce5efa24c7d0b6646d5bb61145551a0112f107ffd7499f1a3e322fbd"
@ -1736,7 +1726,7 @@ dependencies = [
"checksum thread_profiler 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf947d192a9be60ef5131cc7a4648886ba89d712f16700ebbf80c8a69d05d48f"
"checksum time 0.1.36 (registry+https://github.com/rust-lang/crates.io-index)" = "211b63c112206356ef1ff9b19355f43740fc3f85960c598a93d3a3d3ba7beade"
"checksum toml 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "736b60249cb25337bc196faa43ee12c705e426f3d55c214d73a4e7be06f92cb4"
"checksum uluru 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cd28fce445fd48f4e2c10ab0d3d8f6a646b11fd2b05228fa94fc83cf69ad6e98"
"checksum uluru 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "519130f0ea964ba540a9d8af1373738c2226f1d465eda07e61db29feb5479db9"
"checksum unicode-bidi 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a6a2c4e3710edd365cd7e78383153ed739fa31af19f9172f72d3575060f5a43a"
"checksum unicode-normalization 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "51ccda9ef9efa3f7ef5d91e8f9b83bbe6955f9bf86aec89d5cce2c874625920f"
"checksum unicode-segmentation 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "18127285758f0e2c6cf325bb3f3d138a12fee27de4f23e146cd6a179f26c2cf3"