Full Code of llogiq/bytecount for AI

master f06647f90a45 cached
20 files
62.6 KB
19.1k tokens
68 symbols
1 requests
Download .txt
Repository: llogiq/bytecount
Branch: master
Commit: f06647f90a45
Files: 20
Total size: 62.6 KB

Directory structure:
gitextract_fy6189iu/

├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── Cargo.toml
├── LICENSE.Apache2
├── LICENSE.MIT
├── README.md
├── appveyor.yml
├── benches/
│   └── bench.rs
├── ci/
│   └── miri.sh
├── src/
│   ├── integer_simd.rs
│   ├── lib.rs
│   ├── naive.rs
│   └── simd/
│       ├── aarch64.rs
│       ├── generic.rs
│       ├── mod.rs
│       ├── wasm.rs
│       ├── x86_avx2.rs
│       └── x86_sse2.rs
└── tests/
    └── check.rs

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: cargo
  directory: "/"
  schedule:
    interval: daily
    time: "04:00"
  open-pull-requests-limit: 10


================================================
FILE: .github/workflows/ci.yml
================================================
on: 
  push:
    branches:
      - master
  pull_request:

name: Continuous integration

jobs:
  test:
    name: Test suite
    strategy:
      matrix:
        rust:
          - 1.32.0
          - stable
          - beta
          - nightly
        os:
          - macos-latest
          - ubuntu-latest
        arch:
          - i686
          - x86_64
          - aarch64
        features:
          - default
          - runtime-dispatch-simd
          - generic-simd
        exclude:
        - rust: 1.32.0
          features: generic-simd
        - rust: stable
          features: generic-simd
        - rust: beta
          features: generic-simd

    env:
      ARCH: ${{ matrix.arch }}
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v3
      - uses: actions-rs/toolchain@v1.0.7
        with:
          profile: minimal
          toolchain: ${{ matrix.rust }}
          override: true
          components: clippy, rustfmt
      - uses: Swatinem/rust-cache@v2
      - name: Build (1.32.0, default)
        uses: actions-rs/cargo@v1.0.3
        with:
          command: build
          args: --release
        if: ${{ matrix.features == 'default' && matrix.rust == '1.32.0' }}
      - name: Build (1.32.0, non-default)
        uses: actions-rs/cargo@v1.0.3
        with:
          command: build
          args: --release --features ${{ matrix.features }}
        if: ${{ matrix.features != 'default' && matrix.rust == '1.32.0' }}        
      - name: Test (default)
        uses: actions-rs/cargo@v1.0.3
        with:
          command: test
          args: --release
        if: ${{ matrix.features == 'default' && matrix.rust != '1.32.0' }}
      - name: Test (non-default)
        uses: actions-rs/cargo@v1.0.3
        with:
          command: test
          args: --release --features ${{ matrix.features }}
        if: ${{ matrix.features != 'default' && matrix.rust != '1.32.0' }}
      - name: bench
        uses: actions-rs/cargo@v1.0.3
        with:
          command: bench
        env:
          COUNTS: 0,10,1000,100000,10000000
        if: ${{ matrix.rust != '1.32.0' }}

  # Fails currently on check_count_overflow_many 
  #
  # miri:
  #   name: MIRI testing
  #   runs-on: ubuntu-latest
  #   steps:
  #     - uses: actions/checkout@v2.3.4
  #     - uses: actions-rs/toolchain@v1.0.7
  #       with:
  #         profile: minimal
  #         toolchain: nightly
  #         override: true
  #     - name: Run miri
  #       run: ./ci/miri.sh


================================================
FILE: .gitignore
================================================
target
Cargo.lock


================================================
FILE: Cargo.toml
================================================
[package]
authors = ["Andre Bogus <bogusandre@gmail.de>", "Joshua Landau <joshua@landau.ws>"]
description = "count occurrences of a given byte, or the number of UTF-8 code points, in a byte slice, fast"
edition = "2018"
name = "bytecount"
version = "0.6.9"
license = "Apache-2.0/MIT"
repository = "https://github.com/llogiq/bytecount"
categories = ["algorithms", "no-std"]
readme = "README.md"
exclude = ["/.travis.yml", "/appveyor.yml"]

[badges]
travis-ci = { repository = "llogiq/bytecount" }
appveyor = { repository = "llogiq/bytecount" }

[lib]
bench = false

[features]
generic-simd = []
runtime-dispatch-simd = []
html_report = []

[dependencies]

[dev-dependencies]
quickcheck = "1.0"
rand = "0.8"
criterion = { version = "0.4", default-features = false }

[[bench]]
name = "bench"
harness = false


================================================
FILE: LICENSE.Apache2
================================================
                                 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.


================================================
FILE: LICENSE.MIT
================================================
Copyright (c) 2017 The bytecount Developers

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.


================================================
FILE: README.md
================================================
# bytecount

Counting bytes really fast

