1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
//! A native rust implementation of a histogram and percentiles which can offer
//! specified precision across the full range of stored values. This library is
//! inspired by the `HdrHistogram` project.
//!
//! # Goals
//! * maintain precision across full value range
//! * provide percentile metrics for stored data
//! * pre-allocated datastructure
//!
//! # Future work
//! * unknown
//!
//! # Usage
//!
//! Create a new histogram, call increment for every value, retrieve percentile
//! stats.
//!
//! Note that the incremented and decremented values have the
//! precision which is given upon creation of the histogram (by
//! default 3 decimals). This means that increment of x and decrement
//! of y might lead net effect of zero, if x and y are of similar
//! size.
//!
//! # Example
//!
//! Create a histogram, increment values, show percentiles
//!
//! ```
//! use histogram::Histogram;
//!
//! // create a histogram with default config
//! let mut histogram = Histogram::new();
//!
//! let mut value = 0;
//!
//! for i in 1..100 {
//!     histogram.increment(i);
//! }
//!
//! // print percentiles from the histogram
//! println!("Percentiles: p50: {} ns p90: {} ns p99: {} ns p999: {}",
//!     histogram.percentile(50.0).unwrap(),
//!     histogram.percentile(90.0).unwrap(),
//!     histogram.percentile(99.0).unwrap(),
//!     histogram.percentile(99.9).unwrap(),
//! );
//!
//! // print additional statistics
//! println!("Latency (ns): Min: {} Avg: {} Max: {} StdDev: {}",
//!     histogram.minimum().unwrap(),
//!     histogram.mean().unwrap(),
//!     histogram.maximum().unwrap(),
//!     histogram.stddev().unwrap(),
//! );
//! ```

#![cfg_attr(feature = "cargo-clippy", deny(missing_docs))]
#![cfg_attr(feature = "cargo-clippy", deny(warnings))]

use std::fmt;
use std::mem;

/// A configuration struct for building custom `Histogram`s.
#[derive(Clone, Copy)]
pub struct Config {
    precision: u32,
    max_memory: u32,
    max_value: u64,
    radix: u32,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            precision: 3,
            max_memory: 0,
            max_value: 60_000_000_000,
            radix: 10,
        }
    }
}

impl Config {
    /// create a new Histogram Config with defaults
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut c = Histogram::configure();
    /// ```
    pub fn new() -> Config {
        Default::default()
    }

    /// set HistogramConfig precision
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut c = Histogram::configure();
    /// c.precision(4); // set to 4 significant figures
    /// ```
    pub fn precision(mut self, precision: u32) -> Self {
        self.precision = precision;
        self
    }

    /// set HistogramConfig memory limit
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut c = Histogram::configure();
    /// c.max_memory(1024*1024); // cap Histogram at 1MB of data
    /// ```
    pub fn max_memory(mut self, bytes: u32) -> Self {
        self.max_memory = bytes;
        self
    }

    /// set HistogramConfig value limit
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut c = Histogram::configure();
    /// c.max_value(1000); // values above 1000 will not be stored
    /// ```
    pub fn max_value(mut self, max: u64) -> Self {
        self.max_value = max;
        self
    }

    /// Build a new histogram based on the current configuration
    /// values.  Return `None` if the new histogram would require more
    /// than the [configured memory size](#method.max_memory).
    pub fn build(self) -> Option<Histogram> {
        Histogram::configured(self)
    }
}

#[derive(Clone, Copy)]
struct Counters {
    entries_total: u64,
    missed_unknown: u64,
    missed_large: u64,
}

impl Default for Counters {
    fn default() -> Counters {
        Counters {
            entries_total: 0,
            missed_unknown: 0,
            missed_large: 0,
        }
    }
}

impl Counters {
    fn new() -> Counters {
        Default::default()
    }

    fn clear(&mut self) -> &mut Self {
        self.entries_total = 0;
        self.missed_unknown = 0;
        self.missed_large = 0;
        self
    }
}

#[derive(Clone)]
struct Data {
    data: Vec<u64>,
    counters: Counters,
}

