histo-1.0.0/.cargo_vcs_info.json0000644000000001360000000000100121600ustar { "git": { "sha1": "ae1d2fc733b07a24dbd6fd3b03ff2a782a9c7efc" }, "path_in_vcs": "" }histo-1.0.0/.gitignore000064400000000000000000000000371046102023000127400ustar 00000000000000/target/ **/*.rs.bk Cargo.lock histo-1.0.0/.travis.yml000064400000000000000000000006171046102023000130650ustar 00000000000000sudo: false language: rust rust: - nightly cache: cargo env: matrix: - JOB="test" PROFILE="" FEATURES="" - JOB="test" PROFILE="" FEATURES="quickcheck" - JOB="test" PROFILE="--release" FEATURES="" - JOB="test" PROFILE="--release" FEATURES="quickcheck" - JOB="bench" PROFILE="--release" FEATURES="" matrix: fast_finish: true script: ./ci/script.sh histo-1.0.0/Cargo.lock0000644000000144650000000000100101450ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca972c2ea5f742bfce5687b9aef75506a764f61d37f8f649047846a9686ddb66" dependencies = [ "memchr", ] [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "env_logger" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15abd780e45b3ea4f76b4e9a26ff4843258dd8a3eed2775a0e7368c2e7936c2f" dependencies = [ "log 0.3.9", "regex", ] [[package]] name = "fuchsia-cprng" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" [[package]] name = "histo" version = "1.0.0" dependencies = [ "quickcheck", "streaming-stats", ] [[package]] name = "kernel32-sys" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" dependencies = [ "winapi 0.2.8", "winapi-build", ] [[package]] name = "libc" version = "0.2.128" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95f2a930906a03d4ee59113b31586c057c94f4d40c9fe90f21597a8b6822bfd8" [[package]] name = "log" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e19e8d5c34a3e0e2223db8e060f9e8264aeeb5c5fc64a4ee9965c062211c024b" dependencies = [ "log 0.4.17", ] [[package]] name = "log" version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ "cfg-if", ] [[package]] name = "memchr" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b629fb514376c675b98c1421e80b151d3817ac42d7c667717d282761418d20" dependencies = [ "libc", ] [[package]] name = "num-traits" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" dependencies = [ "autocfg", ] [[package]] name = "quickcheck" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02c2411d418cea2364325b18a205664f9ef8252e06b2e911db97c0b0d98b1406" dependencies = [ "env_logger", "log 0.3.9", "rand 0.3.23", ] [[package]] name = "rand" version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64ac302d8f83c0c1974bf758f6b041c6c8ada916fbb44a609158ca8b064cc76c" dependencies = [ "libc", "rand 0.4.6", ] [[package]] name = "rand" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" dependencies = [ "fuchsia-cprng", "libc", "rand_core 0.3.1", "rdrand", "winapi 0.3.9", ] [[package]] name = "rand_core" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" dependencies = [ "rand_core 0.4.2", ] [[package]] name = "rand_core" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" [[package]] name = "rdrand" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" dependencies = [ "rand_core 0.3.1", ] [[package]] name = "regex" version = "0.1.80" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fd4ace6a8cf7860714a2c2280d6c1f7e6a413486c13298bbc86fd3da019402f" dependencies = [ "aho-corasick", "memchr", "regex-syntax", "thread_local", "utf8-ranges", ] [[package]] name = "regex-syntax" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9ec002c35e86791825ed294b50008eea9ddfc8def4420124fbc6b08db834957" [[package]] name = "streaming-stats" version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbc32bf233385fb1ae0c4cf13a8dfd11efec71f6a9de95feac8c870788bc8b25" dependencies = [ "num-traits", ] [[package]] name = "thread-id" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9539db560102d1cef46b8b78ce737ff0bb64e7e18d35b2a5688f7d097d0ff03" dependencies = [ "kernel32-sys", "libc", ] [[package]] name = "thread_local" version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8576dbbfcaef9641452d5cf0df9b0e7eeab7694956dd33bb61515fb8f18cfdd5" dependencies = [ "thread-id", ] [[package]] name = "utf8-ranges" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1ca13c08c41c9c3e04224ed9ff80461d97e121589ff27c753a16cb10830ae0f" [[package]] name = "winapi" version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-build" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" histo-1.0.0/Cargo.toml0000644000000020230000000000100101530ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "histo" version = "1.0.0" authors = ["Nick Fitzgerald "] description = "Simple histograms with configurable buckets" documentation = "https://docs.rs/histo" readme = "README.md" keywords = [ "histogram", "stddev", "mean", ] license = "Apache-2.0/MIT" repository = "https://github.com/fitzgen/histo" resolver = "2" [[bin]] name = "histo" doc = false [dependencies.quickcheck] version = "0.4.1" optional = true [dependencies.streaming-stats] version = "0.1.28" [badges.travis-ci] repository = "fitzgen/histo" histo-1.0.0/Cargo.toml.orig000064400000000000000000000010401046102023000136320ustar 00000000000000[package] authors = ["Nick Fitzgerald "] description = "Simple histograms with configurable buckets" documentation = "https://docs.rs/histo" edition = "2021" keywords = ["histogram", "stddev", "mean"] license = "Apache-2.0/MIT" name = "histo" readme = "README.md" repository = "https://github.com/fitzgen/histo" version = "1.0.0" [badges] travis-ci = { repository = "fitzgen/histo" } [[bin]] name = "histo" doc = false [dependencies] streaming-stats = "0.1.28" [dependencies.quickcheck] optional = true version = "0.4.1" histo-1.0.0/LICENSE-APACHE000064400000000000000000000251371046102023000127040ustar 00000000000000 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. histo-1.0.0/LICENSE-MIT000064400000000000000000000020571046102023000124100ustar 00000000000000Copyright (c) 2015 The Rust Project 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. histo-1.0.0/README.md000064400000000000000000000061301046102023000122270ustar 00000000000000# `histo` [![Build Status](https://travis-ci.org/fitzgen/histo.png?branch=master)](https://travis-ci.org/fitzgen/histo) [![histo on crates.io](https://img.shields.io/crates/v/histo.svg)](https://crates.io/crates/histo) [![histo on docs.rs](https://docs.rs/histo/badge.svg)](https://docs.rs/histo/) Histograms with a configurable number of buckets, and a terminal-friendly `Display`. This crate provides a `Histogram` type that allows configuration of the number of buckets that will be used, regardless of the range of input samples. This is useful when displaying a `Histogram` (for example, when printing it to a terminal) but it sacrifices fancy tracking of precision and significant figures. It uses O(n) memory. ```rust extern crate histo; use histo::Histogram; // Create a histogram that will have 10 buckets. let mut histogram = Histogram::with_buckets(10); // Adds some samples to the histogram. for sample in 0..100 { histogram.add(sample); histogram.add(sample * sample); } // Iterate over buckets and do stuff with their range and count. for bucket in histogram.buckets() { do_stuff(bucket.start(), bucket.end(), bucket.count()); } // And you can also `Display` a histogram! println!("{}", histogram); // Prints: // // ``` // # Number of samples = 200 // # Min = 0 // # Max = 9801 // # // # Mean = 1666.5000000000005 // # Standard deviation = 2641.2281518263426 // # Variance = 6976086.1499999985 // # // # Each ∎ is a count of 2 // # // 0 .. 980 [ 132 ]: ∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ // 980 .. 1960 [ 13 ]: ∎∎∎∎∎∎ // 1960 .. 2940 [ 10 ]: ∎∎∎∎∎ // 2940 .. 3920 [ 8 ]: ∎∎∎∎ // 3920 .. 4900 [ 7 ]: ∎∎∎ // 4900 .. 5880 [ 7 ]: ∎∎∎ // 5880 .. 6860 [ 6 ]: ∎∎∎ // 6860 .. 7840 [ 6 ]: ∎∎∎ // 7840 .. 8820 [ 5 ]: ∎∎ // 8820 .. 9800 [ 6 ]: ∎∎∎ // ``` ``` ## Install and Usage To use the `histo` crate in your Rust project, add it to your `Cargo.toml` file: ```toml [dependencies] histo = "0.1.0" ``` The `histo` crate also comes with the command line `histo` tool: ```commands $ cargo install histo $ tail samples.txt 1 2 3 4 5 1 2 3 4 5 $ histo < samples.txt # Number of samples = 150 # Min = 1 # Max = 10 # # Mean = 5.833333333333334 # Standard deviation = 1.9301698255737905 # Variance = 3.7255555555555566 # # Each ∎ is a count of 1 # 1 .. 2 [ 3 ]: ∎∎∎ 2 .. 3 [ 3 ]: ∎∎∎ 3 .. 4 [ 3 ]: ∎∎∎ 4 .. 5 [ 31 ]: ∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 5 .. 6 [ 28 ]: ∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 6 .. 7 [ 29 ]: ∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 7 .. 8 [ 29 ]: ∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 8 .. 9 [ 8 ]: ∎∎∎∎∎∎∎∎ 9 .. 10 [ 8 ]: ∎∎∎∎∎∎∎∎ 10 .. 11 [ 8 ]: ∎∎∎∎∎∎∎∎ ``` histo-1.0.0/benches/bench.rs000075500000000000000000000012021046102023000140020ustar 00000000000000#![feature(test)] extern crate histo; extern crate test; #[bench] fn bench_adding_samples(b: &mut test::Bencher) { b.iter(|| { let mut h = histo::Histogram::with_buckets(10); for i in 0..100 { h.add(i); h.add(i * i); h.add(i * i * i); } test::black_box(h); }); } #[bench] fn bench_formatting(b: &mut test::Bencher) { use std::string::ToString; let mut h = histo::Histogram::with_buckets(10); for i in 0..100 { h.add(i); h.add(i * i); h.add(i * i * i); } b.iter(|| { test::black_box(h.to_string()); }); } histo-1.0.0/ci/script.sh000075500000000000000000000007241046102023000132110ustar 00000000000000#!/usr/bin/env bash set -eux case "$JOB" in "test") cargo build $PROFILE --verbose --features "$FEATURES" cargo test $PROFILE --verbose --features "$FEATURES" ;; "bench") if [[ "$PROFILE" != "--release" ]]; then echo Benching a non-release build?? exit 1 fi cargo bench --verbose --features "$FEATURES" ;; *) echo Unknown job: "$JOB" exit 1 ;; esac histo-1.0.0/src/bin/histo.rs000064400000000000000000000062351046102023000140110ustar 00000000000000//! Reads samples from stdin, one per line, and then prints the resulting //! histogram. extern crate histo; use std::io::{self, BufRead, Write}; use std::process; fn main() { if let Err(e) = try_main() { let mut stderr = io::stderr(); let _ = write!(&mut stderr, "error: {}", e); process::exit(1); } } fn io_error(error: impl Into>) -> io::Error { io::Error::new(io::ErrorKind::Other, error) } const HELP_TEXT: &'static str = "\ Reads data from `stdin` and prints a histogram of the data to `stdout`. The input data format must be one unsigned 64-bit integer per line. USAGE: histo [OPTIONS] [FLAGS] OPTIONS: -n, --buckets BUCKETS Configure the number of buckets in the histogram FLAGS: -h, --help Prints help information -V, --version Prints version information EXAMPLE: $ head data.txt 3 1 50 38 1 38 1 38 39 4 $ histo < data.txt # Number of samples = 154653 # Min = 1 # Max = 58 # # Mean = 4.407945529669717 # Standard deviation = 5.8241339617399985 # Variance = 33.92053640429325 # # Each ∎ is a count of 2484 # 1 .. 7 [ 124222 ]: ∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 7 .. 13 [ 18556 ]: ∎∎∎∎∎∎∎ 13 .. 19 [ 7117 ]: ∎∎ 19 .. 25 [ 2059 ]: 25 .. 31 [ 1245 ]: 31 .. 37 [ 284 ]: 37 .. 43 [ 882 ]: 43 .. 49 [ 122 ]: 49 .. 55 [ 135 ]: 55 .. 61 [ 31 ]: "; fn help_text() { eprintln!("histo {}\n\n{}", env!("CARGO_PKG_VERSION"), HELP_TEXT); } fn fail_with_help_text(msg: impl AsRef) -> ! { eprintln!("{}", msg.as_ref()); eprintln!(); help_text(); process::exit(1) } fn try_main() -> io::Result<()> { let mut buckets = 10; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { match arg.as_str() { "-n" | "--buckets" => { let arg = args.next().unwrap_or_else(|| { fail_with_help_text(format!("missing number of buckets for `{arg}`")) }); buckets = arg.parse().map_err(|e| io_error(e))?; } "-h" | "--help" => { help_text(); process::exit(0); } "-V" | "--version" => { println!("histo {}", env!("CARGO_PKG_VERSION")); process::exit(0); } _ => fail_with_help_text(format!("unknown CLI argument: `{arg}`")), } } let mut hist = histo::Histogram::with_buckets(buckets); let stdin = io::stdin(); let mut stdin = stdin.lock(); let mut line = String::new(); while stdin.read_line(&mut line)? > 0 { { let line = line.trim(); if line.is_empty() { continue; } let sample: u64 = line.trim().parse().map_err(|e| io_error(e))?; hist.add(sample); } line.clear(); } println!("{}", hist); Ok(()) } histo-1.0.0/src/lib.rs000075500000000000000000000262051046102023000126630ustar 00000000000000//! Histograms with a configurable number of buckets, and a terminal-friendly //! `Display`. //! //! This crate provides a `Histogram` type that allows configuration of the //! number of buckets that will be used, regardless of the range of input //! samples. This is useful when displaying a `Histogram` (for example, when //! printing it to a terminal) but it sacrifices fancy tracking of precision and //! significant figures. //! //! It uses O(n) memory. //! //! ``` //! extern crate histo; //! use histo::Histogram; //! //! # fn main() { //! // Create a histogram that will have 10 buckets. //! let mut histogram = Histogram::with_buckets(10); //! //! // Adds some samples to the histogram. //! for sample in 0..100 { //! histogram.add(sample); //! histogram.add(sample * sample); //! } //! //! // Iterate over buckets and do stuff with their range and count. //! for bucket in histogram.buckets() { //! # let do_stuff = |_, _, _| {}; //! do_stuff(bucket.start(), bucket.end(), bucket.count()); //! } //! //! // And you can also `Display` a histogram! //! println!("{}", histogram); //! //! // Prints: //! // //! // ``` //! // # Number of samples = 200 //! // # Min = 0 //! // # Max = 9801 //! // # //! // # Mean = 1666.5000000000005 //! // # Standard deviation = 2641.2281518263426 //! // # Variance = 6976086.1499999985 //! // # //! // # Each ∎ is a count of 2 //! // # //! // 0 .. 980 [ 132 ]: ∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ //! // 980 .. 1960 [ 13 ]: ∎∎∎∎∎∎ //! // 1960 .. 2940 [ 10 ]: ∎∎∎∎∎ //! // 2940 .. 3920 [ 8 ]: ∎∎∎∎ //! // 3920 .. 4900 [ 7 ]: ∎∎∎ //! // 4900 .. 5880 [ 7 ]: ∎∎∎ //! // 5880 .. 6860 [ 6 ]: ∎∎∎ //! // 6860 .. 7840 [ 6 ]: ∎∎∎ //! // 7840 .. 8820 [ 5 ]: ∎∎ //! // 8820 .. 9800 [ 6 ]: ∎∎∎ //! // ``` //! # } //! ``` //! #![deny(missing_docs)] #![deny(missing_debug_implementations)] #![deny(unsafe_code)] #[cfg(all(test, feature = "quickcheck"))] #[macro_use] extern crate quickcheck; extern crate stats; use std::cmp; use std::fmt; use std::collections::BTreeMap; use std::collections::btree_map::Range; /// A histogram is a collection of samples, sorted into buckets. /// /// See the crate level documentation for more details. #[derive(Debug, Clone)] pub struct Histogram { num_buckets: u64, samples: BTreeMap, stats: stats::OnlineStats, minmax: stats::MinMax, } impl Histogram { /// Construct a new histogram with the given number of buckets. /// /// ## Panics /// /// Panics if the number of buckets is zero. pub fn with_buckets(num_buckets: u64) -> Histogram { assert!(num_buckets > 0); Histogram { num_buckets, samples: Default::default(), stats: Default::default(), minmax: Default::default(), } } /// Add a new sample to this histogram. pub fn add(&mut self, sample: u64) { *self.samples.entry(sample).or_insert(0) += 1; self.minmax.add(sample); self.stats.add(sample); } /// Get an iterator over this histogram's buckets. pub fn buckets(&self) -> Buckets { Buckets { histogram: self, index: 0, } } } impl fmt::Display for Histogram { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Write; let num_samples: u64 = self.samples.values().sum(); writeln!(f, "# Number of samples = {}", num_samples)?; if num_samples == 0 { return Ok(()); } let min = self.minmax.min().unwrap(); let max = self.minmax.max().unwrap(); writeln!(f, "# Min = {}", min)?; writeln!(f, "# Max = {}", max)?; writeln!(f, "#")?; let mean = self.stats.mean(); let dev = self.stats.stddev(); let var = self.stats.variance(); writeln!(f, "# Mean = {}", mean)?; writeln!(f, "# Standard deviation = {}", dev)?; writeln!(f, "# Variance = {}", var)?; writeln!(f, "#")?; let max_bucket_count = self.buckets().map(|b| b.count()).fold(0, cmp::max); const WIDTH: u64 = 50; let count_per_char = cmp::max(max_bucket_count / WIDTH, 1); writeln!(f, "# Each ∎ is a count of {}", count_per_char)?; writeln!(f, "#")?; let mut count_str = String::new(); let widest_count = self.buckets().fold(0, |n, b| { count_str.clear(); write!(&mut count_str, "{}", b.count()).unwrap(); cmp::max(n, count_str.len()) }); let mut end_str = String::new(); let widest_range = self.buckets().fold(0, |n, b| { end_str.clear(); write!(&mut end_str, "{}", b.end()).unwrap(); cmp::max(n, end_str.len()) }); let mut start_str = String::with_capacity(widest_range); for bucket in self.buckets() { start_str.clear(); write!(&mut start_str, "{}", bucket.start()).unwrap(); for _ in 0..widest_range - start_str.len() { start_str.insert(0, ' '); } end_str.clear(); write!(&mut end_str, "{}", bucket.end()).unwrap(); for _ in 0..widest_range - end_str.len() { end_str.insert(0, ' '); } count_str.clear(); write!(&mut count_str, "{}", bucket.count()).unwrap(); for _ in 0..widest_count - count_str.len() { count_str.insert(0, ' '); } write!(f, "{} .. {} [ {} ]: ", start_str, end_str, count_str)?; for _ in 0..bucket.count() / count_per_char { write!(f, "∎")?; } writeln!(f)?; } Ok(()) } } /// An iterator over the buckets in a histogram. #[derive(Debug, Clone)] pub struct Buckets<'a> { histogram: &'a Histogram, index: u64, } impl<'a> Iterator for Buckets<'a> { type Item = Bucket<'a>; fn next(&mut self) -> Option { if self.index >= self.histogram.num_buckets { return None; } let (min, max) = match (self.histogram.minmax.min(), self.histogram.minmax.max()) { (Some(&min), Some(&max)) => (min, max), _ => return None, }; let range = max - min; let range = range + (range % self.histogram.num_buckets); let bucket_size = range / self.histogram.num_buckets; let bucket_size = cmp::max(1, bucket_size); let start = min + self.index * bucket_size; let end = min + (self.index + 1) * bucket_size; self.index += 1; Some(Bucket { start, end, range: if self.index == self.histogram.num_buckets { self.histogram.samples.range(start..) } else { self.histogram.samples.range(start..end) }, }) } } /// A bucket is a range of samples and their count. #[derive(Clone)] pub struct Bucket<'a> { start: u64, end: u64, range: Range<'a, u64, u64>, } impl<'a> Bucket<'a> { /// The number of samples in this bucket's range. pub fn count(&self) -> u64 { self.range.clone().map(|(_, count)| count).sum() } /// The start of this bucket's range. pub fn start(&self) -> u64 { self.start } /// The end of this bucket's range. pub fn end(&self) -> u64 { self.end } } impl<'a> fmt::Debug for Bucket<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Bucket {{ {}..{} }}", self.start, self.end) } } #[cfg(test)] mod tests { use super::*; #[test] fn num_buckets() { let mut histo = Histogram::with_buckets(10); for i in 0..100 { histo.add(i); } assert_eq!(histo.buckets().count(), 10); } #[test] fn bucket_count() { let mut histo = Histogram::with_buckets(1); for i in 0..10 { histo.add(i); } assert_eq!(histo.buckets().count(), 1); assert_eq!(histo.buckets().next().unwrap().count(), 10); } #[test] fn bucket_count_one() { let mut histo = Histogram::with_buckets(1); histo.add(1); assert_eq!(histo.buckets().count(), 1); assert_eq!(histo.buckets().next().unwrap().count(), 1); } #[test] fn overflow_panic() { use std::string::ToString; let mut histo = Histogram::with_buckets(1); histo.add(99); histo.to_string(); } } #[cfg(all(test, feature = "quickcheck"))] mod quickchecks { use super::*; use std::cmp; quickcheck! { fn sum_of_bucket_counts_is_total_count(buckets: u64, samples: Vec) -> () { if buckets == 0 { return; } let len = samples.len(); let mut histo = Histogram::with_buckets(buckets); for s in samples { histo.add(s); } assert_eq!(len, histo.stats.len(), "stats.len() should be correct"); assert_eq!(len, histo.minmax.len(), "minmax.len() should be correct"); assert_eq!(len as u64, histo.samples.values().cloned().sum::(), "samples.values() count should be correct"); assert_eq!(len as u64, histo.buckets().map(|b| b.count()).sum::(), "sum of buckets counts should be correct"); } fn actual_buckets_should_be_less_than_or_equal_num_buckets( buckets: u64, samples: Vec ) -> () { if buckets == 0 { return; } let mut histo = Histogram::with_buckets(buckets); for s in samples { histo.add(s); } assert!(histo.buckets().count() as u64 <= buckets, "should never have more than expected number of buckets"); } fn bucket_ranges_should_be_correct(buckets: u64, samples: Vec) -> () { if buckets == 0 { return; } let mut histo = Histogram::with_buckets(buckets); for s in samples { histo.add(s); } histo.buckets() .fold(None, |minmax, bucket| { let bucket_range = bucket.end() - bucket.start(); let (min, max) = minmax.unwrap_or((bucket_range, bucket_range)); let min = cmp::min(min, bucket_range); let max = cmp::max(max, bucket_range); assert!(max - min <= 1); Some((min, max)) }); } fn formatting_should_never_panic(buckets: u64, samples: Vec) -> () { use std::string::ToString; if buckets == 0 { return; } let mut histo = Histogram::with_buckets(buckets); for s in samples { histo.add(s); } histo.to_string(); } } }