[![Continuous integration](https://github.com/llogiq/bytecount/actions/workflows/ci.yml/badge.svg)](https://github.com/llogiq/bytecount/actions/workflows/ci.yml)
[![Windows build status](https://ci.appveyor.com/api/projects/status/github/llogiq/bytecount?svg=true)](https://ci.appveyor.com/project/llogiq/bytecount)
[![Current Version](https://img.shields.io/crates/v/bytecount.svg)](https://crates.io/crates/bytecount)
[![License: Apache 2.0/MIT](https://img.shields.io/crates/l/bytecount.svg)](#license)

This uses the "hyperscreamingcount" algorithm by Joshua Landau to count bytes faster than anything else.
The [newlinebench](https://github.com/llogiq/newlinebench) repository has further benchmarks for old versions of this repository.

To use bytecount in your crate, if you have [cargo-edit](https://github.com/killercup/cargo-edit), just type
`cargo add bytecount` in a terminal with the crate root as the current path. Otherwise you can manually edit your
`Cargo.toml` to add `bytecount = 0.6.9` to your `[dependencies]` section.

In your crate root (`lib.rs` or `main.rs`, depending on if you are writing a
library or application), add `extern crate bytecount;`. Now you can simply use
`bytecount::count` as follows:

```Rust
extern crate bytecount;

fn main() {
    let mytext = "some potentially large text, perhaps read from disk?";
    let spaces = bytecount::count(mytext.as_bytes(), b' ');
    ..
}
```

bytecount supports two features to make use of modern CPU's features to speed up counting considerably. To allow your
users to use them, add the following to your `Cargo.toml`:

```
[features]
runtime-dispatch-simd = ["bytecount/runtime-dispatch-simd"]
generic-simd = ["bytecount/generic-simd"]
```

The first, `runtime-dispatch-simd`, enables detection of SIMD capabilities at runtime, which allows using the SSE2 and
AVX2 codepaths, but cannot be used with `no_std`.

Your users can then compile with runtime dispatch using:

```
cargo build --release --features runtime-dispatch-simd
```

The second, `generic-simd`, uses [`std::simd`](https://doc.rust-lang.org/std/simd/index.html) and [`#![feature(portable_simd)]`](https://github.com/rust-lang/rust/issues/86656) to provide a fast
architecture-agnostic SIMD codepath, but requires running on nightly.

Your users can compile with this codepath using:

```
cargo build --release --features generic-simd
```

Building for a more specific architecture will also improve performance.
You can do this with

```
RUSTFLAGS="-C target-cpu=native" cargo build --release
```

The scalar algorithm is explained in depth [here](https://llogiq.github.io/2016/09/27/count.html).

**Note: Versions until 0.4.0 worked with Rust as of 1.20.0. Version 0.5.0 until 0.6.0 requires Rust 1.26 or later,
and at least 1.27.2 to use SIMD. Versions from 0.6.0 require Rust 1.32.0 or later.**

## License

Licensed under either of at your discretion:

- [Apache 2.0](LICENSE.Apache2)
- [MIT](LICENSE.MIT)


================================================
FILE: appveyor.yml
================================================
environment:
    global:
        PROJECT_NAME: bytecount
        FEATURES: ""
        RUSTFLAGS: ""
        COUNTS: "0,10,1000,100000"
    matrix:
        - TARGET: i686-pc-windows-gnu
          CHANNEL: stable
        - TARGET: i686-pc-windows-gnu
          CHANNEL: beta
        - TARGET: i686-pc-windows-gnu
          CHANNEL: nightly
        - TARGET: i686-pc-windows-gnu
          CHANNEL: nightly
          FEATURES: "--features generic-simd"
        - TARGET: i686-pc-windows-gnu
          CHANNEL: nightly
          FEATURES: "--features generic-simd,runtime-dispatch-simd"
        - TARGET: i686-pc-windows-msvc
          CHANNEL: stable
        - TARGET: i686-pc-windows-msvc
          CHANNEL: beta
        - TARGET: i686-pc-windows-msvc
          CHANNEL: nightly
        - TARGET: i686-pc-windows-msvc
          CHANNEL: nightly
          FEATURES: "--features generic-simd"
        - TARGET: i686-pc-windows-msvc
          CHANNEL: nightly
          FEATURES: "--features generic-simd,runtime-dispatch-simd"
        - TARGET: x86_64-pc-windows-gnu
          CHANNEL: stable
        - TARGET: x86_64-pc-windows-gnu
          CHANNEL: beta
        - TARGET: x86_64-pc-windows-gnu
          CHANNEL: nightly
        - TARGET: x86_64-pc-windows-gnu
          CHANNEL: nightly
          FEATURES: "--features generic-simd"
        - TARGET: x86_64-pc-windows-gnu
          CHANNEL: nightly
          FEATURES: "--features generic-simd,runtime-dispatch-simd"
        - TARGET: x86_64-pc-windows-msvc
          CHANNEL: stable
        - TARGET: x86_64-pc-windows-msvc
          CHANNEL: beta
        - TARGET: x86_64-pc-windows-msvc
          CHANNEL: nightly
        - TARGET: x86_64-pc-windows-msvc
          CHANNEL: nightly
          FEATURES: "--features generic-simd"
        - TARGET: x86_64-pc-windows-msvc
          CHANNEL: nightly
          FEATURES: "--features generic-simd,runtime-dispatch-simd"

install:
    - curl -sSf -o rustup-init.exe https://win.rustup.rs/
    - rustup-init.exe -y --default-host %TARGET% --default-toolchain %CHANNEL%
    - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin
    - if defined MSYS2_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS2_BITS%\bin
    - rustc -V
    - cargo -V

build: false

cache:
    - target
    - C:\Users\appveyor\.cargo\registry

test_script:
    - echo RUSTFLAGS=%RUSTFLAGS%
    - echo FEATURES=%FEATURES%
    - cargo test --target %TARGET% %FEATURES%
    - cargo bench --target %TARGET% %FEATURES%



================================================
FILE: benches/bench.rs
================================================
#[macro_use]
extern crate criterion;
extern crate bytecount;
extern crate rand;

use criterion::{Bencher, BenchmarkId, Criterion};
use rand::RngCore;
use std::env;
use std::time::Duration;

use bytecount::{count, naive_count, naive_count_32, naive_num_chars, num_chars};

fn random_bytes(len: usize) -> Vec<u8> {
    let mut result = vec![0; len];
    rand::thread_rng().fill_bytes(&mut result);
    result
}

static COUNTS: &[usize] = &[
    0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 140, 170, 210, 250, 300, 400, 500, 600, 700,
    800, 900, 1_000, 1_200, 1_400, 1_700, 2_100, 2_500, 3_000, 4_000, 5_000, 6_000, 7_000, 8_000,
    9_000, 10_000, 12_000, 14_000, 17_000, 21_000, 25_000, 30_000, 100_000, 1_000_000,
];

fn get_counts() -> Vec<usize> {
    env::var("COUNTS")
        .map(|s| {
            s.split(',')
                .map(|n| str::parse::<usize>(n).unwrap())
                .collect()
        })
        .unwrap_or(COUNTS.to_owned())
}

fn get_config() -> Criterion {
    if env::var("CI").is_ok() {
        Criterion::default()
            .nresamples(5_000)
            .without_plots()
            .measurement_time(Duration::new(2, 0))
            .warm_up_time(Duration::new(1, 0))
    } else {
        Criterion::default()
    }
}

fn bench_counts(criterion: &mut Criterion) {
    fn naive(b: &mut Bencher, s: &usize) {
        let haystack = random_bytes(*s);
        b.iter(|| naive_count(&haystack, 10))
    }
    fn naive_32(b: &mut Bencher, s: &usize) {
        let haystack = random_bytes(*s);
        b.iter(|| naive_count_32(&haystack, 10))
    }
    fn hyper(b: &mut Bencher, s: &usize) {
        let haystack = random_bytes(*s);
        b.iter(|| count(&haystack, 10))
    }
    let counts = get_counts();
    let mut group = criterion.benchmark_group("counts");
    for count in counts {
        group.throughput(criterion::Throughput::Bytes(count as u64));
        group.bench_with_input(BenchmarkId::new("naive", count), &count, naive);
        group.bench_with_input(BenchmarkId::new("naive_32", count), &count, naive_32);
        group.bench_with_input(BenchmarkId::new("hyper", count), &count, hyper);
    }
}

fn bench_num_chars(criterion: &mut Criterion) {
    fn naive(b: &mut Bencher, s: &usize) {
        let haystack = random_bytes(*s);
        b.iter(|| naive_num_chars(&haystack))
    }
    fn hyper(b: &mut Bencher, s: &usize) {
        let haystack = random_bytes(*s);
        b.iter(|| num_chars(&haystack))
    }
    let counts = get_counts();
    let mut group = criterion.benchmark_group("num_chars");
    for count in counts {
        group.throughput(criterion::Throughput::Bytes(count as u64));
        group.bench_with_input(BenchmarkId::new("naive", count), &count, naive);
        group.bench_with_input(BenchmarkId::new("hyper", count), &count, hyper);
    }
}

criterion_group!(name = count_bench; config = get_config(); targets = bench_counts);
criterion_group!(name = num_chars_bench; config = get_config(); targets = bench_num_chars);
criterion_main!(count_bench, num_chars_bench);


================================================
FILE: ci/miri.sh
================================================
#!/bin/bash
set -ex

# Setup
MIRI_NIGHTLY=nightly-$(curl -s https://rust-lang.github.io/rustup-components-history/x86_64-unknown-linux-gnu/miri)
echo "Installing latest nightly with Miri: $MIRI_NIGHTLY"
rustup default "$MIRI_NIGHTLY"
rustup component add miri

# Run tests
cargo miri test
cargo miri test --target=mips64-unknown-linux-gnuabi64 # big-endian architecture

================================================
FILE: src/integer_simd.rs
================================================
#[cfg(not(feature = "runtime-dispatch-simd"))]
use core::{mem, ptr, usize};
#[cfg(feature = "runtime-dispatch-simd")]
use std::{mem, ptr, usize};

fn splat(byte: u8) -> usize {
    let lo = usize::MAX / 0xFF;
    lo * byte as usize
}

unsafe fn usize_load_unchecked(bytes: &[u8], offset: usize) -> usize {
    let mut output = 0;
    ptr::copy_nonoverlapping(
        bytes.as_ptr().add(offset),
        &mut output as *mut usize as *mut u8,
        mem::size_of::<usize>(),
    );
    output
}

fn bytewise_equal(lhs: usize, rhs: usize) -> usize {
    let lo = usize::MAX / 0xFF;
    let hi = lo << 7;

    let x = lhs ^ rhs;
    !((((x & !hi) + !hi) | x) >> 7) & lo
}

fn sum_usize(values: usize) -> usize {
    let every_other_byte_lo = usize::MAX / 0xFFFF;
    let every_other_byte = every_other_byte_lo * 0xFF;

    // Pairwise reduction to avoid overflow on next step.
    let pair_sum: usize = (values & every_other_byte) + ((values >> 8) & every_other_byte);

    // Multiplication results in top two bytes holding sum.
    pair_sum.wrapping_mul(every_other_byte_lo) >> ((mem::size_of::<usize>() - 2) * 8)
}

fn is_leading_utf8_byte(values: usize) -> usize {
    // a leading UTF-8 byte is one which does not start with the bits 10.
    ((!values >> 7) | (values >> 6)) & splat(1)
}

pub fn chunk_count(haystack: &[u8], needle: u8) -> usize {
    let chunksize = mem::size_of::<usize>();
    assert!(haystack.len() >= chunksize);

    unsafe {
        let mut offset = 0;
        let mut count = 0;

        let needles = splat(needle);

        // 2040
        while haystack.len() >= offset + chunksize * 255 {
            let mut counts = 0;
            for _ in 0..255 {
                counts += bytewise_equal(usize_load_unchecked(haystack, offset), needles);
                offset += chunksize;
            }
            count += sum_usize(counts);
        }

        // 8
        let mut counts = 0;
        for i in 0..(haystack.len() - offset) / chunksize {
            counts += bytewise_equal(
                usize_load_unchecked(haystack, offset + i * chunksize),
                needles,
            );
        }
        if haystack.len() % 8 != 0 {
            let mask = usize::from_le(!(!0 >> ((haystack.len() % chunksize) * 8)));
            counts += bytewise_equal(
                usize_load_unchecked(haystack, haystack.len() - chunksize),
                needles,
            ) & mask;
        }
        count += sum_usize(counts);

        count
    }
}

pub fn chunk_num_chars(utf8_chars: &[u8]) -> usize {
    let chunksize = mem::size_of::<usize>();
    assert!(utf8_chars.len() >= chunksize);

    unsafe {
        let mut offset = 0;
        let mut count = 0;

        // 2040
        while utf8_chars.len() >= offset + chunksize * 255 {
            let mut counts = 0;
            for _ in 0..255 {
                counts += is_leading_utf8_byte(usize_load_unchecked(utf8_chars, offset));
                offset += chunksize;
            }
            count += sum_usize(counts);
        }

        // 8
        let mut counts = 0;
        for i in 0..(utf8_chars.len() - offset) / chunksize {
            counts +=
                is_leading_utf8_byte(usize_load_unchecked(utf8_chars, offset + i * chunksize));
        }
        if utf8_chars.len() % 8 != 0 {
            let mask = usize::from_le(!(!0 >> ((utf8_chars.len() % chunksize) * 8)));
            counts += is_leading_utf8_byte(usize_load_unchecked(
                utf8_chars,
                utf8_chars.len() - chunksize,
            )) & mask;
        }
        count += sum_usize(counts);

        count
    }
}


================================================
FILE: src/lib.rs
================================================
//! count occurrences of a given byte, or the number of UTF-8 code points, in a
//! byte slice, fast.
//!
//! This crate has the [`count`](fn.count.html) method to count byte
//! occurrences (for example newlines) in a larger `&[u8]` slice.
//!
//! For example:
//!
//! ```rust
//! assert_eq!(5, bytecount::count(b"Hello, this is the bytecount crate!", b' '));
//! ```
//!
//! Also there is a [`num_chars`](fn.num_chars.html) method to count
//! the number of UTF8 characters in a slice. It will work the same as
//! `str::chars().count()` for byte slices of correct UTF-8 character
//! sequences. The result will likely be off for invalid sequences,
//! although the result is guaranteed to be between `0` and
//! `[_]::len()`, inclusive.
//!
//! Example:
//!
//! ```rust
//! let sequence = "Wenn ich ein Vöglein wär, flög ich zu Dir!";
//! assert_eq!(sequence.chars().count(),
//!            bytecount::num_chars(sequence.as_bytes()));
//! ```
//!
//! For completeness and easy comparison, the "naive" versions of both
//! count and num_chars are provided. Those are also faster if used on
//! predominantly small strings. The
//! [`naive_count_32`](fn.naive_count_32.html) method can be faster
//! still on small strings.

#![cfg_attr(feature = "generic-simd", feature(portable_simd))]
#![deny(missing_docs)]
#![cfg_attr(not(feature = "runtime-dispatch-simd"), no_std)]

#[cfg(not(feature = "runtime-dispatch-simd"))]
use core::mem;
#[cfg(feature = "runtime-dispatch-simd")]
use std::mem;

mod naive;
pub use naive::*;
mod integer_simd;

#[cfg(any(
    all(
        feature = "runtime-dispatch-simd",
        any(target_arch = "x86", target_arch = "x86_64")
    ),
    all(target_arch = "aarch64", target_endian = "little"),
    target_arch = "wasm32",
    feature = "generic-simd"
))]
mod simd;

/// Count occurrences of a byte in a slice of bytes, fast
///
/// # Examples
///
/// ```
/// let s = b"This is a Text with spaces";
/// let number_of_spaces = bytecount::count(s, b' ');
/// assert_eq!(number_of_spaces, 5);
/// ```
pub fn count(haystack: &[u8], needle: u8) -> usize {
    if haystack.len() >= 32 {
        #[cfg(all(feature = "runtime-dispatch-simd", target_arch = "x86_64"))]
        {
            if is_x86_feature_detected!("avx2") {
                unsafe {
                    return simd::x86_avx2::chunk_count(haystack, needle);
                }
            }
        }

        #[cfg(feature = "generic-simd")]
        return simd::generic::chunk_count(haystack, needle);
    }

    if haystack.len() >= 16 {
        #[cfg(all(
            feature = "runtime-dispatch-simd",
            any(target_arch = "x86", target_arch = "x86_64"),
            not(feature = "generic-simd")
        ))]
        {
            if is_x86_feature_detected!("sse2") {
                unsafe {
                    return simd::x86_sse2::chunk_count(haystack, needle);
                }
            }
        }
        #[cfg(all(
            target_arch = "aarch64",
            target_endian = "little",
            not(feature = "generic-simd")
        ))]
        {
            unsafe {
                return simd::aarch64::chunk_count(haystack, needle);
            }
        }

        #[cfg(target_arch = "wasm32")]
        {
            unsafe {
                return simd::wasm::chunk_count(haystack, needle);
            }
        }
    }

    if haystack.len() >= mem::size_of::<usize>() {
        return integer_simd::chunk_count(haystack, needle);
    }

    naive_count(haystack, needle)
}

/// Count the number of UTF-8 encoded Unicode codepoints in a slice of bytes, fast
///
/// This function is safe to use on any byte array, valid UTF-8 or not,
/// but the output is only meaningful for well-formed UTF-8.
///
/// # Example
///
/// ```
/// let swordfish = "メカジキ";
/// let char_count = bytecount::num_chars(swordfish.as_bytes());
/// assert_eq!(char_count, 4);
/// ```
pub fn num_chars(utf8_chars: &[u8]) -> usize {
    if utf8_chars.len() >= 32 {
        #[cfg(all(feature = "runtime-dispatch-simd", target_arch = "x86_64"))]
        {
            if is_x86_feature_detected!("avx2") {
                unsafe {
                    return simd::x86_avx2::chunk_num_chars(utf8_chars);
                }
            }
        }

        #[cfg(feature = "generic-simd")]
        return simd::generic::chunk_num_chars(utf8_chars);
    }

    if utf8_chars.len() >= 16 {
        #[cfg(all(
            feature = "runtime-dispatch-simd",
            any(target_arch = "x86", target_arch = "x86_64"),
            not(feature = "generic-simd")
        ))]
        {
            if is_x86_feature_detected!("sse2") {
                unsafe {
                    return simd::x86_sse2::chunk_num_chars(utf8_chars);
                }
            }
        }
        #[cfg(all(
            target_arch = "aarch64",
            target_endian = "little",
            not(feature = "generic-simd")
        ))]
        {
            unsafe {
                return simd::aarch64::chunk_num_chars(utf8_chars);
            }
        }

        #[cfg(target_arch = "wasm32")]
        {
            unsafe {
                return simd::wasm::chunk_num_chars(utf8_chars);
            }
        }
    }

    if utf8_chars.len() >= mem::size_of::<usize>() {
        return integer_simd::chunk_num_chars(utf8_chars);
    }

    naive_num_chars(utf8_chars)
}


