pax_global_header00006660000000000000000000000064147721607150014524gustar00rootroot0000000000000052 comment=45e4f21388cb4b3ea3190d9aeb9df2d47d82f3dc btm-0+20250330/000077500000000000000000000000001477216071500127015ustar00rootroot00000000000000btm-0+20250330/.github/000077500000000000000000000000001477216071500142415ustar00rootroot00000000000000btm-0+20250330/.github/FUNDING.yml000066400000000000000000000000231477216071500160510ustar00rootroot00000000000000ko_fi: clementtsangbtm-0+20250330/.github/workflows/000077500000000000000000000000001477216071500162765ustar00rootroot00000000000000btm-0+20250330/.github/workflows/ci.yml000066400000000000000000000045101477216071500174140ustar00rootroot00000000000000# Main CI workflow to validate PRs and branches are correctly formatted # and pass tests. name: ci on: workflow_dispatch: pull_request: push: branches: - main env: RUST_BACKTRACE: 1 CARGO_INCREMENTAL: 0 CARGO_PROFILE_DEV_DEBUG: 0 CARGO_HUSKY_DONT_INSTALL_HOOKS: true concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' || github.repository != 'ClementTsang/dircs' }} jobs: # Check if things should be skipped. pre-job: runs-on: ubuntu-latest outputs: should_skip: ${{ steps.skip_check.outputs.should_skip }} steps: - name: Check if this action should be skipped id: skip_check uses: fkirc/skip-duplicate-actions@f75f66ce1886f00957d99748a42c724f4330bdcf # v5.3.1 with: skip_after_successful_duplicate: "true" paths: '[".github/workflows/ci.yml", "src/**", "Cargo.lock", "Cargo.toml"]' do_not_skip: '["workflow_dispatch", "push"]' # Runs rustfmt + tests + clippy. test: needs: pre-job if: ${{ needs.pre-job.outputs.should_skip != 'true' }} runs-on: "ubuntu-latest" timeout-minutes: 18 steps: - name: Checkout repository uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 - name: Set up Rust toolchain uses: dtolnay/rust-toolchain@d8352f6b1d2e870bc5716e7a6d9b65c4cc244a1a with: toolchain: stable components: rustfmt, clippy target: x86_64-unknown-linux-gnu - name: Enable Rust cache uses: Swatinem/rust-cache@9bdad043e88c75890e36ad3bbc8d27f0090dd609 # 2.7.3 if: ${{ github.event_name != 'pull_request' || ! github.event.pull_request.head.repo.fork }} # If it is a PR, only if not a fork with: cache-all-crates: true - name: Check cargo fmt run: cargo fmt --all -- --check - name: Run tests uses: ClementTsang/cargo-action@v0.0.5 with: command: test args: --no-fail-fast -- --nocapture --quiet env: RUST_BACKTRACE: full - name: Run clippy uses: ClementTsang/cargo-action@v0.0.5 with: command: clippy args: --all-targets --workspace -- -D warnings cross-version: 0.2.5 env: RUST_BACKTRACE: full btm-0+20250330/.gitignore000066400000000000000000000000101477216071500146600ustar00rootroot00000000000000/target btm-0+20250330/CHANGELOG.md000066400000000000000000000035051477216071500145150ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). Versioning for this project is based on [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## v0.0.14-alpha - 2025-01-26 ### Changes - `ChunkedData::iter_along_base` now returns elements if the base time slice is smaller than the stored data. ## v0.0.13-alpha - 2025-01-25 ### Changes - Renamed the `into_iter` function to `into_owned_iter` to avoid confusion. ### Bugs Fix a bunch of clippy warnings. ## v0.0.12-alpha - 2025-01-20 ### Features - Add a helper function to only shrink the chunk. ## v0.0.11-alpha - 2025-01-20 ### Features - Add a helper function to additionally shrink the chunk when pruning. ## v0.0.10-alpha - 2025-01-18 ### Features - Make the iterator reversible. ## v0.0.9-alpha - 2025-01-18 ### Features - Add `no_elements` function for convenience. ## v0.0.8-alpha - 2025-01-18 ### Features - Add `last` and `first` functions for convenience. ## v0.0.7-alpha - 2025-01-17 ### Bugs - Fix bug around setting next index internally after pruning ## v0.0.6-alpha - 2025-01-16 ### Bugs - Fix bug around pruning indices that are low causing a subtraction underflow. ## v0.0.5-alpha - 2025-01-12 ### Changes - Enable `clone`. ## v0.0.4-alpha - 2025-01-11 ### Changes - `push` has been renamed to `try_push`; `push` now only accepts a value of type `D`. ### Features - Some extra functions added for more fine-grain control. ## v0.0.3-alpha - 2025-01-11 ### Features - Add `Debug` trait to relevant types. ## v0.0.2-alpha - 2025-01-11 ### Changes - A few functions have been renamed. - Some documentation added/tweaked. ### Features - `iter_along_base` added for convenience. ## v0.0.1-alpha - 2025-01-11 Initial base release. btm-0+20250330/Cargo.lock000066400000000000000000000002371477216071500146100ustar00rootroot00000000000000# This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "timeless" version = "0.0.14-alpha" btm-0+20250330/Cargo.toml000066400000000000000000000014711477216071500146340ustar00rootroot00000000000000[package] name = "timeless" version = "0.0.14-alpha" edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/ClementTsang/timeless" description = "A crate of utilities for storing in-memory timeseries data." readme = "README.md" documentation = "https://docs.rs/timeless/" authors = ["Clement Tsang "] categories = [] keywords = [] exclude = [ ".github/", ".idea", ".vscode/", ".gitignore", ".markdownlint.json", "CHANGELOG.md", "clippy.toml", "rustfmt.toml", ] [lib] test = true doctest = true doc = true [dependencies] # No dependencies! [lints.rust] rust_2018_idioms = "deny" [lints.rustdoc] broken_intra_doc_links = "deny" missing_crate_level_docs = "deny" [lints.clippy] todo = "deny" unimplemented = "deny" missing_safety_doc = "deny" btm-0+20250330/LICENSE-APACHE000066400000000000000000000261351477216071500146340ustar00rootroot00000000000000 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. btm-0+20250330/LICENSE-MIT000066400000000000000000000020561477216071500143400ustar00rootroot00000000000000MIT License Copyright (c) 2025 Clement Tsang 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. btm-0+20250330/README.md000066400000000000000000000011411477216071500141550ustar00rootroot00000000000000