#[derive(Clone, Copy)]
struct Properties {
    buckets_inner: u32,
    linear_max: u64,
    linear_power: u32,
}

/// the main datastructure
#[derive(Clone)]
pub struct Histogram {
    config: Config,
    data: Data,
    properties: Properties,
}

/// value-quantized section of `Histogram`
#[derive(Clone, Copy, Debug)]
pub struct Bucket {
    id: u64,
    count: u64,
    value: u64,
    width: u64,
}

impl Bucket {
    /// return the sample value for the bucket
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    /// let b = h.into_iter().next().unwrap();
    /// assert_eq!(b.value(), 0);
    /// ```
    pub fn value(self) -> u64 {
        self.value
    }

    /// return the sample counts for the bucket
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let h = Histogram::new();
    /// let b = h.into_iter().next().unwrap();
    /// assert_eq!(b.count(), 0);
    /// ```
    pub fn count(self) -> u64 {
        self.count
    }

    /// return the bucket id
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let h = Histogram::new();
    /// let b = h.into_iter().next().unwrap();
    /// assert_eq!(b.id(), 0);
    /// ```
    pub fn id(self) -> u64 {
        self.id
    }

    /// return the width of the bucket
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let h = Histogram::new();
    /// let b = h.into_iter().next().unwrap();
    /// assert_eq!(b.width(), 1);
    /// ```
    pub fn width(self) -> u64 {
        self.width
    }
}

/// Iterator over a Histogram's buckets.
pub struct Iter<'a> {
    hist: &'a Histogram,
    index: usize,
}

impl<'a> Iter<'a> {
    fn new(hist: &'a Histogram) -> Iter<'a> {
        Iter { hist, index: 0 }
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = Bucket;

    fn next(&mut self) -> Option<Bucket> {
        let limit = self.hist.get_index(self.hist.config.max_value).unwrap();
        if self.index > limit {
            None
        } else {
            let current = self.index;

            // clamp the value at max value
            let mut value = self.hist.index_value(current);
            if value > self.hist.config.max_value {
                value = self.hist.config.max_value;
                self.index = limit + 1;
            }

            // measure width of current bucket
            let width = if current == 0 {
                1
            } else {
                value - self.hist.index_value(current - 1)
            };
            self.index += 1;
            Some(Bucket {
                id: current as u64,
                count: self.hist.data.data[current],
                value,
                width,
            })
        }
    }
}

impl<'a> IntoIterator for &'a Histogram {
    type Item = Bucket;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self)
    }
}

impl fmt::Debug for Histogram {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({} total)", self.data.counters.entries_total)
    }
}

impl Default for Histogram {
    fn default() -> Histogram {
        Config::new().build().unwrap()
    }
}

impl Histogram {
    /// create a new Histogram
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    /// ```
    pub fn new() -> Histogram {
        Default::default()
    }