================================================
FILE: src/naive.rs
================================================
/// Count up to `(2^32)-1` occurrences of a byte in a slice
/// of bytes, simple
///
/// # Example
///
/// ```
/// let s = b"This is yet another Text with spaces";
/// let number_of_spaces = bytecount::naive_count_32(s, b' ');
/// assert_eq!(number_of_spaces, 6);
/// ```
pub fn naive_count_32(haystack: &[u8], needle: u8) -> usize {
    haystack.iter().fold(0, |n, c| n + (*c == needle) as u32) as usize
}

/// Count occurrences of a byte in a slice of bytes, simple
///
/// # Example
///
/// ```
/// let s = b"This is yet another Text with spaces";
/// let number_of_spaces = bytecount::naive_count(s, b' ');
/// assert_eq!(number_of_spaces, 6);
/// ```
pub fn naive_count(utf8_chars: &[u8], needle: u8) -> usize {
    utf8_chars
        .iter()
        .fold(0, |n, c| n + (*c == needle) as usize)
}

/// Count the number of UTF-8 encoded Unicode codepoints in a slice of bytes, simple
///
/// This function is safe to use on any byte array, valid UTF-8 or not,
/// but the output is only meaningful for well-formed UTF-8.
///
/// # Example
///
/// ```
/// let swordfish = "メカジキ";
/// let char_count = bytecount::naive_num_chars(swordfish.as_bytes());
/// assert_eq!(char_count, 4);
/// ```
pub fn naive_num_chars(utf8_chars: &[u8]) -> usize {
    utf8_chars
        .iter()
        .filter(|&&byte| (byte >> 6) != 0b10)
        .count()
}


================================================
FILE: src/simd/aarch64.rs
================================================
use core::arch::aarch64::{
    uint8x16_t, uint8x16x4_t, vaddlvq_u8, vandq_u8, vceqq_u8, vdupq_n_u8, vld1q_u8, vld1q_u8_x4,
    vsubq_u8,
};

const MASK: [u8; 32] = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255,
];

#[target_feature(enable = "neon")]
unsafe fn u8x16_from_offset(slice: &[u8], offset: usize) -> uint8x16_t {
    debug_assert!(
        offset + 16 <= slice.len(),
        "{} + 16 ≥ {}",
        offset,
        slice.len()
    );
    vld1q_u8(slice.as_ptr().add(offset) as *const _) // TODO: does this need to be aligned?
}

#[target_feature(enable = "neon")]
unsafe fn u8x16_x4_from_offset(slice: &[u8], offset: usize) -> uint8x16x4_t {
    debug_assert!(
        offset + 64 <= slice.len(),
        "{} + 64 ≥ {}",
        offset,
        slice.len()
    );
    vld1q_u8_x4(slice.as_ptr().add(offset) as *const _)
}

#[target_feature(enable = "neon")]
unsafe fn sum(u8s: uint8x16_t) -> usize {
    vaddlvq_u8(u8s) as usize
}

unsafe fn sum4(u1: uint8x16_t, u2: uint8x16_t, u3: uint8x16_t, u4: uint8x16_t) -> usize {
    ((vaddlvq_u8(u1) + vaddlvq_u8(u2)) + (vaddlvq_u8(u3) + vaddlvq_u8(u4))) as usize
}