timeless

A crate of utilities for storing in-memory timeseries data.

[crates.io link](https://crates.io/crates/timeless) [Documentation](https://docs.rs/timeless)
## Usage **Note**: This is a very experimental crate written mainly for use in [bottom](https://github.com/ClementTsang/bottom), and will currently change a lot. You've been warned. ## Licensing This crate is dual-licensed under Apache 2.0 and MIT. btm-0+20250330/rustfmt.toml000066400000000000000000000005151477216071500153030ustar00rootroot00000000000000reorder_imports = true reorder_modules = true merge_derives = true fn_params_layout = "Compressed" use_field_init_shorthand = true tab_spaces = 4 max_width = 100 # Unstable options, disabled by default. # imports_granularity = "Crate" # group_imports = "StdExternalCrate" # wrap_comments = true # format_code_in_doc_comments = true btm-0+20250330/src/000077500000000000000000000000001477216071500134705ustar00rootroot00000000000000btm-0+20250330/src/data.rs000066400000000000000000000000661477216071500147510ustar00rootroot00000000000000mod chunked; pub use chunked::*; // mod non_chunked; btm-0+20250330/src/data/000077500000000000000000000000001477216071500144015ustar00rootroot00000000000000btm-0+20250330/src/data/chunked.rs000066400000000000000000000417331477216071500164000ustar00rootroot00000000000000//! This is code responsible for possibly chunked data. #[derive(Clone, Default, Debug)] struct DataChunk { /// The start offset of this chunk, should correspond to the time vector /// indices. If that updates, this MUST also update. start_offset: usize, /// The actual value data! data: Vec, } impl DataChunk { fn push(&mut self, item: T) { self.data.push(item) } } /// An iterator created from a [`ChunkedData`]. pub struct ChunkedDataIter { iter: I, size: usize, // TODO: We can probably store this as a `OnceCell` instead to avoid computing it if we don't need it. } impl> Iterator for ChunkedDataIter { type Item = T; fn next(&mut self) -> Option { self.iter.next() } fn size_hint(&self) -> (usize, Option) { (self.size, Some(self.size)) } } impl> ExactSizeIterator for ChunkedDataIter {} impl + DoubleEndedIterator> DoubleEndedIterator for ChunkedDataIter { fn next_back(&mut self) -> Option { self.iter.next_back() } } /// A struct representing data that may potentially have breaks. /// If you expect that you may want to store time values but _not_ /// data values, use this to avoid storing blanks. #[derive(Clone, Default, Debug)] pub struct ChunkedData { next_index: usize, is_active: bool, chunks: Vec>, } impl ChunkedData { /// Returns an iterator of items alongside the associated indices for each item. pub fn iter_with_index(&self) -> ChunkedDataIter> { let size = self.chunks.iter().map(|dc| dc.data.len()).sum(); let iter = self.chunks.iter().flat_map(|dc| { let start = dc.start_offset; dc.data .iter() .enumerate() .map(move |(offset, datum)| (start + offset, datum)) }); ChunkedDataIter { iter, size } } /// Returns an iterator of items. pub fn iter(&self) -> ChunkedDataIter> { let size = self.chunks.iter().map(|dc| dc.data.len()).sum(); let iter = self.chunks.iter().flat_map(|dc| dc.data.iter()); ChunkedDataIter { iter, size } } /// Returns an iterator of owned items. This consumes the [`ChunkedData`]. /// /// Note this is currently not just `into_iter` due to how it's implemented, this is subject to change. pub fn into_owned_iter(self) -> ChunkedDataIter> { let size = self.chunks.iter().map(|dc| dc.data.len()).sum(); let iter = self.chunks.into_iter().flat_map(|dc| dc.data.into_iter()); ChunkedDataIter { iter, size } } /// Given a slice that serves as the "base" yielding items `T`, return an iterator of `(T, D)`, where each `D` from /// the [`ChunkedData`] has its index associated with that of `base_slice`. /// /// This is meant to be used alongside a slice of time values. /// /// Note this will return the minimum of the number of elements in either the base slice or the [`ChunkedData`]. pub fn iter_along_base<'a, T>( &'a self, base_slice: &'a [T], ) -> ChunkedDataIter> { let size = if base_slice.len() >= self.length() { // Happy path. We return at most the number of stored elements! self.num_elements() } else { // Uh oh. We need a bit more logic around this step. let mut num_returned_elements = 0; for dc in self.chunks.iter() { let start = dc.start_offset; let end = dc.start_offset + dc.data.len(); if base_slice.len() > end { num_returned_elements += dc.data.len(); } else if base_slice.len() < start { break; } else { // It's somewhere in the middle. num_returned_elements += base_slice.len() - start; } } num_returned_elements }; let iter = self.chunks.iter().flat_map(move |dc| { let start = dc.start_offset; let to_take = base_slice.len().saturating_sub(start); // Take at most all the values in the chunk, or up to the number of base element indices. dc.data .iter() .take(to_take) .enumerate() .map(move |(offset, datum)| { let actual_index = start + offset; let base = &base_slice[actual_index]; (base, datum) }) }); ChunkedDataIter { iter, size } } /// Return how many elements actually are stored in the [`ChunkedData`]. pub fn num_elements(&self) -> usize { self.chunks.iter().map(|dc| dc.data.len()).sum() } /// Return the "length" of the [`ChunkedData`], _including_ skipped /// elements. pub fn length(&self) -> usize { self.next_index } /// Push an element. pub fn push(&mut self, item: D) { if self.is_active { let current_chunk = self .chunks .last_mut() .expect("chunks must be initialized with at least a value if is_active is set"); current_chunk.push(item); } else { // Start a new chunk. self.chunks.push(DataChunk { start_offset: self.next_index, data: vec![item], }); self.is_active = true; } self.next_index += 1; } /// Manually mark that a break is needed in the chunk. pub fn insert_break(&mut self) { // "Seal" the latest chunk. self.is_active = false; } /// Push an element. If `item` is [`None`], then it will automatically /// insert a break in the chunk if needed. pub fn try_push(&mut self, item: Option) { match item { Some(item) => { self.push(item); } None => { self.insert_break(); self.next_index += 1; } } } /// Remove all elements up to (and including) `index`, including "skipped" /// elements. This will result in the effective length becoming /// `prev_length - index - 1`. /// /// If `index` goes past the number of elements, this function will return /// an error containing the stored index in the [`ChunkedData`]. pub fn prune(&mut self, index: usize) -> Result<(), usize> { if self.next_index == 0 || self.next_index - 1 < index || self.chunks.is_empty() { return Err(self.next_index); } self.next_index -= index + 1; let dc_index = match self.chunks.binary_search_by(|c| c.start_offset.cmp(&index)) { Ok(result) => result, Err(result) => { if result > 0 { result - 1 } else { // Nothing to prune. We still need to change the offsets though. for chunk in &mut self.chunks { chunk.start_offset -= index + 1; } return Ok(()); } } }; // SAFETY: This index must be valid since it was returned from the binary search. let curr = unsafe { self.chunks.get_unchecked_mut(dc_index) }; let to_remove = index - curr.start_offset + 1; if to_remove <= curr.data.len() { curr.data.drain(..to_remove); curr.start_offset = 0; // Remove all previous chunks. self.chunks.drain(0..dc_index); // Update offsets for all following chunks. for chunk in self.chunks.iter_mut().skip(1) { chunk.start_offset -= to_remove; } } else { // Drain this chunk too. self.chunks.drain(0..=dc_index); for chunk in &mut self.chunks { chunk.start_offset -= to_remove; } } Ok(()) } /// Shrink the [`ChunkedData`] after. pub fn shrink_to_fit(&mut self) { for chunk in &mut self.chunks { chunk.data.shrink_to_fit(); } self.chunks.shrink_to_fit(); } /// Convenience function to prune _and_ shrink the [`ChunkedData`] after. pub fn prune_and_shrink_to_fit(&mut self, index: usize) -> Result<(), usize> { self.prune(index)?; self.shrink_to_fit(); Ok(()) } /// Try and return the first element. pub fn first(&self) -> Option<&D> { self.chunks.first().and_then(|chunk| chunk.data.first()) } /// Try and return the last element. pub fn last(&self) -> Option<&D> { self.chunks.last().and_then(|chunk| chunk.data.last()) } /// Return whether there are zero elements left stored internally. pub fn no_elements(&self) -> bool { self.num_elements() == 0 } } #[cfg(test)] mod tests { use super::*; #[test] fn chunked_push() { let mut data = ChunkedData::default(); assert!(data.no_elements()); data.try_push(Some(1)); assert!(!data.chunks.is_empty()); assert!(data.is_active); assert_eq!(data.chunks.last().as_ref().unwrap().data, vec![1]); assert_eq!(data.next_index, 1); data.try_push(Some(2)); data.try_push(None); assert!(!data.is_active); assert_eq!(data.chunks.len(), 1); assert_eq!(data.chunks.first().unwrap().data, vec![1, 2]); assert_eq!(data.next_index, 3); data.try_push(None); assert!(!data.is_active); assert_eq!(data.next_index, 4); data.try_push(Some(3)); assert!(data.is_active); assert_eq!(data.chunks.last().as_ref().unwrap().data, vec![3]); assert_eq!(data.next_index, 5); assert_eq!(data.length(), 5); assert_eq!(data.num_elements(), 3); } /// Ensure that if we push nothing at first, we don't incorrectly try and /// seal nothing. #[test] fn chunked_empty_initial_push() { let mut data: ChunkedData = ChunkedData::default(); data.try_push(None); assert!(!data.is_active); data.try_push(Some(1)); assert!(data.is_active); assert_eq!(data.next_index, 2); } const POPULATION: [Option; 10] = [ Some(1), Some(2), Some(3), None, None, None, Some(7), Some(8), Some(9), Some(10), ]; fn test_populate(data: &mut ChunkedData) { for p in POPULATION { data.try_push(p); } } /// Initialize data, prune, and insert. #[track_caller] fn test_pruning(to_prune_index: usize) { // println!("Trying to prune up to index {to_prune_index}..."); let mut data = ChunkedData::default(); test_populate(&mut data); assert!(data.prune(to_prune_index).is_ok()); let removed = to_prune_index + 1; let result = data .iter_with_index() .map(|(a, b)| (a, *b)) .collect::>(); let expected = POPULATION .into_iter() .skip(removed) .enumerate() .filter_map(|(a, b)| b.map(|b| (a, b))) .collect::>(); assert_eq!(result, expected); assert_eq!(data.next_index, POPULATION.len() - (to_prune_index + 1)); } #[test] fn chunked_prune() { test_pruning(0); test_pruning(1); test_pruning(2); test_pruning(3); test_pruning(4); test_pruning(5); test_pruning(6); test_pruning(7); test_pruning(8); test_pruning(9); } /// Handle if we try and prune something empty. #[test] fn chunked_prune_empty() { let mut data: ChunkedData = ChunkedData::default(); assert!(data.prune(0).is_err()); } /// Handle if we try to clear an index past the index stored. #[test] fn chunked_prune_past_index() { let mut data = ChunkedData::default(); test_populate(&mut data); assert!(data.prune(10).is_err()); } #[test] fn chunked_prune_without_curr() { let mut data = ChunkedData::default(); test_populate(&mut data); data.try_push(None); assert!(data.prune(10).is_ok()); } #[test] fn prune_zero_when_none() { let mut data = ChunkedData::default(); data.try_push(None); data.try_push(None); data.try_push(None); test_populate(&mut data); assert!(data.prune(0).is_ok()); assert_eq!(data.chunks[0].start_offset, 2); assert_eq!(data.chunks[1].start_offset, 8); assert_eq!(data.next_index, POPULATION.len() + 3 - 1); assert!(data.prune(0).is_ok()); assert_eq!(data.chunks[0].start_offset, 1); assert_eq!(data.chunks[1].start_offset, 7); assert_eq!(data.next_index, POPULATION.len() + 3 - 2); assert!(data.prune(0).is_ok()); assert_eq!(data.chunks[0].start_offset, 0); assert_eq!(data.chunks[1].start_offset, 6); assert_eq!(data.next_index, POPULATION.len() + 3 - 3); assert!(data.prune(0).is_ok()); assert_eq!(data.chunks[0].start_offset, 0); assert_eq!(data.chunks[0].data.as_slice(), &[2, 3]); assert_eq!(data.chunks[1].start_offset, 5); assert_eq!(data.next_index, POPULATION.len() + 3 - 4); } #[test] fn first_last() { let mut data = ChunkedData::default(); test_populate(&mut data); assert_eq!(data.first(), Some(&1)); assert_eq!(data.last(), Some(&10)); } #[test] fn iter() { let mut data = ChunkedData::default(); test_populate(&mut data); assert_eq!( data.into_owned_iter().collect::>(), POPULATION.iter().filter_map(|v| *v).collect::>(), ); } #[test] fn reverse_iter() { let mut data = ChunkedData::default(); test_populate(&mut data); assert_eq!( data.into_owned_iter().rev().collect::>(), POPULATION .iter() .filter_map(|v| *v) .rev() .collect::>(), ); } #[track_caller] fn base_slice_test( data: &ChunkedData, base_slice: &[u32], expected: &[(u32, u32)], base_slice_index: usize, expected_slice_index: usize, ) { let base_slice = &base_slice[0..base_slice_index]; assert_eq!( data.iter_along_base(base_slice).len(), expected_slice_index, "the returned size of the iterator should match" ); assert_eq!( data.iter_along_base(base_slice) .map(|(a, b)| (*a, *b)) .collect::>(), expected[0..expected_slice_index], "the actual generated values should match" ); } #[test] fn base_slice_simple() { let mut data = ChunkedData::default(); data.push(1); data.push(2); data.push(3); let base_slice = [1, 2, 3, 4, 5]; let expected = [(1, 1), (2, 2), (3, 3)]; // Test with a larger base slice base_slice_test(&data, &base_slice, &expected, 5, 3); // Test with an exact base slice base_slice_test(&data, &base_slice, &expected, 3, 3); // Test with a smaller base slice base_slice_test(&data, &base_slice, &expected, 2, 2); base_slice_test(&data, &base_slice, &expected, 1, 1); base_slice_test(&data, &base_slice, &expected, 0, 0); } #[test] fn base_slice_chunked() { let mut data = ChunkedData::default(); data.push(1); data.push(2); data.push(3); data.try_push(None); data.try_push(None); data.try_push(None); data.push(7); data.push(8); data.push(9); let base_slice = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let expected = [(1, 1), (2, 2), (3, 3), (7, 7), (8, 8), (9, 9)]; // Test with a larger base slice base_slice_test(&data, &base_slice, &expected, 10, 6); // Test with an exact base slice base_slice_test(&data, &base_slice, &expected, 9, 6); // Test with a smaller base slice base_slice_test(&data, &base_slice, &expected, 8, 5); base_slice_test(&data, &base_slice, &expected, 7, 4); base_slice_test(&data, &base_slice, &expected, 6, 3); base_slice_test(&data, &base_slice, &expected, 5, 3); base_slice_test(&data, &base_slice, &expected, 4, 3); base_slice_test(&data, &base_slice, &expected, 3, 3); base_slice_test(&data, &base_slice, &expected, 2, 2); base_slice_test(&data, &base_slice, &expected, 1, 1); base_slice_test(&data, &base_slice, &expected, 0, 0); } } btm-0+20250330/src/data/non_chunked.rs000066400000000000000000000005501477216071500172420ustar00rootroot00000000000000//! This is code responsible for *non-chunked* data //! corresponding to times in a [`crate::time::OffsetTimeList`]. //! AKA, this is just one giant timespan with no breaks. /// A struct representing data that will not have any breaks; /// if you use this, you are assuming each time will have a /// corresponding value. pub struct NonChunkedData(Vec); btm-0+20250330/src/lib.rs000066400000000000000000000004321477216071500146030ustar00rootroot00000000000000//! A crate of utilities for storing in-memory timeseries data. //! //! **Note**: This is a very experimental crate written mainly for use in //! [bottom](https://github.com/ClementTsang/bottom), and will currently //! change a lot. You've been warned. pub mod data; pub mod time; btm-0+20250330/src/time.rs000066400000000000000000000000241477216071500147700ustar00rootroot00000000000000// mod offset_time; btm-0+20250330/src/time/000077500000000000000000000000001477216071500144265ustar00rootroot00000000000000btm-0+20250330/src/time/offset_time.rs000066400000000000000000000103601477216071500173000ustar00rootroot00000000000000//! Code around the time aspect. Stored as a list of offsets, //! each a negative offset of the next value, with the latest //! value being represented in whole. use std::time::{Duration, Instant}; /// Time stored as a bunch of offsets. #[derive(Default, Clone, Debug)] pub struct OffsetTimeList { time_offsets: Vec, checkpoints: Vec<(Instant, usize)>, current_time: Option, } impl OffsetTimeList { /// Create a [`OffsetTimeList`] with a capacity pre-initialized. pub fn with_capacity(capacity: usize) -> Self { Self::with_both_capacity(capacity, 0) } /// Create a [`OffsetTimeList`] with both time storage and /// checkpoint capacity pre-initialized. pub fn with_both_capacity(time_capacity: usize, checkpoint_capacity: usize) -> Self { Self { time_offsets: Vec::with_capacity(time_capacity), checkpoints: Vec::with_capacity(checkpoint_capacity), current_time: None, } } /// Add a time entry. This will return the current index, /// which can be used to update any [`crate::data::Data`] entries /// that are corresponding to this [`OffsetTimeList`]. pub fn add(&mut self, time: Instant) -> usize { if let Some(current_time) = self.current_time { let offset = time.duration_since(current_time).as_millis() as u32; self.current_time = Some(time); self.time_offsets.push(offset); // The current "index" is the length of the vec - 1, but we // add back 1 since we store the current head as a separate instant. self.time_offsets.len() } else { self.current_time = Some(time); 1 } } /// Add a "checkpoint"; this is used for pruning by time. pub fn checkpoint(&mut self) { if let Some(current_time) = self.current_time { self.checkpoints .push((current_time, self.time_offsets.len())); } } /// Approximately prune time values older than the given [`Duration`], /// and returns the new index. pub fn prune(&mut self, max_age: Duration) -> Option { if let Some(current_time) = self.current_time { let checkpoint_index = match self.checkpoints.binary_search_by(|(instant, _)| { println!( "current time duration since: {:?}", current_time.duration_since(*instant) ); current_time.duration_since(*instant).cmp(&max_age) }) { Ok(index) | Err(index) => index, }; let checkpoint_index = std::cmp::min(checkpoint_index, self.checkpoints.len().saturating_sub(1)); match self.checkpoints.drain(..checkpoint_index).last() { Some((_, index)) => { if index < self.time_offsets.len() { self.time_offsets.drain(..index); Some(self.time_offsets.len()) } else { self.time_offsets.clear(); self.current_time = None; Some(0) } } None => None, } } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_add() { let mut times = OffsetTimeList::default(); let now = Instant::now(); times.add(now); assert_eq!(times.current_time, Some(now)); let next = now + Duration::from_millis(1); times.add(next); assert_eq!(times.current_time, Some(next)); assert_eq!(times.time_offsets, vec!(1)); } #[test] fn test_prune() { let mut times = OffsetTimeList::default(); // Test fully empty. assert_eq!(times.prune(Duration::from_secs(0)), None); let now = Instant::now(); times.add(now); // Test no checkpoint. assert_eq!(times.prune(Duration::from_secs(0)), None); // Add a checkpoint, try clearing it. times.add(now); times.checkpoint(); assert_eq!(times.prune(Duration::from_secs(1000)), Some(1)); assert_eq!(times.prune(Duration::from_secs(0)), None); } }