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
#![allow(incomplete_features, clippy::arc_with_non_send_sync)]
#![feature(generic_const_exprs)]
//! AnyRope is an arbitrary data rope for Rust.
//!
//! AnyRope's [`Rope<M>`] contains elements `M` that implement [`Measurable`], a
//! trait that assigns an arbitrary "width" to each element, through the
//! [`width()`][Measurable::width] function. AnyRope can then use these "widths"
//! to retrieve and iterate over elements in any given "width" from the beginning
//! of the [`Rope<M>`].
//!
//! Keep in mind that the "width" does not correspond to the actual size of a type
//! in bits or bytes, but is instead decided by the implementor, and can be whatever
//! value they want.
//!
//! The library is made up of four main components:
//!
//! - [`Rope<M>`]: the main rope type.
//! - [`RopeSlice<M>`]: an immutable view into part of a [`Rope<M>`].
//! - [`iter`]: iterators over [`Rope<M>`]/[`RopeSlice<M>`] data.
//! - [`RopeBuilder<M>`]: an efficient incremental [`Rope<M>`] builder.
//!
//! # A Basic Example
//!
//! Let's say we want create a tagging system that will be applied to text,
//! in which the tags either tell you to print normally, print in red, underline, or skip:
//!
//! ```rust
//! # use std::io::Result;
//! use std::fs::File;
//! use std::io::{BufReader, BufWriter};
//! use any_rope::{Rope, Measurable};
//!
//! // A simple tag structure that our program can understand.
//! #[derive(Clone, Copy)]
//! enum Tag {
//! InRed,
//! UnderLine,
//! Normal,
//! // The `usize` in here represents an amount of characters that won't change
//! // the color of the text.
//! Skip(usize)
//! }
//!
//! impl Measurable for Tag {
//! fn width(&self) -> usize {
//! match self {
//! // The coloring tags are only meant to color, not to "move forward".
//! Tag::InRed | Tag::UnderLine | Tag::Normal => 0,
//! // The Skip tag represents an amount of characters in which no
//! // tags are applied.
//! Tag::Skip(amount) => *amount
//! }
//! }
//! }
//! use Tag::*;
//!
//! # fn activate_tag(tag: &Tag) {}
//! // An `&str` that will be colored.
//! let my_str = "This word will be red!";
//!
//! // Here's what this means:
//! // - Skip 5 characters;
//! // - Change the color to red;
//! // - Start underlining;
//! // - Skip 4 characters;
//! // - Change the rendering back to normal.
//! let my_tagger = Rope::from_slice(&[Skip(5), InRed, UnderLine, Skip(4), Normal]);
//! // Do note that Tag::Skip only represents characters because we are also iterating
//! // over a `Chars` iterator, and have chosen to do so.
//!
//! let mut tags_iter = my_tagger.iter().peekable();
//! for (cur_index, ch) in my_str.chars().enumerate() {
//! // The while let loop here is a useful way to activate all tags within the same
//! // character. Note the sequence of [.., InRed, UnderLine, ..], both of which have
//! // a width of 0. This means that both would be triggered before moving on to the next
//! // character.
//! while let Some((index, tag)) = tags_iter.peek() {
//! // The returned index is always the width where an element began. In this
//! // case, `tags_iter.peek()` would return `Some((0, Skip(5)))`, and then
//! // `Some((5, InRed))`.
//! if *index == cur_index {
//! activate_tag(tag);
//! tags_iter.next();
//! } else {
//! break;
//! }
//! }
//!
//! print!("{}", ch);
//! }
//! ```
//!
//! An example can be found in the `examples` directory, detailing a "search and replace"
//! functionality for [`Rope<M>`].
//!
//! # Low-level APIs
//!
//! AnyRope also provides access to some of its low-level APIs, enabling client
//! code to efficiently work with a [`Rope<M>`]'s data and implement new
//! functionality. The most important of those API's are:
//!
//! - The [`chunk_at_*()`][Rope::chunk_at_width]
//! chunk-fetching methods of [`Rope<M>`] and [`RopeSlice<M>`].
//! - The [`Chunks`](iter::Chunks) iterator.
//! - The functions in `slice_utils` for operating on [`&[M]`][Measurable] slices.
//!
//! As a reminder, if you notice similarities with the AnyRope crate, it is because this
//! is a heavily modified fork of it.
#![allow(clippy::collapsible_if)]
#![allow(clippy::inline_always)]
#![allow(clippy::needless_return)]
#![allow(clippy::redundant_field_names)]
#![allow(clippy::type_complexity)]
mod rope;
mod rope_builder;
mod slice;
mod slice_utils;
mod tree;
pub mod iter;
use std::ops::Bound;
pub use crate::rope::{Measurable, Rope};
pub use crate::rope_builder::RopeBuilder;
pub use crate::slice::RopeSlice;
pub use crate::tree::{max_children, max_len};
/// A struct meant for testing and exemplification
///
/// Its [`width`][Measurable::width] is always equal to the number within.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Width(pub usize);
impl Measurable for Width {
fn width(&self) -> usize {
self.0
}
}
//==============================================================
// Error reporting types.
/// AnyRope's result type.
pub type Result<T> = std::result::Result<T, Error>;
/// AnyRope's error type.
#[derive(Clone, Copy)]
#[non_exhaustive]
pub enum Error {
/// Indicates that the passed index was out of bounds.
///
/// Contains the index attempted and the actual length of the
/// [`Rope<M>`]/[`RopeSlice<M>`], in that order.
IndexOutOfBounds(usize, usize),
/// Indicates that the passed width was out of bounds.
///
/// Contains the index attempted and the actual width of the
/// [`Rope<M>`]/[`RopeSlice<M>`], in that order.
WidthOutOfBounds(usize, usize),
/// Indicates that a reversed index range (end < start) was encountered.
///
/// Contains the [start, end) indices of the range, in that order.
IndexRangeInvalid(
usize, // Start.
usize, // End.
),
/// Indicates that a reversed width range (end < start) was
/// encountered.
///
/// Contains the [start, end) widths of the range, in that order.
WidthRangeInvalid(
usize, // Start.
usize, // End.
),
/// Indicates that the passed index range was partially or fully out of bounds.
///
/// Contains the [start, end) indices of the range and the actual
/// length of the [`Rope<M>`]/[`RopeSlice<M>`], in that order.
/// When either the start or end are [`None`], that indicates a half-open range.
IndexRangeOutOfBounds(
Option<usize>, // Start.
Option<usize>, // End.
usize, // Rope byte length.
),
/// Indicates that the passed width range was partially or fully out of bounds.
///
/// Contains the [start, end) widths of the range and the actual
/// width of the [`Rope<M>`]/[`RopeSlice<M>`], in that order.
/// When either the start or end are [`None`], that indicates a half-open range.
WidthRangeOutOfBounds(
Option<usize>, // Start.
Option<usize>, // End.
usize, // Rope char length.
),
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
Error::IndexOutOfBounds(index, len) => {
write!(
f,
"Index out of bounds: index {}, Rope/RopeSlice length {}",
index, len
)
}
Error::WidthOutOfBounds(index, len) => {
write!(
f,
"Width out of bounds: width {}, Rope/RopeSlice char length {}",
index, len
)
}
Error::IndexRangeInvalid(start_idx, end_idx) => {
write!(
f,
"Invalid index range {}..{}: start must be <= end",
start_idx, end_idx
)
}
Error::WidthRangeInvalid(start_idx, end_idx) => {
write!(
f,
"Invalid width range {}..{}: start must be <= end",
start_idx, end_idx
)
}
Error::IndexRangeOutOfBounds(start_idx_opt, end_idx_opt, len) => {
write!(f, "Index range out of bounds: index range ")?;
write_range(f, start_idx_opt, end_idx_opt)?;
write!(f, ", Rope/RopeSlice byte length {}", len)
}
Error::WidthRangeOutOfBounds(start_idx_opt, end_idx_opt, len) => {
write!(f, "Width range out of bounds: width range ")?;
write_range(f, start_idx_opt, end_idx_opt)?;
write!(f, ", Rope/RopeSlice char length {}", len)
}
}
}
}
impl std::error::Error for Error {}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Just re-use the debug impl.
std::fmt::Debug::fmt(self, f)
}
}
fn write_range(
f: &mut std::fmt::Formatter<'_>,
start_idx: Option<usize>,
end_idx: Option<usize>,
) -> std::fmt::Result {
match (start_idx, end_idx) {
(None, None) => write!(f, ".."),
(Some(start), None) => write!(f, "{}..", start),
(None, Some(end)) => write!(f, "..{}", end),
(Some(start), Some(end)) => write!(f, "{}..{}", start, end),
}
}
//==============================================================
// Range handling utilities.
#[inline(always)]
pub(crate) fn start_bound_to_num(b: Bound<&usize>) -> Option<usize> {
match b {
Bound::Included(n) => Some(*n),
Bound::Excluded(n) => Some(*n + 1),
Bound::Unbounded => None,
}
}
#[inline(always)]
pub(crate) fn end_bound_to_num(b: Bound<&usize>) -> Option<usize> {
match b {
Bound::Included(n) => Some(*n + 1),
Bound::Excluded(n) => Some(*n),
Bound::Unbounded => None,
}
}
/// Internal macro used to log information.
#[macro_export]
#[doc(hidden)]
macro_rules! log_info {
($($text:tt)*) => {{
use std::{fs, io::Write};
let mut log = fs::OpenOptions::new().append(true).open("log").unwrap();
log.write_fmt(format_args!($($text)*)).unwrap();
}};
}