#[target_feature(enable = "neon")]
pub unsafe fn chunk_count(haystack: &[u8], needle: u8) -> usize {
    assert!(haystack.len() >= 16);

    let mut offset = 0;
    let mut count = 0;

    let needles = vdupq_n_u8(needle);

    // 16320
    while haystack.len() >= offset + 64 * 255 {
        let (mut count1, mut count2, mut count3, mut count4) =
            (vdupq_n_u8(0), vdupq_n_u8(0), vdupq_n_u8(0), vdupq_n_u8(0));
        for _ in 0..255 {
            let uint8x16x4_t(h1, h2, h3, h4) = u8x16_x4_from_offset(haystack, offset);
            count1 = vsubq_u8(count1, vceqq_u8(h1, needles));
            count2 = vsubq_u8(count2, vceqq_u8(h2, needles));
            count3 = vsubq_u8(count3, vceqq_u8(h3, needles));
            count4 = vsubq_u8(count4, vceqq_u8(h4, needles));
            offset += 64;
        }
        count += sum4(count1, count2, count3, count4);
    }

    // 64
    let (mut count1, mut count2, mut count3, mut count4) =
        (vdupq_n_u8(0), vdupq_n_u8(0), vdupq_n_u8(0), vdupq_n_u8(0));
    for _ in 0..(haystack.len() - offset) / 64 {
        let uint8x16x4_t(h1, h2, h3, h4) = u8x16_x4_from_offset(haystack, offset);
        count1 = vsubq_u8(count1, vceqq_u8(h1, needles));
        count2 = vsubq_u8(count2, vceqq_u8(h2, needles));
        count3 = vsubq_u8(count3, vceqq_u8(h3, needles));
        count4 = vsubq_u8(count4, vceqq_u8(h4, needles));
        offset += 64;
    }
    count += sum4(count1, count2, count3, count4);

    let mut counts = vdupq_n_u8(0);
    // 16
    for i in 0..(haystack.len() - offset) / 16 {
        counts = vsubq_u8(
            counts,
            vceqq_u8(u8x16_from_offset(haystack, offset + i * 16), needles),
        );
    }
    if haystack.len() % 16 != 0 {
        counts = vsubq_u8(
            counts,
            vandq_u8(
                vceqq_u8(u8x16_from_offset(haystack, haystack.len() - 16), needles),
                u8x16_from_offset(&MASK, haystack.len() % 16),
            ),
        );
    }
    count + sum(counts)
}

#[target_feature(enable = "neon")]
unsafe fn is_following_utf8_byte(u8s: uint8x16_t) -> uint8x16_t {
    vceqq_u8(
        vandq_u8(u8s, vdupq_n_u8(0b1100_0000)),
        vdupq_n_u8(0b1000_0000),
    )
}

#[target_feature(enable = "neon")]
pub unsafe fn chunk_num_chars(utf8_chars: &[u8]) -> usize {
    assert!(utf8_chars.len() >= 16);

    let mut offset = 0;
    let mut count = 0;

    // 4080
    while utf8_chars.len() >= offset + 64 * 255 {
        let (mut count1, mut count2, mut count3, mut count4) =
            (vdupq_n_u8(0), vdupq_n_u8(0), vdupq_n_u8(0), vdupq_n_u8(0));

        for _ in 0..255 {
            let uint8x16x4_t(h1, h2, h3, h4) = u8x16_x4_from_offset(utf8_chars, offset);
            count1 = vsubq_u8(count1,is_following_utf8_byte(h1));
            count2 = vsubq_u8(count2,is_following_utf8_byte(h2));
            count3 = vsubq_u8(count3,is_following_utf8_byte(h3));
            count4 = vsubq_u8(count4,is_following_utf8_byte(h4));
            offset += 64;
        }
        count += sum4(count1, count2, count3, count4);
    }

    // 4080
    let (mut count1, mut count2, mut count3, mut count4) =
        (vdupq_n_u8(0), vdupq_n_u8(0), vdupq_n_u8(0), vdupq_n_u8(0));
        for _ in 0..(utf8_chars.len() - offset) / 64 {
            let uint8x16x4_t(h1, h2, h3, h4) = u8x16_x4_from_offset(utf8_chars, offset);
            count1 = vsubq_u8(count1, is_following_utf8_byte(h1));
            count2 = vsubq_u8(count2, is_following_utf8_byte(h2));
            count3 = vsubq_u8(count3, is_following_utf8_byte(h3));
            count4 = vsubq_u8(count4, is_following_utf8_byte(h4));
            offset += 64;
        }
        count += sum4(count1, count2, count3, count4);
    // 16
    let mut counts = vdupq_n_u8(0);
    for i in 0..(utf8_chars.len() - offset) / 16 {
        counts = vsubq_u8(
            counts,
            is_following_utf8_byte(u8x16_from_offset(utf8_chars, offset + i * 16)),
        );
    }
    if utf8_chars.len() % 16 != 0 {
        counts = vsubq_u8(
            counts,
            vandq_u8(
                is_following_utf8_byte(u8x16_from_offset(utf8_chars, utf8_chars.len() - 16)),
                u8x16_from_offset(&MASK, utf8_chars.len() % 16),
            ),
        );
    }
    count += sum(counts);

    utf8_chars.len() - count
}


================================================
FILE: src/simd/generic.rs
================================================


#[cfg(not(feature = "runtime-dispatch-simd"))]
use core::{mem, simd};

#[cfg(feature = "runtime-dispatch-simd")]
use std::{mem, simd};

use simd::{u8x32, u8x64, cmp::SimdPartialEq, num::SimdInt};

const MASK: [u8; 64] = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];

unsafe fn u8x64_from_offset(slice: &[u8], offset: usize) -> u8x64 {
    u8x64::from_slice(slice.get_unchecked(offset..))
}
unsafe fn u8x32_from_offset(slice: &[u8], offset: usize) -> u8x32 {
    u8x32::from_slice(slice.get_unchecked(offset..))
}

fn sum_x64(u8s: &u8x64) -> usize {
    let mut store = [0; mem::size_of::<u8x64>()];
    u8s.copy_to_slice(&mut store);
    store.iter().map(|&e| e as usize).sum()
}
fn sum_x32(u8s: &u8x32) -> usize {
    let mut store = [0; mem::size_of::<u8x32>()];
    u8s.copy_to_slice(&mut store);
    store.iter().map(|&e| e as usize).sum()
}

pub fn chunk_count(haystack: &[u8], needle: u8) -> usize {
    assert!(haystack.len() >= 32);

    unsafe {
        let mut offset = 0;
        let mut count = 0;

        let needles_x64 = u8x64::splat(needle);

        // 16320
        while haystack.len() >= offset + 64 * 255 {
            let mut counts = u8x64::splat(0);
            for _ in 0..255 {
                counts -= u8x64_from_offset(haystack, offset).simd_eq(needles_x64).to_int().cast();
                offset += 64;
            }
            count += sum_x64(&counts);
        }

        // 8192
        if haystack.len() >= offset + 64 * 128 {
            let mut counts = u8x64::splat(0);
            for _ in 0..128 {
                counts -= u8x64_from_offset(haystack, offset).simd_eq(needles_x64).to_int().cast();
                offset += 64;
            }
            count += sum_x64(&counts);
        }

        let needles_x32 = u8x32::splat(needle);

        // 32
        let mut counts = u8x32::splat(0);
        for i in 0..(haystack.len() - offset) / 32 {
            counts -=
                u8x32_from_offset(haystack, offset + i * 32).simd_eq(needles_x32).to_int().cast();
        }
        count += sum_x32(&counts);

        // Straggler; need to reset counts because prior loop can run 255 times
        counts = u8x32::splat(0);
        if haystack.len() % 32 != 0 {
            counts -=
                u8x32_from_offset(haystack, haystack.len() - 32).simd_eq(needles_x32).to_int().cast()
                    & u8x32_from_offset(&MASK, haystack.len() % 32);
        }
        count += sum_x32(&counts);

        count
    }
}

fn is_leading_utf8_byte_x64(u8s: u8x64) -> u8x64 {
    (u8s & u8x64::splat(0b1100_0000)).simd_ne(u8x64::splat(0b1000_0000)).to_int().cast()
}

fn is_leading_utf8_byte_x32(u8s: u8x32) -> u8x32 {
    (u8s & u8x32::splat(0b1100_0000)).simd_ne(u8x32::splat(0b1000_0000)).to_int().cast()
}