    /// configure a Histogram
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::configure()
    ///     .max_value(10_000)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn configure() -> Config {
        Config::default()
    }

    fn configured(config: Config) -> Option<Histogram> {
        let buckets_inner: u32 = config.radix.pow(config.precision);
        let linear_power: u32 = 32 - buckets_inner.leading_zeros();
        let linear_max: u64 = 2.0_f64.powi(linear_power as i32) as u64;
        let max_value_power: u32 = 64 - config.max_value.leading_zeros();

        let buckets_outer = if max_value_power > linear_power {
            max_value_power - linear_power
        } else {
            0
        };

        let buckets_total = buckets_inner * buckets_outer + linear_max as u32;
        let memory_used = buckets_total * mem::size_of::<u64>() as u32;

        if config.max_memory > 0 && config.max_memory < memory_used {
            return None;
        }

        let data = vec![0; buckets_total as usize];

        let counters = Counters::new();

        Some(Histogram {
            config,
            data: Data { data, counters },
            properties: Properties {
                buckets_inner,
                linear_max,
                linear_power,
            },
        })
    }

    /// clear the histogram data
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    ///
    /// h.increment(1);
    /// assert_eq!(h.entries(), 1);
    /// h.clear();
    /// assert_eq!(h.entries(), 0);
    /// ```
    pub fn clear(&mut self) {
        // clear everything manually, weird results in practice?
        self.data.counters.clear();
        for x in &mut self.data.data {
            *x = 0;
        }
    }

    /// increment the count for a value
    ///
    /// # Example
    /// ```
    /// use histogram::Histogram;
    ///
    /// let mut h = Histogram::new();
    ///
    /// h.increment(1);
    /// assert_eq!(h.get(1).unwrap(), 1);
    /// ```
    pub fn increment(&mut self, value: u64) -> Result<(), &'static str> {
        self.increment_by(value, 1_u64)
    }

    /// record additional counts for value
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    ///
    /// h.increment_by(1, 1);
    /// assert_eq!(h.get(1).unwrap(), 1);
    ///
    /// h.increment_by(2, 2);
    /// assert_eq!(h.get(2).unwrap(), 2);
    ///
    /// h.increment_by(10, 10);
    /// assert_eq!(h.get(10).unwrap(), 10);
    /// ```
    pub fn increment_by(&mut self, value: u64, count: u64) -> Result<(), &'static str> {
        self.data.counters.entries_total = self.data.counters.entries_total.saturating_add(count);
        if value > self.config.max_value {
            self.data.counters.missed_large = self.data.counters.missed_large.saturating_add(count);
            Err("sample value too large")
        } else {
            match self.get_index(value) {
                Some(index) => {
                    self.data.data[index] = self.data.data[index].saturating_add(count);
                    Ok(())
                }
                None => {
                    self.data.counters.missed_unknown =
                        self.data.counters.missed_unknown.saturating_add(count);
                    Err("sample unknown error")
                }
            }
        }
    }

    /// decrement the count for a value. This functionality is best
    /// used to remove previously inserted from the histogram.
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    ///
    /// h.increment(1).unwrap();
    /// assert_eq!(h.get(1).unwrap(), 1);
    /// h.decrement(1).unwrap();
    /// assert_eq!(h.get(1).unwrap(), 0);
    /// ```
    pub fn decrement(&mut self, value: u64) -> Result<(), &'static str> {
        self.decrement_by(value, 1_u64)
    }

    /// remove count for value from histogram. This functionality is
    /// best used to remove previously inserted from the
    /// histogram.
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    ///
    /// h.increment_by(1, 1).unwrap();
    /// h.increment_by(2, 2).unwrap();
    /// h.decrement_by(1, 1).unwrap();
    ///
    /// assert_eq!(h.get(2).unwrap(), 2);
    /// assert_eq!(h.get(1).unwrap(), 0);
    /// ```
    pub fn decrement_by(&mut self, value: u64, count: u64) -> Result<(), &'static str> {
        if value > self.config.max_value {
            if let Some(new_missed_large) = self.data.counters.missed_large.checked_sub(count) {
                self.data.counters.missed_large = new_missed_large;
                self.data.counters.entries_total =
                    self.data.counters.entries_total.saturating_sub(count);
                Err("sample value too large")
            } else {
                Err("large sample value underflow")
            }
        } else {
            match self.get_index(value) {
                Some(index) => {
                    if let Some(new_index_value) = self.data.data[index].checked_sub(count) {
                        self.data.data[index] = new_index_value;
                        self.data.counters.entries_total =
                            self.data.counters.entries_total.saturating_sub(count);
                        Ok(())
                    } else {
                        Err("underflow")
                    }
                }
                None => {
                    self.data.counters.missed_unknown =
                        self.data.counters.missed_unknown.saturating_add(count);
                    Err("sample unknown error")
                }
            }
        }
    }

    /// get the count for a value
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    /// assert_eq!(h.get(1).unwrap(), 0);
    /// ```
    pub fn get(&self, value: u64) -> Option<u64> {
        match self.get_index(value) {
            Some(index) => Some(self.data.data[index]),
            None => None,
        }
    }

    // calculate the index for a given value
    fn get_index(&self, value: u64) -> Option<usize> {
        if value <= (self.properties.linear_max + 2_u64.pow(self.config.precision)) {
            return Some(value as usize);
        }

        let l_max = self.properties.linear_max as u32;

        let outer = 63 - value.leading_zeros();

        let l_power = 63 - self.properties.linear_max.leading_zeros();

        let remain = value as f64 - 2.0_f64.powi(outer as i32);

        let inner = (f64::from(self.properties.buckets_inner) * remain as f64 /
                         2.0_f64.powi((outer) as i32))
            .floor() as u32;

        // this gives the shifted outer index
        let outer = outer as u32 - l_power;

        let index = l_max + self.properties.buckets_inner * outer + inner + 1;

        Some(index as usize)

    }

    // calculate the nominal value of the given index
    fn index_value(&self, index: usize) -> u64 {
        // in this case, the index is linear
        let index = index as u32;

        let linear_max = self.properties.linear_max as u32;

        if index <= linear_max {
            return u64::from(index);
        }

        let log_index = index - linear_max;

        let outer = (f64::from(log_index) / f64::from(self.properties.buckets_inner)).floor() as
            u32;

        let inner = log_index - outer * self.properties.buckets_inner as u32;

        let mut value = 2.0_f64.powi((outer as u32 + self.properties.linear_power) as i32);
        value += f64::from(inner) * (value as f64 / f64::from(self.properties.buckets_inner));

        if value > self.config.max_value as f64 {
            return self.config.max_value as u64;
        }
        value.ceil() as u64
    }

    /// return the value for the given percentile
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    /// for value in 1..1000 {
    ///     h.increment(value).unwrap();
    /// }
    ///
    /// assert_eq!(h.percentile(50.0).unwrap(), 501);
    /// assert_eq!(h.percentile(90.0).unwrap(), 901);
    /// assert_eq!(h.percentile(99.0).unwrap(), 991);
    /// assert_eq!(h.percentile(99.9).unwrap(), 999);
    /// ```
    pub fn percentile(&self, percentile: f64) -> Result<u64, &'static str> {
        if self.entries() < 1 {
            return Err("no data");
        }

        if percentile <= 100.0 && percentile >= 0.0 {

            let total = self.entries();

            let mut need = (total as f64 * (percentile / 100.0_f64)).ceil() as u64;

            if need > total {
                need = total;
            }

            need = total - need;

            let mut index: isize = (self.buckets_total() - 1) as isize;
            let mut step: isize = -1 as isize;

            let mut have = if percentile < 50.0 {
                index = 0 as isize;
                step = 1 as isize;
                need = total - need;
                0
            } else {
                self.data.counters.missed_large
            };

            if need == 0 {
                need = 1;
            }

            if have >= need {
                if index == 0 {
                    return Err("underflow");
                }
                return Err("overflow");
            }
            loop {
                have += self.data.data[index as usize];

                if have >= need {
                    return Ok(self.index_value(index as usize) as u64);
                }

                index += step;

                if index >= self.buckets_total() as isize {
                    break;
                }
                if index < 0 {
                    break;
                }
            }
        }
        Err("unknown failure")
    }

    /// convenience function for min
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    /// for value in 1..1000 {
    ///     h.increment(value);
    /// }
    /// assert_eq!(h.minimum().unwrap(), 1);
    /// ```
    pub fn minimum(&self) -> Result<u64, &'static str> {
        self.percentile(0.0_f64)
    }

    /// convenience function for max
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    /// for value in 1..1000 {
    ///     h.increment(value);
    /// }
    /// assert_eq!(h.maximum().unwrap(), 999);
    /// ```
    pub fn maximum(&self) -> Result<u64, &'static str> {
        self.percentile(100.0_f64)
    }

    /// arithmetic mean approximation across the histogram
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    /// for value in 1..1000 {
    ///     h.increment(value);
    /// }
    /// assert_eq!(h.mean().unwrap(), 500);
    /// ```
    pub fn mean(&self) -> Result<u64, &'static str> {

        if self.entries() < 1 {
            return Err("no data");
        }

        let total = self.entries();

        let mut mean = 0.0_f64;

        for index in 0..(self.buckets_total() as usize) {
            mean += (self.index_value(index) as f64 * self.data.data[index] as f64) as f64 /
                total as f64;
        }
        Ok(mean.ceil() as u64)
    }

    /// standard variance approximation across the histogram
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    /// for value in 1..11 {
    ///     h.increment(value);
    /// }
    /// assert_eq!(h.stdvar().unwrap(), 9);
    /// ```
    pub fn stdvar(&self) -> Result<u64, &'static str> {

        if self.entries() < 1 {
            return Err("no data");
        }

        let total = self.entries() as f64;

        let m = self.mean().unwrap() as f64;

        let mut stdvar = 0.0_f64;

        for index in 0..(self.buckets_total() as usize) {
            let v = self.index_value(index) as f64;
            let c = self.data.data[index] as f64;
            stdvar += (c * v * v) - (2_f64 * c * m * v) + (c * m * m);
        }

        stdvar /= total;

        Ok(stdvar.ceil() as u64)
    }

    /// standard deviation approximation across the histogram
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    ///
    /// for value in 1..11 {
    ///     h.increment(value);
    /// }
    ///
    /// assert_eq!(h.stddev().unwrap(), 3);
    ///
    /// h.clear();
    ///
    /// for value in 1..4 {
    ///     h.increment(value);
    /// }
    /// for _ in 0..26 {
    ///     h.increment(1);
    /// }
    ///
    /// assert_eq!(h.stddev().unwrap(), 1);
    /// ```
    pub fn stddev(&self) -> Option<u64> {

        if self.entries() < 1 {
            return None;
        }

        let stdvar = self.stdvar().unwrap() as f64;

        let stddev = stdvar.sqrt();

        Some(stddev.ceil() as u64)
    }

    /// merge one Histogram into another Histogram
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut a = Histogram::new();
    /// let mut b = Histogram::new();
    ///
    /// assert_eq!(a.entries(), 0);
    /// assert_eq!(b.entries(), 0);
    ///
    /// a.increment(1);
    /// b.increment(2);
    ///
    /// assert_eq!(a.entries(), 1);
    /// assert_eq!(b.entries(), 1);
    ///
    /// a.merge(&mut b);
    ///
    /// assert_eq!(a.entries(), 2);
    /// assert_eq!(a.get(1).unwrap(), 1);
    /// assert_eq!(a.get(2).unwrap(), 1);
    /// ```
    pub fn merge(&mut self, other: &Histogram) {
        for bucket in other {
            let _ = self.increment_by(bucket.value, bucket.count);
        }
    }

    /// return the number of entries in the Histogram
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    ///
    /// assert_eq!(h.entries(), 0);
    /// h.increment(1);
    /// assert_eq!(h.entries(), 1);
    /// ```
    pub fn entries(&self) -> u64 {
        self.data.counters.entries_total
    }

    /// return the number of buckets in the Histogram
    ///
    /// # Example
    /// ```
    /// # use histogram::Histogram;
    /// let mut h = Histogram::new();
    ///
    /// assert!(h.buckets_total() > 1);
    /// ```
    pub fn buckets_total(&self) -> u64 {
        (self.get_index(self.config.max_value).unwrap() + 1) as u64
    }
}

