1use std::collections::HashMap;
2use std::ops::Range;
3
4use super::{Error, nonnegative, positive, valid_extent};
5
6#[derive(Debug)]
9pub struct Heights {
10 mode: HeightMode,
11}
12
13#[derive(Debug)]
14enum HeightMode {
15 Fixed {
16 len: usize,
17 height: f64,
18 },
19 Variable {
20 values: Vec<f64>,
21 tree: Vec<f64>,
22 },
23 Sparse {
24 len: usize,
25 estimate: f64,
26 values: HashMap<usize, f64>,
27 tree: HashMap<usize, Deviation>,
28 },
29}
30#[derive(Clone, Copy, Debug, Default)]
31struct Deviation {
32 sum: f64,
33 count: usize,
34}
35
36impl Heights {
37 pub fn fixed(len: usize, height: f64) -> Result<Self, Error> {
38 if !positive(height) || !valid_extent(len as f64 * height) {
39 return Err(Error::InvalidSize);
40 }
41 Ok(Self {
42 mode: HeightMode::Fixed { len, height },
43 })
44 }
45
46 pub fn variable(len: usize, estimate: f64) -> Result<Self, Error> {
47 if !positive(estimate) || !valid_extent(len as f64 * estimate) {
48 return Err(Error::InvalidSize);
49 }
50 let mut values = Vec::new();
51 let mut tree = Vec::new();
52 values
53 .try_reserve_exact(len)
54 .map_err(|_| Error::Allocation)?;
55 tree.try_reserve_exact(len).map_err(|_| Error::Allocation)?;
56 values.resize(len, estimate);
57 tree.extend((1..=len).map(|i| (i & i.wrapping_neg()) as f64 * estimate));
59 Ok(Self {
60 mode: HeightMode::Variable { values, tree },
61 })
62 }
63
64 pub fn sparse(len: usize, estimate: f64) -> Result<Self, Error> {
68 if !positive(estimate) || !valid_extent(len as f64 * estimate) {
69 return Err(Error::InvalidSize);
70 }
71 Ok(Self {
72 mode: HeightMode::Sparse {
73 len,
74 estimate,
75 values: HashMap::new(),
76 tree: HashMap::new(),
77 },
78 })
79 }
80
81 pub fn len(&self) -> usize {
82 match &self.mode {
83 HeightMode::Fixed { len, .. } => *len,
84 HeightMode::Variable { values, .. } => values.len(),
85 HeightMode::Sparse { len, .. } => *len,
86 }
87 }
88 pub fn is_empty(&self) -> bool {
89 self.len() == 0
90 }
91 pub fn storage_len(&self) -> usize {
92 match &self.mode {
93 HeightMode::Fixed { .. } => 0,
94 HeightMode::Variable { values, tree } => values.len() + tree.len(),
95 HeightMode::Sparse { values, tree, .. } => values.len() + tree.len(),
96 }
97 }
98 pub fn storage_capacity(&self) -> usize {
101 match &self.mode {
102 HeightMode::Fixed { .. } => 0,
103 HeightMode::Variable { values, tree } => values.capacity() + tree.capacity(),
104 HeightMode::Sparse { values, tree, .. } => values.capacity() + tree.capacity(),
105 }
106 }
107
108 pub fn height(&self, index: usize) -> Option<f64> {
109 match &self.mode {
110 HeightMode::Fixed { len, height } => (index < *len).then_some(*height),
111 HeightMode::Variable { values, .. } => values.get(index).copied(),
112 HeightMode::Sparse {
113 len,
114 estimate,
115 values,
116 ..
117 } => (index < *len).then(|| values.get(&index).copied().unwrap_or(*estimate)),
118 }
119 }
120
121 pub fn prefix(&self, count: usize) -> Result<f64, Error> {
123 if count > self.len() {
124 return Err(Error::OutOfBounds);
125 }
126 Ok(self.prefix_unchecked(count))
127 }
128
129 fn prefix_unchecked(&self, mut count: usize) -> f64 {
130 match &self.mode {
131 HeightMode::Fixed { height, .. } => count as f64 * height,
132 HeightMode::Variable { tree, .. } => {
133 let mut sum = 0.0;
134 while count > 0 {
135 sum += tree[count - 1];
136 count &= count - 1;
137 }
138 sum
139 }
140 HeightMode::Sparse { estimate, tree, .. } => {
141 let mut sum = count as f64 * estimate;
142 while count > 0 {
143 sum += tree.get(&count).map_or(0.0, |node| node.sum);
144 count &= count - 1;
145 }
146 sum
147 }
148 }
149 }
150
151 pub fn total(&self) -> f64 {
152 self.prefix_unchecked(self.len())
153 }
154
155 fn complete_before(&self, offset: f64) -> usize {
157 match &self.mode {
158 HeightMode::Fixed { len, height } => ((offset / height).floor() as usize).min(*len),
159 HeightMode::Variable { tree, .. } => {
160 let mut count = 0;
161 let mut sum = 0.0;
162 let mut bit = if tree.is_empty() {
163 0
164 } else {
165 1usize << tree.len().ilog2()
166 };
167 while bit != 0 {
168 let next = count + bit;
169 if next <= tree.len() && sum + tree[next - 1] <= offset {
170 count = next;
171 sum += tree[next - 1];
172 }
173 bit >>= 1;
174 }
175 count
176 }
177 HeightMode::Sparse {
178 len,
179 estimate,
180 tree,
181 ..
182 } => {
183 let mut count = 0_usize;
184 let mut sum = 0.0;
185 let mut bit = if *len == 0 { 0 } else { 1usize << len.ilog2() };
186 while bit != 0 {
187 if let Some(next) = count.checked_add(bit).filter(|next| *next <= *len) {
188 let block = (next & next.wrapping_neg()) as f64 * estimate
189 + tree.get(&next).map_or(0.0, |node| node.sum);
190 if sum + block <= offset {
191 count = next;
192 sum += block;
193 }
194 }
195 bit >>= 1;
196 }
197 count
198 }
199 }
200 }
201
202 pub fn measure(&mut self, index: usize, height: f64) -> Result<bool, Error> {
205 if !positive(height) {
206 return Err(Error::InvalidSize);
207 }
208 let total = self.total();
209 match &mut self.mode {
210 HeightMode::Fixed { .. } => Err(Error::InvalidSize),
211 HeightMode::Variable { values, tree } => {
212 let value = values.get_mut(index).ok_or(Error::OutOfBounds)?;
213 let delta = height - *value;
214 if delta == 0.0 {
215 return Ok(false);
216 }
217 if !valid_extent(total + delta) {
218 return Err(Error::InvalidSize);
219 }
220 *value = height;
221 let mut i = index + 1;
222 while i <= tree.len() {
223 tree[i - 1] += delta;
224 let Some(next) = i.checked_add(i & i.wrapping_neg()) else {
225 break;
226 };
227 i = next;
228 }
229 Ok(true)
230 }
231 HeightMode::Sparse {
232 len,
233 estimate,
234 values,
235 tree,
236 } => {
237 if index >= *len {
238 return Err(Error::OutOfBounds);
239 }
240 let delta = height - values.get(&index).copied().unwrap_or(*estimate);
241 if delta == 0.0 {
242 return Ok(false);
243 }
244 if !valid_extent(total + delta) {
245 return Err(Error::InvalidSize);
246 }
247 let had = usize::from(values.contains_key(&index));
248 let has = usize::from(height != *estimate);
249 if has == 0 {
250 values.remove(&index);
251 } else {
252 values.insert(index, height);
253 }
254 let mut i = index + 1;
255 while i <= *len {
256 let previous = tree.get(&i).copied().unwrap_or_default();
257 let count = previous.count + has - had;
258 if count == 0 {
259 tree.remove(&i);
260 } else {
261 tree.insert(
262 i,
263 Deviation {
264 sum: previous.sum + delta,
265 count,
266 },
267 );
268 }
269 let Some(next) = i.checked_add(i & i.wrapping_neg()) else {
270 break;
271 };
272 i = next;
273 }
274 Ok(true)
275 }
276 }
277 }
278
279 pub fn splice(
282 &mut self,
283 range: Range<usize>,
284 inserted: usize,
285 estimate: f64,
286 ) -> Result<(), Error> {
287 if range.start > range.end || range.end > self.len() {
288 return Err(Error::InvalidRange);
289 }
290 if !positive(estimate) {
291 return Err(Error::InvalidSize);
292 }
293 let len = self
294 .len()
295 .checked_sub(range.len())
296 .and_then(|len| len.checked_add(inserted))
297 .ok_or(Error::InvalidSize)?;
298 match &mut self.mode {
299 HeightMode::Fixed {
300 len: current,
301 height,
302 } => {
303 if !valid_extent(len as f64 * *height) {
304 return Err(Error::InvalidSize);
305 }
306 *current = len;
307 }
308 HeightMode::Variable { values, tree } => {
309 let total = values[..range.start]
310 .iter()
311 .chain(&values[range.end..])
312 .sum::<f64>()
313 + inserted as f64 * estimate;
314 if !valid_extent(total) {
315 return Err(Error::InvalidSize);
316 }
317 values
318 .try_reserve(len.saturating_sub(values.len()))
319 .map_err(|_| Error::Allocation)?;
320 tree.try_reserve(len.saturating_sub(tree.len()))
321 .map_err(|_| Error::Allocation)?;
322 values.splice(range, std::iter::repeat_n(estimate, inserted));
323 tree.clear();
324 tree.extend_from_slice(values);
325 for i in 1..=len {
326 if let Some(parent) = i
327 .checked_add(i & i.wrapping_neg())
328 .filter(|parent| *parent <= len)
329 {
330 tree[parent - 1] += tree[i - 1];
331 }
332 }
333 }
334 HeightMode::Sparse {
335 estimate: base,
336 values,
337 ..
338 } => {
339 if inserted > 0 && estimate != *base {
343 return Err(Error::InvalidSize);
344 }
345 let mut next = Self::sparse(len, *base)?;
346 for (&index, &height) in values.iter() {
347 if index < range.start {
348 next.measure(index, height)?;
349 } else if index >= range.end {
350 next.measure(index - (range.end - range.start) + inserted, height)?;
351 }
352 }
353 *self = next;
354 }
355 }
356 Ok(())
357 }
358}
359
360#[derive(Clone, Copy, Debug, PartialEq)]
361pub struct Anchor {
362 pub index: usize,
363 pub within: f64,
364}
365
366#[derive(Clone, Debug, Default, PartialEq)]
367pub struct Window {
368 pub visible: Range<usize>,
369 pub render: Range<usize>,
370 pub offset: f64,
371 pub total: f64,
372 pub top: f64,
373 pub bottom: f64,
374}
375
376#[derive(Debug)]
377pub struct Layout {
378 heights: Heights,
379 overscan: usize,
380}
381
382impl Layout {
383 pub fn new(heights: Heights, overscan: usize) -> Self {
384 Self { heights, overscan }
385 }
386 pub fn heights(&self) -> &Heights {
387 &self.heights
388 }
389 pub fn heights_mut(&mut self) -> &mut Heights {
390 &mut self.heights
391 }
392
393 pub fn window(&self, offset: f64, viewport: f64) -> Result<Window, Error> {
394 if !nonnegative(offset) || !nonnegative(viewport) {
395 return Err(Error::InvalidSize);
396 }
397 let len = self.heights.len();
398 let total = self.heights.total();
399 let offset = offset.min((total - viewport).max(0.0));
400 if len == 0 || viewport == 0.0 {
401 return Ok(Window {
402 offset,
403 total,
404 bottom: total,
405 ..Window::default()
406 });
407 }
408 let start = self.heights.complete_before(offset).min(len);
409 let end_offset = (offset + viewport).min(total);
410 let complete = self.heights.complete_before(end_offset);
411 let end =
412 (complete + usize::from(self.heights.prefix_unchecked(complete) < end_offset)).min(len);
413 let range = start.saturating_sub(self.overscan)..end.saturating_add(self.overscan).min(len);
414 let top = self.heights.prefix_unchecked(range.start);
415 let bottom = (total - self.heights.prefix_unchecked(range.end)).max(0.0);
416 Ok(Window {
417 visible: start..end,
418 render: range,
419 offset,
420 total,
421 top,
422 bottom,
423 })
424 }
425
426 pub fn anchor(&self, offset: f64) -> Result<Option<Anchor>, Error> {
427 if !nonnegative(offset) {
428 return Err(Error::InvalidSize);
429 }
430 if self.heights.is_empty() {
431 return Ok(None);
432 }
433 let index = self
434 .heights
435 .complete_before(offset)
436 .min(self.heights.len() - 1);
437 Ok(Some(Anchor {
438 index,
439 within: (offset - self.heights.prefix_unchecked(index))
440 .clamp(0.0, self.heights.height(index).expect("known row")),
441 }))
442 }
443
444 pub fn restore(&self, anchor: Anchor) -> Result<f64, Error> {
447 if !nonnegative(anchor.within) {
448 return Err(Error::InvalidSize);
449 }
450 let height = self
451 .heights
452 .height(anchor.index)
453 .ok_or(Error::OutOfBounds)?;
454 Ok(self.heights.prefix_unchecked(anchor.index) + anchor.within.min(height))
455 }
456
457 pub fn measure(
458 &mut self,
459 index: usize,
460 height: f64,
461 anchor: Option<Anchor>,
462 ) -> Result<(bool, Option<f64>), Error> {
463 if let Some(anchor) = anchor {
464 self.restore(anchor)?;
465 }
466 let changed = self.heights.measure(index, height)?;
467 Ok((
468 changed,
469 anchor.map(|anchor| self.restore(anchor)).transpose()?,
470 ))
471 }
472
473 pub fn splice(
477 &mut self,
478 range: Range<usize>,
479 inserted: usize,
480 estimate: f64,
481 anchor: Option<Anchor>,
482 ) -> Result<Option<f64>, Error> {
483 if let Some(anchor) = anchor {
484 self.restore(anchor)?;
485 }
486 let removed = range
487 .end
488 .checked_sub(range.start)
489 .ok_or(Error::InvalidRange)?;
490 self.heights.splice(range.clone(), inserted, estimate)?;
491 let Some(anchor) = anchor else {
492 return Ok(None);
493 };
494 if self.heights.is_empty() {
495 return Ok(None);
496 }
497 let next = if anchor.index < range.start {
498 anchor
499 } else if anchor.index >= range.end {
500 Anchor {
501 index: anchor.index - removed + inserted,
502 ..anchor
503 }
504 } else {
505 Anchor {
506 index: range.start.min(self.heights.len() - 1),
507 within: 0.0,
508 }
509 };
510 self.restore(next).map(Some)
511 }
512}