pub fn chunk_num_chars(utf8_chars: &[u8]) -> usize {
    assert!(utf8_chars.len() >= 32);

    unsafe {
        let mut offset = 0;
        let mut count = 0;

        // 16320
        while utf8_chars.len() >= offset + 64 * 255 {
            let mut counts = u8x64::splat(0);
            for _ in 0..255 {
                counts -= is_leading_utf8_byte_x64(u8x64_from_offset(utf8_chars, offset));
                offset += 64;
            }
            count += sum_x64(&counts);
        }

        // 8192
        if utf8_chars.len() >= offset + 64 * 128 {
            let mut counts = u8x64::splat(0);
            for _ in 0..128 {
                counts -= is_leading_utf8_byte_x64(u8x64_from_offset(utf8_chars, offset));
                offset += 64;
            }
            count += sum_x64(&counts);
        }

        // 32
        let mut counts = u8x32::splat(0);
        for i in 0..(utf8_chars.len() - offset) / 32 {
            counts -= is_leading_utf8_byte_x32(u8x32_from_offset(utf8_chars, offset + i * 32));
        }
        count += sum_x32(&counts);

        // Straggler; need to reset counts because prior loop can run 255 times
        counts = u8x32::splat(0);
        if utf8_chars.len() % 32 != 0 {
            counts -=
                is_leading_utf8_byte_x32(u8x32_from_offset(utf8_chars, utf8_chars.len() - 32))
                    & u8x32_from_offset(&MASK, utf8_chars.len() % 32);
        }
        count += sum_x32(&counts);

        count
    }
}


================================================
FILE: src/simd/mod.rs
================================================
#[cfg(feature = "generic-simd")]
pub mod generic;

// This is like generic, but written explicitly
// because generic SIMD requires nightly.
#[cfg(all(
    feature = "runtime-dispatch-simd",
    any(target_arch = "x86", target_arch = "x86_64"),
    not(feature = "generic-simd")
))]
pub mod x86_sse2;

// Modern x86 machines can do lots of fun stuff;
// this is where the *real* optimizations go.
// Runtime feature detection is not available with no_std.
#[cfg(all(feature = "runtime-dispatch-simd", target_arch = "x86_64"))]
pub mod x86_avx2;

/// Modern ARM machines are also quite capable thanks to NEON
#[cfg(target_arch = "aarch64")]
pub mod aarch64;

#[cfg(target_arch = "wasm32")]
pub mod wasm;

================================================
FILE: src/simd/wasm.rs
================================================
use core::arch::wasm32::*;

const MASK: [u8; 32] = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255,
];

#[target_feature(enable = "simd128")]
unsafe fn u8x16_from_offset(slice: &[u8], offset: usize) -> v128 {
    debug_assert!(
        offset + 16 <= slice.len(),
        "{} + 16 ≥ {}",
        offset,
        slice.len()
    );
    v128_load(slice.as_ptr().add(offset) as *const _)
}

// Load four 16-byte vectors from a slice at a given offset.
// This function assumes that the slice has at least 64 bytes available from the offset.
#[target_feature(enable = "simd128")]
unsafe fn u8x16x4_from_offset(slice: &[u8], offset: usize) -> (v128, v128, v128, v128) {
    debug_assert!(
        offset + 64 <= slice.len(),
        "{} + 64 ≥ {}",
        offset,
        slice.len()
    );
    (
        v128_load(slice.as_ptr().add(offset + 0) as *const _),
        v128_load(slice.as_ptr().add(offset + 16) as *const _),
        v128_load(slice.as_ptr().add(offset + 32) as *const _),
        v128_load(slice.as_ptr().add(offset + 48) as *const _),
    )
}

// TODO: We might want to amortize some additions by
// keeping in multiple u16s and u32s respectively for a few ns
#[target_feature(enable = "simd128")]
unsafe fn sum(u8s: v128) -> usize {
    let u16s = u16x8_extadd_pairwise_u8x16(u8s);
    let u32s = u32x4_extadd_pairwise_u16x8(u16s);
    let (u1, u2, u3, u4) = (
        u32x4_extract_lane::<0>(u32s),
        u32x4_extract_lane::<1>(u32s),
        u32x4_extract_lane::<2>(u32s),
        u32x4_extract_lane::<3>(u32s),
    );
    ((u1 + u2) + (u3 + u4)) as usize
}

#[target_feature(enable = "simd128")]
unsafe fn sum4(u1: v128, u2: v128, u3: v128, u4: v128) -> usize {
    // sum < (2^2 * 2^3 * 2^8 = 2^13) < 2^16, therefore no overflow here
    let u16s = u16x8_add(
        u16x8_add(
            u16x8_extadd_pairwise_u8x16(u1),
            u16x8_extadd_pairwise_u8x16(u2),
        ),
        u16x8_add(
            u16x8_extadd_pairwise_u8x16(u3),
            u16x8_extadd_pairwise_u8x16(u4),
        ),
    );
    let u32s = u32x4_extadd_pairwise_u16x8(u16s);
    let (u1, u2, u3, u4) = (
        u32x4_extract_lane::<0>(u32s),
        u32x4_extract_lane::<1>(u32s),
        u32x4_extract_lane::<2>(u32s),
        u32x4_extract_lane::<3>(u32s),
    );
    ((u1 + u2) + (u3 + u4)) as usize
}

#[target_feature(enable = "simd128")]
pub unsafe fn chunk_count(haystack: &[u8], needle: u8) -> usize {
    let needles = u8x16_splat(needle);
    let mut count = 0;
    let mut offset = 0;

    while haystack.len() >= offset + 64 * 255 {
        let (mut count1, mut count2, mut count3, mut count4) = (
            u8x16_splat(0),
            u8x16_splat(0),
            u8x16_splat(0),
            u8x16_splat(0),
        );
        for _ in 0..255 {
            let (h1, h2, h3, h4) = u8x16x4_from_offset(haystack, offset);
            count1 = u8x16_sub(count1, u8x16_eq(h1, needles));
            count2 = u8x16_sub(count2, u8x16_eq(h2, needles));
            count3 = u8x16_sub(count3, u8x16_eq(h3, needles));
            count4 = u8x16_sub(count4, u8x16_eq(h4, needles));
            offset += 64;
        }
        count += sum4(count1, count2, count3, count4);
    }

    // 64
    let (mut count1, mut count2, mut count3, mut count4) = (
        u8x16_splat(0),
        u8x16_splat(0),
        u8x16_splat(0),
        u8x16_splat(0),
    );
    for _ in 0..(haystack.len() - offset) / 64 {
        let (h1, h2, h3, h4) = u8x16x4_from_offset(haystack, offset);
        count1 = u8x16_sub(count1, u8x16_eq(h1, needles));
        count2 = u8x16_sub(count2, u8x16_eq(h2, needles));
        count3 = u8x16_sub(count3, u8x16_eq(h3, needles));
        count4 = u8x16_sub(count4, u8x16_eq(h4, needles));
        offset += 64;
    }
    count += sum4(count1, count2, count3, count4);

    let mut counts = u8x16_splat(0);
    // 16
    for i in 0..(haystack.len() - offset) / 16 {
        counts = u8x16_sub(
            counts,
            u8x16_eq(u8x16_from_offset(haystack, offset + i * 16), needles),
        );
    }
    if haystack.len() % 16 != 0 {
        counts = u8x16_sub(
            counts,
            v128_and(
                u8x16_eq(u8x16_from_offset(haystack, haystack.len() - 16), needles),
                u8x16_from_offset(&MASK, haystack.len() % 16),
            ),
        );
    }
    count + sum(counts)
}

#[target_feature(enable = "simd128")]
unsafe fn is_leading_utf8_byte(u8s: v128) -> v128 {
    u8x16_ne(
        v128_and(u8s, u8x16_splat(0b1100_0000)),
        u8x16_splat(0b1000_0000),
    )
}

#[target_feature(enable = "simd128")]
pub unsafe fn chunk_num_chars(utf8_chars: &[u8]) -> usize {
    assert!(utf8_chars.len() >= 16);

    let mut offset = 0;
    let mut count = 0;

    // 4080
    while utf8_chars.len() >= offset + 64 * 255 {
        let (mut count1, mut count2, mut count3, mut count4) = (
            u8x16_splat(0),
            u8x16_splat(0),
            u8x16_splat(0),
            u8x16_splat(0),
        );

        for _ in 0..255 {
            let (h1, h2, h3, h4) = u8x16x4_from_offset(utf8_chars, offset);
            count1 = u8x16_sub(count1, is_leading_utf8_byte(h1));
            count2 = u8x16_sub(count2, is_leading_utf8_byte(h2));
            count3 = u8x16_sub(count3, is_leading_utf8_byte(h3));
            count4 = u8x16_sub(count4, is_leading_utf8_byte(h4));
            offset += 64;
        }
        count += sum4(count1, count2, count3, count4);
    }

    // 4080
    let (mut count1, mut count2, mut count3, mut count4) = (
        u8x16_splat(0),
        u8x16_splat(0),
        u8x16_splat(0),
        u8x16_splat(0),
    );
    for _ in 0..(utf8_chars.len() - offset) / 64 {
        let (h1, h2, h3, h4) = u8x16x4_from_offset(utf8_chars, offset);
        count1 = u8x16_sub(count1, is_leading_utf8_byte(h1));
        count2 = u8x16_sub(count2, is_leading_utf8_byte(h2));
        count3 = u8x16_sub(count3, is_leading_utf8_byte(h3));
        count4 = u8x16_sub(count4, is_leading_utf8_byte(h4));
        offset += 64;
    }
    count += sum4(count1, count2, count3, count4);

    // 16
    let mut counts = u8x16_splat(0);
    for i in 0..(utf8_chars.len() - offset) / 16 {
        counts = u8x16_sub(
            counts,
            is_leading_utf8_byte(u8x16_from_offset(utf8_chars, offset + i * 16)),
        );
    }
    if utf8_chars.len() % 16 != 0 {
        counts = u8x16_sub(
            counts,
            v128_and(
                is_leading_utf8_byte(u8x16_from_offset(utf8_chars, utf8_chars.len() - 16)),
                u8x16_from_offset(&MASK, utf8_chars.len() % 16),
            ),
        );
    }
    count += sum(counts);

    count
}