#[cfg(test)]
mod tests {
    use super::Histogram;

    #[test]
    fn test_too_large() {
        let h = Histogram::configure()
            .max_value(10_000)
            .precision(3)
            .max_memory(8192)
            .build();

        if let Some(_) = h {
            panic!("Created histogram which used too much memory");
        }
    }


    #[test]
    fn test_increment_0() {
        let mut h = Histogram::new();

        for op in 1..1000000 {
            h.increment(1).unwrap();
            assert_eq!(h.entries(), op);
        }
    }

    #[test]
    fn test_increment_1() {
        let mut h = Histogram::configure()
            .max_value(10)
            .precision(3)
            .build()
            .unwrap();

        // increment values across the entire range
        // including 0 and max_value
        for v in 0..11 {
            h.increment(v).unwrap();
            assert_eq!(h.entries(), v + 1);
        }
    }

    #[test]
    fn test_decrement_0() {
        let mut h = Histogram::new();
        let m = 1000000;

        for _ in 0..m {
            h.increment(2).unwrap();
        }

        for op in 1..m {
            h.decrement(2).unwrap();
            assert_eq!(h.entries(), m - op);
        }
    }

    #[test]
    fn test_decrement_1() {
        let mut h = Histogram::configure()
            .max_value(20_000)
            .precision(3)
            .build()
            .unwrap();

        let v = h.properties.linear_max + 2;
        let m = 1_000_000;

        for _ in 0..m {
            h.increment(v).unwrap();
        }

        for op in 1..m {
            h.decrement(v).unwrap();
            assert_eq!(h.entries(), m - op);
        }
    }

