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
//! Classification of structurally significant JSON bytes.
//!
//! Provides the [`Structural`] struct and [`StructuralIterator`] trait
//! that allow effectively iterating over structural characters in a JSON document.
//!
//! Classifying [`Commas`](`Structural::Comma`) and [`Colons`](`Structural::Colon`) is disabled by default.
//! It can be enabled on demand by calling
//! [`StructuralIterator::turn_commas_on`]/[`StructuralIterator::turn_colons_on`].
//! This configuration is persisted across [`stop`](StructuralIterator::stop) and
//! [`resume`](StructuralIterator::resume) calls.
//!
//! A structural classifier needs ownership over a base
//! [`QuoteClassifiedIterator`](`crate::classification::quotes::QuoteClassifiedIterator`).
//!
//! # Examples
//! ```rust
//! use rsonpath_lib::classification::structural::{BracketType, Structural, classify_structural_characters};
//! use aligners::AlignedBytes;
//!
//! let json = r#"{"x": [{"y": 42}, {}]}""#;
//! let aligned = AlignedBytes::new_padded(json.as_bytes());
//! let expected = vec![
//! Structural::Opening(BracketType::Curly, 0),
//! Structural::Opening(BracketType::Square, 6),
//! Structural::Opening(BracketType::Curly, 7),
//! Structural::Closing(BracketType::Curly, 15),
//! Structural::Opening(BracketType::Curly, 18),
//! Structural::Closing(BracketType::Curly, 19),
//! Structural::Closing(BracketType::Square, 20),
//! Structural::Closing(BracketType::Curly, 21)
//! ];
//! let quote_classifier = rsonpath_lib::classification::quotes::classify_quoted_sequences(&aligned);
//! let actual = classify_structural_characters(quote_classifier).collect::<Vec<Structural>>();
//! assert_eq!(expected, actual);
//! ```
//! ```rust
//! use rsonpath_lib::classification::structural::{BracketType, Structural, classify_structural_characters};
//! use rsonpath_lib::classification::quotes::classify_quoted_sequences;
//! use aligners::{alignment, AlignedBytes};
//!
//! let json = r#"{"x": "[\"\"]"}""#;
//! let aligned = AlignedBytes::new_padded(json.as_bytes());
//! let expected = vec![
//! Structural::Opening(BracketType::Curly, 0),
//! Structural::Closing(BracketType::Curly, 14)
//! ];
//! let quote_classifier = classify_quoted_sequences(&aligned);
//! let actual = classify_structural_characters(quote_classifier).collect::<Vec<Structural>>();
//! assert_eq!(expected, actual);
//! ```
use crate::classification::{quotes::QuoteClassifiedIterator, ResumeClassifierState};
use cfg_if::cfg_if;
/// Defines the kinds of brackets that can be identified as structural.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[repr(u8)]
pub enum BracketType {
/// Square brackets, '[' and ']'.
Square,
/// Curly braces, '{' and '}'.
Curly,
}
/// Defines structural characters in JSON documents.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Structural {
/// Represents the closing square or curly brace, ']' or '}'.
Closing(BracketType, usize),
/// Represents the colon ':' character.
Colon(usize),
/// Represents the opening square or curly brace, '[' or '{'.
Opening(BracketType, usize),
/// Represents the comma ',' character.
Comma(usize),
}
use Structural::*;
impl Structural {
/// Returns the index of the character in the document,
/// i.e. which byte it is counting from 0.
#[inline(always)]
#[must_use]
pub fn idx(self) -> usize {
match self {
Closing(_, idx) | Colon(idx) | Opening(_, idx) | Comma(idx) => idx,
}
}
/// Add a given amount to the structural's index.
///
/// # Examples
/// ```rust
/// # use rsonpath_lib::classification::structural::Structural;
///
/// let structural = Structural::Colon(42);
/// let offset_structural = structural.offset(10);
///
/// assert_eq!(structural.idx(), 42);
/// assert_eq!(offset_structural.idx(), 52);
/// ```
#[inline(always)]
#[must_use]
pub fn offset(self, amount: usize) -> Self {
match self {
Closing(b, idx) => Closing(b, idx + amount),
Colon(idx) => Colon(idx + amount),
Opening(b, idx) => Opening(b, idx + amount),
Comma(idx) => Comma(idx + amount),
}
}
/// Check if the structural represents a closing character,
/// i.e. a [`Closing`] with either of the [`BracketType`] variants.
///
/// # Examples
/// ```rust
/// # use rsonpath_lib::classification::structural::{BracketType, Structural};
///
/// let brace = Structural::Closing(BracketType::Curly, 42);
/// let bracket = Structural::Closing(BracketType::Square, 43);
/// let neither = Structural::Comma(44);
///
/// assert!(brace.is_closing());
/// assert!(bracket.is_closing());
/// assert!(!neither.is_closing());
/// ```
#[inline(always)]
#[must_use]
pub fn is_closing(&self) -> bool {
matches!(self, Closing(_, _))
}
/// Check if the structural represents an opening character,
/// i.e. an [`Opening`] with either of the [`BracketType`] variants.
///
/// # Examples
/// ```rust
/// # use rsonpath_lib::classification::structural::{BracketType, Structural};
///
/// let brace = Structural::Opening(BracketType::Curly, 42);
/// let bracket = Structural::Opening(BracketType::Square, 43);
/// let neither = Structural::Comma(44);
///
/// assert!(brace.is_opening());
/// assert!(bracket.is_opening());
/// assert!(!neither.is_opening());
/// ```
#[inline(always)]
#[must_use]
pub fn is_opening(&self) -> bool {
matches!(self, Opening(_, _))
}
}
/// Trait for classifier iterators, i.e. finite iterators of [`Structural`] characters
/// that hold a reference to the JSON document valid for `'a`.
pub trait StructuralIterator<'a, I: QuoteClassifiedIterator<'a>>:
Iterator<Item = Structural> + 'a
{
/// Stop classification and return a state object that can be used to resume
/// a classifier from the place in which the current one was stopped.
fn stop(self) -> ResumeClassifierState<'a, I>;
/// Resume classification from a state retrieved by stopping a classifier.
fn resume(state: ResumeClassifierState<'a, I>) -> Self;
/// Turn classification of [`Structural::Colon`] characters off.
fn turn_colons_off(&mut self);
/// Turn classification of [`Structural::Colon`] characters on.
///
/// The `idx` passed should be the index of the byte in the input
/// from which commas are to be classified. Passing an `idx` that
/// does not match the index which the internal [`QuoteClassifiedIterator`]
/// reached may result in incorrect results.
fn turn_colons_on(&mut self, idx: usize);
/// Turn classification of [`Structural::Comma`] characters off.
fn turn_commas_off(&mut self);
/// Turn classification of [`Structural::Comma`] characters on.
///
/// The `idx` passed should be the index of the byte in the input
/// from which commas are to be classified. Passing an `idx` that
/// does not match the index which the internal [`QuoteClassifiedIterator`]
/// reached may result in incorrect results.
fn turn_commas_on(&mut self, idx: usize);
}
cfg_if! {
if #[cfg(any(doc, not(feature = "simd")))] {
mod nosimd;
use nosimd::*;
/// Walk through the JSON document represented by `bytes` and iterate over all
/// occurrences of structural characters in it.
#[inline(always)]
pub fn classify_structural_characters<'a, I: QuoteClassifiedIterator<'a>>(
iter: I,
) -> impl StructuralIterator<'a, I> {
SequentialClassifier::new(iter)
}
/// Resume classification using a state retrieved from a previously
/// used classifier via the `stop` function.
#[inline(always)]
pub fn resume_structural_classification<'a, I: QuoteClassifiedIterator<'a>>(
state: ResumeClassifierState<'a, I>
) -> impl StructuralIterator<'a, I> {
SequentialClassifier::resume(state)
}
}
else if #[cfg(simd = "avx2")] {
mod avx2;
use avx2::Avx2Classifier;
/// Walk through the JSON document represented by `bytes` and iterate over all
/// occurrences of structural characters in it.
#[inline(always)]
pub fn classify_structural_characters<'a, I: QuoteClassifiedIterator<'a>>(
iter: I,
) -> impl StructuralIterator<'a, I> {
Avx2Classifier::new(iter)
}
/// Resume classification using a state retrieved from a previously
/// used classifier via the `stop` function.
#[inline(always)]
pub fn resume_structural_classification<'a, I: QuoteClassifiedIterator<'a>>(
state: ResumeClassifierState<'a, I>
) -> impl StructuralIterator<'a, I> {
Avx2Classifier::resume(state)
}
}
else {
compile_error!("Target architecture is not supported by SIMD features of this crate. Disable the default `simd` feature.");
}
}
#[cfg(test)]
mod tests {
use crate::classification::quotes::classify_quoted_sequences;
use super::*;
use aligners::AlignedBytes;
#[test]
fn resumption_without_commas_or_colons() {
use BracketType::*;
use Structural::*;
let json = r#"{"a": [42, 36, { "b": { "c": 1, "d": 2 } }]}"#;
let bytes = AlignedBytes::new_padded(json.as_bytes());
let quotes = classify_quoted_sequences(&bytes);
let mut classifier = classify_structural_characters(quotes);
assert_eq!(Some(Opening(Curly, 0)), classifier.next());
assert_eq!(Some(Opening(Square, 6)), classifier.next());
let resume_state = classifier.stop();
let mut resumed_classifier = resume_structural_classification(resume_state);
assert_eq!(Some(Opening(Curly, 15)), resumed_classifier.next());
assert_eq!(Some(Opening(Curly, 22)), resumed_classifier.next());
}
#[test]
fn resumption_with_commas_but_no_colons() {
use BracketType::*;
use Structural::*;
let json = r#"{"a": [42, 36, { "b": { "c": 1, "d": 2 } }]}"#;
let bytes = AlignedBytes::new_padded(json.as_bytes());
let quotes = classify_quoted_sequences(&bytes);
let mut classifier = classify_structural_characters(quotes);
classifier.turn_commas_on(0);
assert_eq!(Some(Opening(Curly, 0)), classifier.next());
assert_eq!(Some(Opening(Square, 6)), classifier.next());
assert_eq!(Some(Comma(9)), classifier.next());
assert_eq!(Some(Comma(13)), classifier.next());
let resume_state = classifier.stop();
let mut resumed_classifier = resume_structural_classification(resume_state);
assert_eq!(Some(Opening(Curly, 15)), resumed_classifier.next());
assert_eq!(Some(Opening(Curly, 22)), resumed_classifier.next());
assert_eq!(Some(Comma(30)), resumed_classifier.next());
}
#[test]
fn resumption_with_colons_but_no_commas() {
use BracketType::*;
use Structural::*;
let json = r#"{"a": [42, 36, { "b": { "c": 1, "d": 2 } }]}"#;
let bytes = AlignedBytes::new_padded(json.as_bytes());
let quotes = classify_quoted_sequences(&bytes);
let mut classifier = classify_structural_characters(quotes);
classifier.turn_colons_on(0);
assert_eq!(Some(Opening(Curly, 0)), classifier.next());
assert_eq!(Some(Colon(4)), classifier.next());
assert_eq!(Some(Opening(Square, 6)), classifier.next());
let resume_state = classifier.stop();
let mut resumed_classifier = resume_structural_classification(resume_state);
assert_eq!(Some(Opening(Curly, 15)), resumed_classifier.next());
assert_eq!(Some(Colon(20)), resumed_classifier.next());
assert_eq!(Some(Opening(Curly, 22)), resumed_classifier.next());
assert_eq!(Some(Colon(27)), resumed_classifier.next());
}
#[test]
fn resumption_with_commas_and_colons() {
use BracketType::*;
use Structural::*;
let json = r#"{"a": [42, 36, { "b": { "c": 1, "d": 2 } }]}"#;
let bytes = AlignedBytes::new_padded(json.as_bytes());
let quotes = classify_quoted_sequences(&bytes);
let mut classifier = classify_structural_characters(quotes);
classifier.turn_commas_on(0);
classifier.turn_colons_on(0);
assert_eq!(Some(Opening(Curly, 0)), classifier.next());
assert_eq!(Some(Colon(4)), classifier.next());
assert_eq!(Some(Opening(Square, 6)), classifier.next());
assert_eq!(Some(Comma(9)), classifier.next());
assert_eq!(Some(Comma(13)), classifier.next());
let resume_state = classifier.stop();
let mut resumed_classifier = resume_structural_classification(resume_state);
assert_eq!(Some(Opening(Curly, 15)), resumed_classifier.next());
assert_eq!(Some(Colon(20)), resumed_classifier.next());
assert_eq!(Some(Opening(Curly, 22)), resumed_classifier.next());
assert_eq!(Some(Colon(27)), resumed_classifier.next());
assert_eq!(Some(Comma(30)), resumed_classifier.next());
}
}