================================================
FILE: src/simd/x86_avx2.rs
================================================
use std::arch::x86_64::{
    __m256i, _mm256_and_si256, _mm256_cmpeq_epi8, _mm256_extract_epi64, _mm256_loadu_si256,
    _mm256_sad_epu8, _mm256_set1_epi8, _mm256_setzero_si256, _mm256_sub_epi8, _mm256_xor_si256,
};

#[target_feature(enable = "avx2")]
pub unsafe fn _mm256_set1_epu8(a: u8) -> __m256i {
    _mm256_set1_epi8(a as i8)
}

#[target_feature(enable = "avx2")]
pub unsafe fn mm256_cmpneq_epi8(a: __m256i, b: __m256i) -> __m256i {
    _mm256_xor_si256(_mm256_cmpeq_epi8(a, b), _mm256_set1_epi8(-1))
}

const MASK: [u8; 64] = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];

#[target_feature(enable = "avx2")]
unsafe fn mm256_from_offset(slice: &[u8], offset: usize) -> __m256i {
    _mm256_loadu_si256(slice.as_ptr().add(offset) as *const _)
}

#[target_feature(enable = "avx2")]
unsafe fn sum(u8s: &__m256i) -> usize {
    let sums = _mm256_sad_epu8(*u8s, _mm256_setzero_si256());
    (_mm256_extract_epi64(sums, 0)
        + _mm256_extract_epi64(sums, 1)
        + _mm256_extract_epi64(sums, 2)
        + _mm256_extract_epi64(sums, 3)) as usize
}

#[target_feature(enable = "avx2")]
pub unsafe fn chunk_count(haystack: &[u8], needle: u8) -> usize {
    assert!(haystack.len() >= 32);

    let mut offset = 0;
    let mut count = 0;

    let needles = _mm256_set1_epu8(needle);

    // 8160
    while haystack.len() >= offset + 32 * 255 {
        let mut counts = _mm256_setzero_si256();
        for _ in 0..255 {
            counts = _mm256_sub_epi8(
                counts,
                _mm256_cmpeq_epi8(mm256_from_offset(haystack, offset), needles),
            );
            offset += 32;
        }
        count += sum(&counts);
    }

    // 4096
    if haystack.len() >= offset + 32 * 128 {
        let mut counts = _mm256_setzero_si256();
        for _ in 0..128 {
            counts = _mm256_sub_epi8(
                counts,
                _mm256_cmpeq_epi8(mm256_from_offset(haystack, offset), needles),
            );
            offset += 32;
        }
        count += sum(&counts);
    }

    // 32
    let mut counts = _mm256_setzero_si256();
    for i in 0..(haystack.len() - offset) / 32 {
        counts = _mm256_sub_epi8(
            counts,
            _mm256_cmpeq_epi8(mm256_from_offset(haystack, offset + i * 32), needles),
        );
    }
    if haystack.len() % 32 != 0 {
        counts = _mm256_sub_epi8(
            counts,
            _mm256_and_si256(
                _mm256_cmpeq_epi8(mm256_from_offset(haystack, haystack.len() - 32), needles),
                mm256_from_offset(&MASK, haystack.len() % 32),
            ),
        );
    }
    count += sum(&counts);

    count
}

#[target_feature(enable = "avx2")]
unsafe fn is_leading_utf8_byte(u8s: __m256i) -> __m256i {
    mm256_cmpneq_epi8(
        _mm256_and_si256(u8s, _mm256_set1_epu8(0b1100_0000)),
        _mm256_set1_epu8(0b1000_0000),
    )
}

#[target_feature(enable = "avx2")]
pub unsafe fn chunk_num_chars(utf8_chars: &[u8]) -> usize {
    assert!(utf8_chars.len() >= 32);

    let mut offset = 0;
    let mut count = 0;

    // 8160
    while utf8_chars.len() >= offset + 32 * 255 {
        let mut counts = _mm256_setzero_si256();

        for _ in 0..255 {
            counts = _mm256_sub_epi8(
                counts,
                is_leading_utf8_byte(mm256_from_offset(utf8_chars, offset)),
            );
            offset += 32;
        }
        count += sum(&counts);
    }

    // 4096
    if utf8_chars.len() >= offset + 32 * 128 {
        let mut counts = _mm256_setzero_si256();
        for _ in 0..128 {
            counts = _mm256_sub_epi8(
                counts,
                is_leading_utf8_byte(mm256_from_offset(utf8_chars, offset)),
            );
            offset += 32;
        }
        count += sum(&counts);
    }

    // 32
    let mut counts = _mm256_setzero_si256();
    for i in 0..(utf8_chars.len() - offset) / 32 {
        counts = _mm256_sub_epi8(
            counts,
            is_leading_utf8_byte(mm256_from_offset(utf8_chars, offset + i * 32)),
        );
    }
    if utf8_chars.len() % 32 != 0 {
        counts = _mm256_sub_epi8(
            counts,
            _mm256_and_si256(
                is_leading_utf8_byte(mm256_from_offset(utf8_chars, utf8_chars.len() - 32)),
                mm256_from_offset(&MASK, utf8_chars.len() % 32),
            ),
        );
    }
    count += sum(&counts);

    count
}


================================================
FILE: src/simd/x86_sse2.rs
================================================
#[cfg(target_arch = "x86")]
use std::arch::x86::{
    __m128i,
    _mm_and_si128,
    _mm_cmpeq_epi8,
    _mm_cvtsi128_si32,
    _mm_loadu_si128,
    _mm_sad_epu8,
    _mm_set1_epi8,
    _mm_setzero_si128,
    _mm_shuffle_epi32,
    _mm_sub_epi8,
    _mm_xor_si128,
};

#[cfg(target_arch = "x86_64")]
use std::arch::x86_64::{
    __m128i,
    _mm_and_si128,
    _mm_cmpeq_epi8,
    _mm_cvtsi128_si32,
    _mm_loadu_si128,
    _mm_sad_epu8,
    _mm_set1_epi8,
    _mm_setzero_si128,
    _mm_shuffle_epi32,
    _mm_sub_epi8,
    _mm_xor_si128,
};

#[target_feature(enable = "sse2")]
pub unsafe fn _mm_set1_epu8(a: u8) -> __m128i {
    _mm_set1_epi8(a as i8)
}

#[target_feature(enable = "sse2")]
pub unsafe fn mm_cmpneq_epi8(a: __m128i, b: __m128i) -> __m128i {
    _mm_xor_si128(_mm_cmpeq_epi8(a, b), _mm_set1_epi8(-1))
}

const MASK: [u8; 32] = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];

#[target_feature(enable = "sse2")]
unsafe fn mm_from_offset(slice: &[u8], offset: usize) -> __m128i {
    _mm_loadu_si128(slice.as_ptr().offset(offset as isize) as *const _)
}

#[target_feature(enable = "sse2")]
unsafe fn sum(u8s: &__m128i) -> usize {
    let sums = _mm_sad_epu8(*u8s, _mm_setzero_si128());
    (_mm_cvtsi128_si32(sums) + _mm_cvtsi128_si32(_mm_shuffle_epi32(sums, 0xaa))) as usize
}

#[target_feature(enable = "sse2")]
pub unsafe fn chunk_count(haystack: &[u8], needle: u8) -> usize {
    assert!(haystack.len() >= 16);

    let mut offset = 0;
    let mut count = 0;

    let needles = _mm_set1_epu8(needle);

    // 4080
    while haystack.len() >= offset + 16 * 255 {
        let mut counts = _mm_setzero_si128();
        for _ in 0..255 {
            counts = _mm_sub_epi8(
                counts,
                _mm_cmpeq_epi8(mm_from_offset(haystack, offset), needles)
            );
            offset += 16;
        }
        count += sum(&counts);
    }

    // 2048
    if haystack.len() >= offset + 16 * 128 {
        let mut counts = _mm_setzero_si128();
        for _ in 0..128 {
            counts = _mm_sub_epi8(
                counts,
                _mm_cmpeq_epi8(mm_from_offset(haystack, offset), needles)
            );
            offset += 16;
        }
        count += sum(&counts);
    }

    // 16
    let mut counts = _mm_setzero_si128();
    for i in 0..(haystack.len() - offset) / 16 {
        counts = _mm_sub_epi8(
            counts,
            _mm_cmpeq_epi8(mm_from_offset(haystack, offset + i * 16), needles)
        );
    }
    if haystack.len() % 16 != 0 {
        counts = _mm_sub_epi8(
            counts,
            _mm_and_si128(
                _mm_cmpeq_epi8(mm_from_offset(haystack, haystack.len() - 16), needles),
                                  mm_from_offset(&MASK, haystack.len() % 16)
            )
        );
    }
    count += sum(&counts);

    count
}