    #[test]
    #[should_panic(expected = "large sample value underflow")]
    fn test_decrement_4() {
        let mut h = Histogram::new();
        let v = h.config.max_value + 1;
        h.decrement(v).unwrap();
    }

    #[test]
    #[should_panic(expected = "sample value too large")]
    fn test_decrement_5() {
        let mut h = Histogram::new();
        let v = h.config.max_value + 1;
        let _ = h.increment(v);
        h.decrement(v).unwrap();
    }

    #[test]
    fn test_decrement_example_0() {
        let mut h = Histogram::new();

        h.increment(1).unwrap();
        assert_eq!(h.get(1).unwrap(), 1);
        h.decrement(1).unwrap();
        assert_eq!(h.get(1).unwrap(), 0);
    }

    #[test]
    fn test_decrement_by_example_0() {
        let mut h = Histogram::new();

        h.increment_by(1, 1).unwrap();
        h.increment_by(2, 2).unwrap();
        h.decrement_by(1, 1).unwrap();

        assert_eq!(h.get(2).unwrap(), 2);
        assert_eq!(h.get(1).unwrap(), 0);
    }

    #[test]
    fn test_get() {
        let mut h = Histogram::new();

        h.increment(1).unwrap();
        assert_eq!(h.get(1), Some(1));

        h.increment(1).unwrap();
        assert_eq!(h.get(1), Some(2));

        h.increment(2).unwrap();
        assert_eq!(h.get(2), Some(1));

        assert_eq!(h.get(3), Some(0));
    }

