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
extern crate libc;
pub mod opus {
mod imported_decode;
mod imported_encode;
mod encode;
mod decode;
pub use self::encode::Writer;
pub use self::decode::Reader;
}
#[derive(Clone, Copy)]
pub struct Segment {
pub low: u32,
pub next: u32,
}
pub struct IndexedSegment {
pub segment: Segment,
pub index: usize,
}
pub struct CumulativeDistributionFrequency {
segments: Box<[Segment]>,
width: u32,
}
impl CumulativeDistributionFrequency {
pub fn new(probabilities: Vec<u32>) -> Result<Self, ()> {
if probabilities.len() == 0 {
return Err(())
}
let mut segments = Vec::with_capacity(probabilities.len());
let mut start = 0;
for probability in probabilities {
let next = start + probability;
segments.push(Segment {
low: start,
next,
});
start = next;
}
Ok(Self {
segments: segments
.into_boxed_slice(),
width: start,
})
}
pub fn width(&self) -> u32 {
self.width
}
pub fn find(&self, probability: u32) -> Option<IndexedSegment> {
if probability >= self.width {
return None
}
let index = self.segments.binary_search_by(|segment| {
use std::cmp::Ordering;
if segment.low > probability {
return Ordering::Greater
}
if segment.next <= probability {
return Ordering::Less
}
Ordering::Equal
}).ok()?;
Some(IndexedSegment {
index,
segment: self.segments[index]
})
}
pub fn at_index(&self, index: usize) -> Option<Segment> {
self.segments.get(index)
.map(|indexed| indexed.clone())
}
}