#[target_feature(enable = "sse2")]
unsafe fn is_leading_utf8_byte(u8s: __m128i) -> __m128i {
    mm_cmpneq_epi8(_mm_and_si128(u8s, _mm_set1_epu8(0b1100_0000)), _mm_set1_epu8(0b1000_0000))
}

#[target_feature(enable = "sse2")]
pub unsafe fn chunk_num_chars(utf8_chars: &[u8]) -> usize {
    assert!(utf8_chars.len() >= 16);

    let mut offset = 0;
    let mut count = 0;

    // 4080
    while utf8_chars.len() >= offset + 16 * 255 {
        let mut counts = _mm_setzero_si128();

        for _ in 0..255 {
            counts = _mm_sub_epi8(
                counts,
                is_leading_utf8_byte(mm_from_offset(utf8_chars, offset))
            );
            offset += 16;
        }
        count += sum(&counts);
    }

    // 2048
    if utf8_chars.len() >= offset + 16 * 128 {
        let mut counts = _mm_setzero_si128();
        for _ in 0..128 {
            counts = _mm_sub_epi8(
                counts,
                is_leading_utf8_byte(mm_from_offset(utf8_chars, offset))
            );
            offset += 16;
        }
        count += sum(&counts);
    }

    // 16
    let mut counts = _mm_setzero_si128();
    for i in 0..(utf8_chars.len() - offset) / 16 {
        counts = _mm_sub_epi8(
            counts,
            is_leading_utf8_byte(mm_from_offset(utf8_chars, offset + i * 16))
        );
    }
    if utf8_chars.len() % 16 != 0 {
        counts = _mm_sub_epi8(
            counts,
            _mm_and_si128(
                is_leading_utf8_byte(mm_from_offset(utf8_chars, utf8_chars.len() - 16)),
                                     mm_from_offset(&MASK,      utf8_chars.len() % 16)
            )
        );
    }
    count += sum(&counts);

    count
}


================================================
FILE: tests/check.rs
================================================
extern crate bytecount;
#[macro_use]
extern crate quickcheck;
extern crate rand;

use bytecount::{count, naive_count, naive_num_chars, num_chars};
use rand::RngCore;

fn random_bytes(len: usize) -> Vec<u8> {
    let mut result = vec![0; len];
    rand::thread_rng().fill_bytes(&mut result);
    result
}

quickcheck! {
    fn check_count_correct(x: (Vec<u8>, u8)) -> bool {
        let (haystack, needle) = x;
        count(&haystack, needle) == naive_count(&haystack, needle)
    }
}

#[test]
fn check_count_large() {
    let haystack = vec![0u8; if cfg!(miri) { 2_000 } else { 10_000_000 }];
    assert_eq!(naive_count(&haystack, 0), count(&haystack, 0));
    assert_eq!(naive_count(&haystack, 1), count(&haystack, 1));
}

#[test]
fn check_count_large_rand() {
    let haystack = random_bytes(if cfg!(miri) { 200 } else { 100_000 });
    for i in 0..=255 {
        assert_eq!(naive_count(&haystack, i), count(&haystack, i));
    }
}

#[test]
fn check_count_some() {
    let haystack = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68];
    let needle = 68;
    assert_eq!(count(&haystack, needle), naive_count(&haystack, needle));
}

#[test]
fn check_count_overflow() {
    let haystack = vec![0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    let needle = 2;
    assert_eq!(count(&haystack, needle), naive_count(&haystack, needle));
}

#[test]
fn check_count_overflow_many() {
    let string = [b'x'; 20000];
    for i in 0..20000 {
        assert_eq!(count(&string[..i], b'x'), i);
    }
}

quickcheck! {
    fn check_num_chars_correct(haystack: Vec<u8>) -> bool {
        num_chars(&haystack) == naive_num_chars(&haystack)
    }
}

#[test]
fn check_num_chars_large() {
    let haystack = vec![0u8; if cfg!(miri) { 2_000 } else { 10_000_000 }];
    assert_eq!(naive_num_chars(&haystack), num_chars(&haystack));
    assert_eq!(naive_num_chars(&haystack), num_chars(&haystack));
}

#[test]
fn check_num_chars_some() {
    let haystack = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68];
    assert_eq!(num_chars(&haystack), naive_num_chars(&haystack));
}