    #[test]
    fn test_get_index_0() {
        let h = Histogram::configure()
            .max_value(32)
            .precision(3)
            .build()
            .unwrap();

        // all values should index directly to value
        // no estimated buckets are needed given the precision and max
        for i in 0..32 {
            assert_eq!(h.get_index(i), Some(i as usize));
            assert_eq!(h.index_value(i as usize), i);
        }
    }

    #[test]
    fn test_index_value_0() {
        let h = Histogram::configure()
            .max_value(100)
            .precision(1)
            .build()
            .unwrap();

        assert_eq!(h.index_value(1), 1);
        assert_eq!(h.index_value(2), 2);
        assert_eq!(h.index_value(15), 15);

        assert_eq!(h.index_value(16), 16);
        assert_eq!(h.index_value(26), 32);
        assert_eq!(h.index_value(36), 64);
    }

    #[test]
    fn test_index_value_1() {
        let h = Histogram::configure()
            .max_value(1_000)
            .precision(2)
            .build()
            .unwrap();

        assert_eq!(h.index_value(0), 0);
        assert_eq!(h.index_value(1), 1);
        assert_eq!(h.index_value(126), 126);

        assert_eq!(h.index_value(128), 128);
        assert_eq!(h.index_value(228), 256);
        assert_eq!(h.index_value(328), 512);
    }

    #[test]
    fn test_index_value_2() {
        let h = Histogram::configure()
            .max_value(10_000)
            .precision(3)
            .build()
            .unwrap();

        assert_eq!(h.index_value(0), 0);
        assert_eq!(h.index_value(1), 1);
        assert_eq!(h.index_value(1023), 1023);

        assert_eq!(h.index_value(1024), 1024);
        assert_eq!(h.index_value(2024), 2048);
    }