#[test]
fn check_num_chars_overflow() {
    let haystack = vec![0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    assert_eq!(num_chars(&haystack), naive_num_chars(&haystack));
}

#[test]
fn check_num_chars_overflow_many() {
    let string = [b'x'; 20000];
    for i in 0..20000 {
        assert_eq!(num_chars(&string[..i]), i);
    }
}
Download .txt
gitextract_fy6189iu/

├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── Cargo.toml
├── LICENSE.Apache2
├── LICENSE.MIT
├── README.md
├── appveyor.yml
├── benches/
│   └── bench.rs
├── ci/
│   └── miri.sh
├── src/
│   ├── integer_simd.rs
│   ├── lib.rs
│   ├── naive.rs
│   └── simd/
│       ├── aarch64.rs
│       ├── generic.rs
│       ├── mod.rs
│       ├── wasm.rs
│       ├── x86_avx2.rs
│       └── x86_sse2.rs
└── tests/
    └── check.rs
Download .txt
SYMBOL INDEX (68 symbols across 10 files)

FILE: benches/bench.rs
  function random_bytes (line 13) | fn random_bytes(len: usize) -> Vec<u8> {
  function get_counts (line 25) | fn get_counts() -> Vec<usize> {
  function get_config (line 35) | fn get_config() -> Criterion {
  function bench_counts (line 47) | fn bench_counts(criterion: &mut Criterion) {
  function bench_num_chars (line 70) | fn bench_num_chars(criterion: &mut Criterion) {

FILE: src/integer_simd.rs
  function splat (line 6) | fn splat(byte: u8) -> usize {
  function usize_load_unchecked (line 11) | unsafe fn usize_load_unchecked(bytes: &[u8], offset: usize) -> usize {
  function bytewise_equal (line 21) | fn bytewise_equal(lhs: usize, rhs: usize) -> usize {
  function sum_usize (line 29) | fn sum_usize(values: usize) -> usize {
  function is_leading_utf8_byte (line 40) | fn is_leading_utf8_byte(values: usize) -> usize {
  function chunk_count (line 45) | pub fn chunk_count(haystack: &[u8], needle: u8) -> usize {
  function chunk_num_chars (line 86) | pub fn chunk_num_chars(utf8_chars: &[u8]) -> usize {

FILE: src/lib.rs
  function count (line 67) | pub fn count(haystack: &[u8], needle: u8) -> usize {
  function num_chars (line 133) | pub fn num_chars(utf8_chars: &[u8]) -> usize {

FILE: src/naive.rs
  function naive_count_32 (line 11) | pub fn naive_count_32(haystack: &[u8], needle: u8) -> usize {
  function naive_count (line 24) | pub fn naive_count(utf8_chars: &[u8], needle: u8) -> usize {
  function naive_num_chars (line 42) | pub fn naive_num_chars(utf8_chars: &[u8]) -> usize {

FILE: src/simd/aarch64.rs
  constant MASK (line 6) | const MASK: [u8; 32] = [
  function u8x16_from_offset (line 12) | unsafe fn u8x16_from_offset(slice: &[u8], offset: usize) -> uint8x16_t {
  function u8x16_x4_from_offset (line 23) | unsafe fn u8x16_x4_from_offset(slice: &[u8], offset: usize) -> uint8x16x...
  function sum (line 34) | unsafe fn sum(u8s: uint8x16_t) -> usize {
  function sum4 (line 38) | unsafe fn sum4(u1: uint8x16_t, u2: uint8x16_t, u3: uint8x16_t, u4: uint8...
  function chunk_count (line 43) | pub unsafe fn chunk_count(haystack: &[u8], needle: u8) -> usize {
  function is_following_utf8_byte (line 100) | unsafe fn is_following_utf8_byte(u8s: uint8x16_t) -> uint8x16_t {
  function chunk_num_chars (line 108) | pub unsafe fn chunk_num_chars(utf8_chars: &[u8]) -> usize {

FILE: src/simd/generic.rs
  constant MASK (line 11) | const MASK: [u8; 64] = [
  function u8x64_from_offset (line 17) | unsafe fn u8x64_from_offset(slice: &[u8], offset: usize) -> u8x64 {
  function u8x32_from_offset (line 20) | unsafe fn u8x32_from_offset(slice: &[u8], offset: usize) -> u8x32 {
  function sum_x64 (line 24) | fn sum_x64(u8s: &u8x64) -> usize {
  function sum_x32 (line 29) | fn sum_x32(u8s: &u8x32) -> usize {
  function chunk_count (line 35) | pub fn chunk_count(haystack: &[u8], needle: u8) -> usize {
  function is_leading_utf8_byte_x64 (line 87) | fn is_leading_utf8_byte_x64(u8s: u8x64) -> u8x64 {
  function is_leading_utf8_byte_x32 (line 91) | fn is_leading_utf8_byte_x32(u8s: u8x32) -> u8x32 {
  function chunk_num_chars (line 95) | pub fn chunk_num_chars(utf8_chars: &[u8]) -> usize {

FILE: src/simd/wasm.rs
  constant MASK (line 3) | const MASK: [u8; 32] = [
  function u8x16_from_offset (line 9) | unsafe fn u8x16_from_offset(slice: &[u8], offset: usize) -> v128 {
  function u8x16x4_from_offset (line 22) | unsafe fn u8x16x4_from_offset(slice: &[u8], offset: usize) -> (v128, v12...
  function sum (line 40) | unsafe fn sum(u8s: v128) -> usize {
  function sum4 (line 53) | unsafe fn sum4(u1: v128, u2: v128, u3: v128, u4: v128) -> usize {
  function chunk_count (line 76) | pub unsafe fn chunk_count(haystack: &[u8], needle: u8) -> usize {
  function is_leading_utf8_byte (line 137) | unsafe fn is_leading_utf8_byte(u8s: v128) -> v128 {
  function chunk_num_chars (line 145) | pub unsafe fn chunk_num_chars(utf8_chars: &[u8]) -> usize {

FILE: src/simd/x86_avx2.rs
  function _mm256_set1_epu8 (line 7) | pub unsafe fn _mm256_set1_epu8(a: u8) -> __m256i {
  function mm256_cmpneq_epi8 (line 12) | pub unsafe fn mm256_cmpneq_epi8(a: __m256i, b: __m256i) -> __m256i {
  constant MASK (line 16) | const MASK: [u8; 64] = [
  function mm256_from_offset (line 23) | unsafe fn mm256_from_offset(slice: &[u8], offset: usize) -> __m256i {
  function sum (line 28) | unsafe fn sum(u8s: &__m256i) -> usize {
  function chunk_count (line 37) | pub unsafe fn chunk_count(haystack: &[u8], needle: u8) -> usize {
  function is_leading_utf8_byte (line 94) | unsafe fn is_leading_utf8_byte(u8s: __m256i) -> __m256i {
  function chunk_num_chars (line 102) | pub unsafe fn chunk_num_chars(utf8_chars: &[u8]) -> usize {

FILE: src/simd/x86_sse2.rs
  function _mm_set1_epu8 (line 32) | pub unsafe fn _mm_set1_epu8(a: u8) -> __m128i {
  function mm_cmpneq_epi8 (line 37) | pub unsafe fn mm_cmpneq_epi8(a: __m128i, b: __m128i) -> __m128i {
  constant MASK (line 41) | const MASK: [u8; 32] = [
  function mm_from_offset (line 47) | unsafe fn mm_from_offset(slice: &[u8], offset: usize) -> __m128i {
  function sum (line 52) | unsafe fn sum(u8s: &__m128i) -> usize {
  function chunk_count (line 58) | pub unsafe fn chunk_count(haystack: &[u8], needle: u8) -> usize {
  function is_leading_utf8_byte (line 115) | unsafe fn is_leading_utf8_byte(u8s: __m128i) -> __m128i {
  function chunk_num_chars (line 120) | pub unsafe fn chunk_num_chars(utf8_chars: &[u8]) -> usize {

FILE: tests/check.rs
  function random_bytes (line 9) | fn random_bytes(len: usize) -> Vec<u8> {
  function check_count_large (line 23) | fn check_count_large() {
  function check_count_large_rand (line 30) | fn check_count_large_rand() {
  function check_count_some (line 38) | fn check_count_some() {
  function check_count_overflow (line 45) | fn check_count_overflow() {
  function check_count_overflow_many (line 52) | fn check_count_overflow_many() {
  function check_num_chars_large (line 66) | fn check_num_chars_large() {
  function check_num_chars_some (line 73) | fn check_num_chars_some() {
  function check_num_chars_overflow (line 79) | fn check_num_chars_overflow() {
  function check_num_chars_overflow_many (line 85) | fn check_num_chars_overflow_many() {
Condensed preview — 20 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (67K chars).
[
  {
    "path": ".github/dependabot.yml",
    "chars": 145,
    "preview": "version: 2\nupdates:\n- package-ecosystem: cargo\n  directory: \"/\"\n  schedule:\n    interval: daily\n    time: \"04:00\"\n  open"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 2490,
    "preview": "on: \n  push:\n    branches:\n      - master\n  pull_request:\n\nname: Continuous integration\n\njobs:\n  test:\n    name: Test su"
  },
  {
    "path": ".gitignore",
    "chars": 18,
    "preview": "target\nCargo.lock\n"
  },
  {
    "path": "Cargo.toml",
    "chars": 806,
    "preview": "[package]\nauthors = [\"Andre Bogus <bogusandre@gmail.de>\", \"Joshua Landau <joshua@landau.ws>\"]\ndescription = \"count occur"
  },
  {
    "path": "LICENSE.Apache2",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "LICENSE.MIT",
    "chars": 1068,
    "preview": "Copyright (c) 2017 The bytecount Developers\n\nPermission is hereby granted, free of charge, to any person obtaining a cop"
  },
  {
    "path": "README.md",
    "chars": 2996,
    "preview": "# bytecount\n\nCounting bytes really fast\n\n[![Continuous integration](https://github.com/llogiq/bytecount/actions/workflow"
  },
  {
    "path": "appveyor.yml",
    "chars": 2468,
    "preview": "environment:\n    global:\n        PROJECT_NAME: bytecount\n        FEATURES: \"\"\n        RUSTFLAGS: \"\"\n        COUNTS: \"0,1"
  },
  {
    "path": "benches/bench.rs",
    "chars": 3054,
    "preview": "#[macro_use]\nextern crate criterion;\nextern crate bytecount;\nextern crate rand;\n\nuse criterion::{Bencher, BenchmarkId, C"
  },
  {
    "path": "ci/miri.sh",
    "chars": 369,
    "preview": "#!/bin/bash\nset -ex\n\n# Setup\nMIRI_NIGHTLY=nightly-$(curl -s https://rust-lang.github.io/rustup-components-history/x86_64"
  },
  {
    "path": "src/integer_simd.rs",
    "chars": 3619,
    "preview": "#[cfg(not(feature = \"runtime-dispatch-simd\"))]\nuse core::{mem, ptr, usize};\n#[cfg(feature = \"runtime-dispatch-simd\")]\nus"
  },
  {
    "path": "src/lib.rs",
    "chars": 5360,
    "preview": "//! count occurrences of a given byte, or the number of UTF-8 code points, in a\n//! byte slice, fast.\n//!\n//! This crate"
  },
  {
    "path": "src/naive.rs",
    "chars": 1343,
    "preview": "/// Count up to `(2^32)-1` occurrences of a byte in a slice\n/// of bytes, simple\n///\n/// # Example\n///\n/// ```\n/// let s"
  },
  {
    "path": "src/simd/aarch64.rs",
    "chars": 5529,
    "preview": "use core::arch::aarch64::{\n    uint8x16_t, uint8x16x4_t, vaddlvq_u8, vandq_u8, vceqq_u8, vdupq_n_u8, vld1q_u8, vld1q_u8_"
  },
  {
    "path": "src/simd/generic.rs",
    "chars": 4471,
    "preview": "\n\n#[cfg(not(feature = \"runtime-dispatch-simd\"))]\nuse core::{mem, simd};\n\n#[cfg(feature = \"runtime-dispatch-simd\")]\nuse s"
  },
  {
    "path": "src/simd/mod.rs",
    "chars": 702,
    "preview": "#[cfg(feature = \"generic-simd\")]\npub mod generic;\n\n// This is like generic, but written explicitly\n// because generic SI"
  },
  {
    "path": "src/simd/wasm.rs",
    "chars": 6735,
    "preview": "use core::arch::wasm32::*;\n\nconst MASK: [u8; 32] = [\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, "
  },
  {
    "path": "src/simd/x86_avx2.rs",
    "chars": 4597,
    "preview": "use std::arch::x86_64::{\n    __m256i, _mm256_and_si256, _mm256_cmpeq_epi8, _mm256_extract_epi64, _mm256_loadu_si256,\n   "
  },
  {
    "path": "src/simd/x86_sse2.rs",
    "chars": 4607,
    "preview": "#[cfg(target_arch = \"x86\")]\nuse std::arch::x86::{\n    __m128i,\n    _mm_and_si128,\n    _mm_cmpeq_epi8,\n    _mm_cvtsi128_s"
  },
  {
    "path": "tests/check.rs",
    "chars": 2415,
    "preview": "extern crate bytecount;\n#[macro_use]\nextern crate quickcheck;\nextern crate rand;\n\nuse bytecount::{count, naive_count, na"
  }
]

About this extraction

This page contains the full source code of the llogiq/bytecount GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 20 files (62.6 KB), approximately 19.1k tokens, and a symbol index with 68 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!