    #[test]
    fn test_iterator() {
        let h = Histogram::configure()
            .max_value(100)
            .precision(1)
            .build()
            .unwrap();

        let mut buckets_seen = 0;
        for bucket in &h {
            println!("Bucket: {:?}", bucket);
            assert_eq!(bucket.id(), buckets_seen);
            assert_eq!(bucket.value(), h.index_value(bucket.id() as usize));
            assert_eq!(bucket.count(), 0);
            buckets_seen += 1;
        }
        assert_eq!(h.buckets_total(), buckets_seen);
    }

    #[test]
    fn test_percentile() {
        let mut h = Histogram::configure()
            .max_value(1_000)
            .precision(4)
            .build()
            .unwrap();

        for i in 100..200 {
            h.increment(i).ok().expect("error");
        }

        assert_eq!(h.percentile(0.0).unwrap(), 100);
        assert_eq!(h.percentile(10.0).unwrap(), 109);
        assert_eq!(h.percentile(25.0).unwrap(), 124);
        assert_eq!(h.percentile(50.0).unwrap(), 150);
        assert_eq!(h.percentile(75.0).unwrap(), 175);
        assert_eq!(h.percentile(90.0).unwrap(), 190);
        assert_eq!(h.percentile(95.0).unwrap(), 195);
        assert_eq!(h.percentile(100.0).unwrap(), 199);
    }

    #[test]
    fn test_percentile_bad() {
        let mut h = Histogram::configure()
            .max_value(1_000)
            .precision(4)
            .build()
            .unwrap();

        let _ = h.increment(5_000);

        assert!(h.percentile(0.0).is_err());
        assert!(h.percentile(50.0).is_err());
        assert!(h.percentile(100.0).is_err());

        let _ = h.increment(1);

        assert!(h.percentile(0.0).is_ok());

        let _ = h.increment(500);
        let _ = h.increment(500);

        assert!(h.percentile(50.0).is_ok());
    }

    #[test]
    fn test_width_1() {
        let mut h = Histogram::configure()
            .max_value(100)
            .precision(3)
            .build()
            .unwrap();

        for v in 0..101 {
            let _ = h.increment(v);
        }

        assert_eq!(h.data.counters.missed_large, 0);

        let mut prev_id = 0;
        for b in &h {
            println!("Bucket: {:?}", b);
            if b.id() >= 1 {
                assert!(b.id() - 1 == prev_id);
                prev_id = b.id();
            }
            assert!(b.width() != 0, "width should not be 0");
            assert_eq!(b.width(), b.count());
        }
    }

    #[test]
    fn test_width_2() {
        let mut h = Histogram::configure()
            .max_value(1000)
            .precision(2)
            .build()
            .unwrap();

        for v in 0..1001 {
            let _ = h.increment(v);
        }

        assert_eq!(h.data.counters.missed_large, 0);

        let mut prev_id = 0;
        let mut prev_value = 0;
        for b in &h {
            println!("Bucket: {:?}", b);
            if b.id() >= 1 {
                assert_eq!(b.width(), b.value() - prev_value);
                assert!(b.id() - 1 == prev_id);
                prev_id = b.id();
                prev_value = b.value();
            }
            assert!(b.width() != 0, "width should not be 0");

        }
    }
    #[test]
    fn test_width_3() {
        let mut h = Histogram::configure()
            .max_value(10_000)
            .precision(3)
            .build()
            .unwrap();

        for v in 0..10_000 {
            let _ = h.increment(v + 1);
        }

        assert_eq!(h.data.counters.missed_large, 0);

        let mut prev_id = 0;
        let mut prev_value = 0;
        for b in &h {
            println!("Bucket: {:?}", b);
            if b.id() >= 1 {
                assert_eq!(b.width(), b.value() - prev_value);
                assert!(b.id() - 1 == prev_id);
                prev_id = b.id();
                prev_value = b.value();
            }
            assert!(b.width() != 0, "width should not be 0");
        }
    }
}