v1.rs (24347B)
1 #![forbid(unsafe_code)] 2 3 //! Frozen NIP-01 wire-v1 parsing and canonical-identifier semantics. 4 5 #[cfg(all(not(feature = "std"), not(test)))] 6 use alloc::{ 7 collections::BTreeMap, 8 string::{String, ToString}, 9 vec::Vec, 10 }; 11 12 #[cfg(any(feature = "std", test))] 13 use std::{collections::BTreeMap, string::String, vec::Vec}; 14 15 use crate::envelope::{EventEnvelope, EventEnvelopeError, EventEnvelopeParts}; 16 use crate::id::{EventId, EventSignature, ParseError, parse_public_key}; 17 use core::fmt; 18 use serde_json::{Map, Value}; 19 use sha2::{Digest, Sha256}; 20 21 pub const DEFAULT_RAW_JSON_MAX_BYTES: usize = 256 * 1024; 22 pub const DEFAULT_CONTENT_MAX_BYTES: usize = 128 * 1024; 23 pub const DEFAULT_TAG_MAX_COUNT: usize = 1024; 24 pub const DEFAULT_TAG_TOTAL_ELEMENT_MAX_COUNT: usize = 4096; 25 pub const DEFAULT_TAG_ELEMENT_MAX_BYTES: usize = 4 * 1024; 26 pub const DEFAULT_TAG_TOTAL_MAX_BYTES: usize = 128 * 1024; 27 pub const DEFAULT_EXTRA_MAX_FIELDS: usize = 64; 28 pub const DEFAULT_EXTRA_TOTAL_JSON_MAX_BYTES: usize = 64 * 1024; 29 30 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 31 pub struct EventWireLimits { 32 pub max_raw_json_bytes: usize, 33 pub max_content_bytes: usize, 34 pub max_tag_count: usize, 35 pub max_total_tag_elements: usize, 36 pub max_tag_element_bytes: usize, 37 pub max_total_tag_bytes: usize, 38 pub max_extra_fields: usize, 39 pub max_total_extra_json_bytes: usize, 40 } 41 42 impl Default for EventWireLimits { 43 fn default() -> Self { 44 Self { 45 max_raw_json_bytes: DEFAULT_RAW_JSON_MAX_BYTES, 46 max_content_bytes: DEFAULT_CONTENT_MAX_BYTES, 47 max_tag_count: DEFAULT_TAG_MAX_COUNT, 48 max_total_tag_elements: DEFAULT_TAG_TOTAL_ELEMENT_MAX_COUNT, 49 max_tag_element_bytes: DEFAULT_TAG_ELEMENT_MAX_BYTES, 50 max_total_tag_bytes: DEFAULT_TAG_TOTAL_MAX_BYTES, 51 max_extra_fields: DEFAULT_EXTRA_MAX_FIELDS, 52 max_total_extra_json_bytes: DEFAULT_EXTRA_TOTAL_JSON_MAX_BYTES, 53 } 54 } 55 } 56 57 #[derive(Clone, Debug, PartialEq, Eq)] 58 pub enum CanonicalEventIdError { 59 InvalidPubkey(ParseError), 60 InvalidComputedEventId(ParseError), 61 } 62 63 impl fmt::Display for CanonicalEventIdError { 64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 65 match self { 66 Self::InvalidPubkey(error) => { 67 write!(f, "canonical event id pubkey is invalid: {error}") 68 } 69 Self::InvalidComputedEventId(error) => { 70 write!(f, "canonical event id digest is invalid: {error}") 71 } 72 } 73 } 74 } 75 76 #[cfg(feature = "std")] 77 impl std::error::Error for CanonicalEventIdError {} 78 79 #[derive(Clone, Debug, PartialEq, Eq)] 80 pub enum EventWireError { 81 Json(String), 82 RootNotObject, 83 MissingField(&'static str), 84 InvalidField(&'static str), 85 InvalidIdentifier { 86 field: &'static str, 87 error: ParseError, 88 }, 89 NonCanonicalIdentifier { 90 field: &'static str, 91 }, 92 RawJsonTooLarge { 93 max: usize, 94 actual: usize, 95 }, 96 ContentTooLarge { 97 max: usize, 98 actual: usize, 99 }, 100 TooManyTags { 101 max: usize, 102 actual: usize, 103 }, 104 TooManyTagElements { 105 max: usize, 106 actual: usize, 107 }, 108 EmptyTag { 109 index: usize, 110 }, 111 EmptyTagKey { 112 index: usize, 113 }, 114 ControlCharacterTagKey { 115 index: usize, 116 }, 117 TagElementTooLarge { 118 tag_index: usize, 119 element_index: usize, 120 max: usize, 121 actual: usize, 122 }, 123 TagsTooLarge { 124 max: usize, 125 actual: usize, 126 }, 127 TooManyExtraFields { 128 max: usize, 129 actual: usize, 130 }, 131 ExtraJsonTooLarge { 132 max: usize, 133 actual: usize, 134 }, 135 CanonicalEventId(CanonicalEventIdError), 136 Envelope(EventEnvelopeError), 137 EventIdMismatch { 138 declared: String, 139 computed: String, 140 }, 141 } 142 143 impl fmt::Display for EventWireError { 144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 145 match self { 146 Self::Json(error) => write!(f, "event wire json is invalid: {error}"), 147 Self::RootNotObject => write!(f, "event wire root must be a JSON object"), 148 Self::MissingField(field) => write!(f, "event wire missing required field {field}"), 149 Self::InvalidField(field) => write!(f, "event wire field {field} is invalid"), 150 Self::InvalidIdentifier { field, error } => { 151 write!(f, "event wire field {field} is invalid: {error}") 152 } 153 Self::NonCanonicalIdentifier { field } => { 154 write!( 155 f, 156 "event wire field {field} must be canonical lowercase hex" 157 ) 158 } 159 Self::RawJsonTooLarge { max, actual } => { 160 write!(f, "event wire raw JSON size {actual} exceeds {max} bytes") 161 } 162 Self::ContentTooLarge { max, actual } => { 163 write!(f, "event wire content size {actual} exceeds {max} bytes") 164 } 165 Self::TooManyTags { max, actual } => { 166 write!(f, "event wire tag count {actual} exceeds {max}") 167 } 168 Self::TooManyTagElements { max, actual } => { 169 write!(f, "event wire tag element count {actual} exceeds {max}") 170 } 171 Self::EmptyTag { index } => write!(f, "event wire tag {index} is empty"), 172 Self::EmptyTagKey { index } => write!(f, "event wire tag {index} key is empty"), 173 Self::ControlCharacterTagKey { index } => { 174 write!(f, "event wire tag {index} key contains a control character") 175 } 176 Self::TagElementTooLarge { 177 tag_index, 178 element_index, 179 max, 180 actual, 181 } => write!( 182 f, 183 "event wire tag {tag_index} element {element_index} size {actual} exceeds {max} bytes" 184 ), 185 Self::TagsTooLarge { max, actual } => { 186 write!(f, "event wire tag bytes {actual} exceed {max}") 187 } 188 Self::TooManyExtraFields { max, actual } => { 189 write!(f, "event wire extra field count {actual} exceeds {max}") 190 } 191 Self::ExtraJsonTooLarge { max, actual } => { 192 write!(f, "event wire extra JSON bytes {actual} exceed {max}") 193 } 194 Self::CanonicalEventId(error) => write!(f, "{error}"), 195 Self::Envelope(error) => write!(f, "{error}"), 196 Self::EventIdMismatch { declared, computed } => write!( 197 f, 198 "event wire id mismatch: declared {declared}, computed {computed}" 199 ), 200 } 201 } 202 } 203 204 #[cfg(feature = "std")] 205 impl std::error::Error for EventWireError {} 206 207 impl From<CanonicalEventIdError> for EventWireError { 208 fn from(value: CanonicalEventIdError) -> Self { 209 Self::CanonicalEventId(value) 210 } 211 } 212 213 impl From<EventEnvelopeError> for EventWireError { 214 fn from(value: EventEnvelopeError) -> Self { 215 Self::Envelope(value) 216 } 217 } 218 219 #[cfg_attr( 220 any(feature = "serde", test), 221 derive(serde::Serialize, serde::Deserialize) 222 )] 223 #[derive(Clone, Debug, PartialEq, Eq)] 224 pub struct Nip01EventWireParts { 225 pub kind: u32, 226 pub content: String, 227 pub tags: Vec<Vec<String>>, 228 } 229 230 #[cfg_attr( 231 any(feature = "serde", test), 232 derive(serde::Serialize, serde::Deserialize) 233 )] 234 #[derive(Clone, Debug, PartialEq, Eq)] 235 pub struct Nip01EventWire { 236 pub id: String, 237 pub pubkey: String, 238 pub created_at: u64, 239 pub kind: u32, 240 pub tags: Vec<Vec<String>>, 241 pub content: String, 242 pub sig: String, 243 #[cfg_attr(any(feature = "serde", test), serde(flatten))] 244 pub extra: BTreeMap<String, Value>, 245 } 246 247 impl Nip01EventWire { 248 pub fn parse_json(raw_json: &str) -> Result<Self, EventWireError> { 249 Self::parse_json_with_limits(raw_json, EventWireLimits::default()) 250 } 251 252 /// Parses and structurally validates an event without verifying its ID. 253 /// 254 /// This boundary enforces every [`EventWireLimits`] budget. Callers must 255 /// invoke [`Self::verify_id`] before treating the result as ID-verified. 256 pub fn parse_json_unverified(raw_json: &str) -> Result<Self, EventWireError> { 257 Self::parse_json_unverified_with_limits(raw_json, EventWireLimits::default()) 258 } 259 260 pub fn parse_json_with_limits( 261 raw_json: &str, 262 limits: EventWireLimits, 263 ) -> Result<Self, EventWireError> { 264 let wire = Self::parse_json_unverified_with_limits(raw_json, limits)?; 265 wire.verify_id()?; 266 Ok(wire) 267 } 268 269 /// Parses the exact seven-field NIP-01 event profile. Root keys, including 270 /// escaped spellings, must occur exactly once; nesting is bounded to 16 271 /// before the semantic JSON decoder allocates values. Unknown fields are 272 /// unsupported by this exact signing-result profile. Historical/general 273 /// decoding retains its separately governed behavior. 274 pub fn parse_json_exact_with_limits( 275 raw_json: &str, 276 limits: EventWireLimits, 277 ) -> Result<Self, EventWireError> { 278 if raw_json.len() > limits.max_raw_json_bytes { 279 return Err(EventWireError::RawJsonTooLarge { 280 max: limits.max_raw_json_bytes, 281 actual: raw_json.len(), 282 }); 283 } 284 if !exact_event_json_shape(raw_json) { 285 return Err(EventWireError::InvalidField("exact_event_profile")); 286 } 287 Self::parse_json_with_limits(raw_json, limits) 288 } 289 290 /// Parses and structurally validates an event under explicit limits 291 /// without verifying its ID. 292 pub fn parse_json_unverified_with_limits( 293 raw_json: &str, 294 limits: EventWireLimits, 295 ) -> Result<Self, EventWireError> { 296 let raw_len = raw_json.len(); 297 if raw_len > limits.max_raw_json_bytes { 298 return Err(EventWireError::RawJsonTooLarge { 299 max: limits.max_raw_json_bytes, 300 actual: raw_len, 301 }); 302 } 303 let value = serde_json::from_str::<Value>(raw_json) 304 .map_err(|error| EventWireError::Json(error.to_string()))?; 305 Self::from_json_value(value, limits) 306 } 307 308 pub fn canonical_id_preimage(&self) -> Result<String, CanonicalEventIdError> { 309 canonical_nip01_event_id_preimage( 310 self.pubkey.as_str(), 311 self.created_at, 312 self.kind, 313 &self.tags, 314 self.content.as_str(), 315 ) 316 } 317 318 pub fn computed_event_id(&self) -> Result<EventId, CanonicalEventIdError> { 319 compute_canonical_nip01_event_id( 320 self.pubkey.as_str(), 321 self.created_at, 322 self.kind, 323 &self.tags, 324 self.content.as_str(), 325 ) 326 } 327 328 pub fn verify_id(&self) -> Result<(), EventWireError> { 329 let computed = self.computed_event_id()?.into_string(); 330 if computed.as_str() != self.id.as_str() { 331 return Err(EventWireError::EventIdMismatch { 332 declared: self.id.clone(), 333 computed, 334 }); 335 } 336 Ok(()) 337 } 338 339 pub fn into_envelope(self) -> Result<EventEnvelope, EventWireError> { 340 self.verify_id()?; 341 self.into_unverified_envelope() 342 .map_err(EventWireError::Envelope) 343 } 344 345 /// Converts structurally validated wire data without verifying its ID. 346 /// 347 /// The returned envelope remains untrusted until an admission typestate 348 /// transition verifies its canonical ID and signature. 349 pub fn into_unverified_envelope(self) -> Result<EventEnvelope, EventEnvelopeError> { 350 EventEnvelope::new(EventEnvelopeParts { 351 id: self.id, 352 author: self.pubkey, 353 created_at: self.created_at, 354 kind: self.kind, 355 tags: self.tags, 356 content: self.content, 357 sig: self.sig, 358 }) 359 } 360 361 fn from_json_value(value: Value, limits: EventWireLimits) -> Result<Self, EventWireError> { 362 let mut object = match value { 363 Value::Object(object) => object, 364 _ => return Err(EventWireError::RootNotObject), 365 }; 366 let id = take_canonical_event_id(&mut object)?; 367 let pubkey = take_canonical_pubkey(&mut object)?; 368 let created_at = take_u64(&mut object, "created_at")?; 369 let kind = take_u32(&mut object, "kind")?; 370 let tags = take_tags(&mut object, limits)?; 371 let content = take_string(&mut object, "content")?; 372 let content_len = content.len(); 373 if content_len > limits.max_content_bytes { 374 return Err(EventWireError::ContentTooLarge { 375 max: limits.max_content_bytes, 376 actual: content_len, 377 }); 378 } 379 let sig = take_canonical_signature(&mut object)?; 380 let extra = validate_extra(object, limits)?; 381 let wire = Self { 382 id, 383 pubkey, 384 created_at, 385 kind, 386 tags, 387 content, 388 sig, 389 extra, 390 }; 391 Ok(wire) 392 } 393 } 394 395 pub fn canonical_nip01_event_id_preimage( 396 pubkey: &str, 397 created_at: u64, 398 kind: u32, 399 tags: &[Vec<String>], 400 content: &str, 401 ) -> Result<String, CanonicalEventIdError> { 402 canonical_nip01_event_id_preimage_v1(pubkey, created_at, kind, tags, content) 403 } 404 405 /// Serializes the canonical NIP-01 event-id preimage with wire-v1 semantics. 406 pub fn canonical_nip01_event_id_preimage_v1( 407 pubkey: &str, 408 created_at: u64, 409 kind: u32, 410 tags: &[Vec<String>], 411 content: &str, 412 ) -> Result<String, CanonicalEventIdError> { 413 let author = parse_public_key(pubkey).map_err(CanonicalEventIdError::InvalidPubkey)?; 414 Ok(radroots_protocol::nip01::canonical_preimage( 415 &radroots_protocol::nip01::EventFields { 416 author, 417 created_at, 418 kind, 419 tags, 420 content, 421 }, 422 )) 423 } 424 425 pub fn compute_canonical_nip01_event_id( 426 pubkey: &str, 427 created_at: u64, 428 kind: u32, 429 tags: &[Vec<String>], 430 content: &str, 431 ) -> Result<EventId, CanonicalEventIdError> { 432 compute_canonical_nip01_event_id_v1(pubkey, created_at, kind, tags, content) 433 } 434 435 /// Computes the canonical NIP-01 event identifier with wire-v1 semantics. 436 pub fn compute_canonical_nip01_event_id_v1( 437 pubkey: &str, 438 created_at: u64, 439 kind: u32, 440 tags: &[Vec<String>], 441 content: &str, 442 ) -> Result<EventId, CanonicalEventIdError> { 443 let preimage = canonical_nip01_event_id_preimage_v1(pubkey, created_at, kind, tags, content)?; 444 let digest = Sha256::digest(preimage.as_bytes()); 445 let event_id = hex::encode(digest); 446 EventId::parse(event_id).map_err(CanonicalEventIdError::InvalidComputedEventId) 447 } 448 449 fn take_string( 450 object: &mut Map<String, Value>, 451 field: &'static str, 452 ) -> Result<String, EventWireError> { 453 match object.remove(field) { 454 Some(Value::String(value)) => Ok(value), 455 Some(_) => Err(EventWireError::InvalidField(field)), 456 None => Err(EventWireError::MissingField(field)), 457 } 458 } 459 460 fn take_canonical_event_id(object: &mut Map<String, Value>) -> Result<String, EventWireError> { 461 let raw = take_string(object, "id")?; 462 let parsed = EventId::parse(raw.as_str()) 463 .map_err(|error| EventWireError::InvalidIdentifier { field: "id", error })?; 464 canonical_identifier_string("id", raw, parsed.into_string()) 465 } 466 467 fn take_canonical_pubkey(object: &mut Map<String, Value>) -> Result<String, EventWireError> { 468 let raw = take_string(object, "pubkey")?; 469 let parsed = 470 parse_public_key(raw.as_str()).map_err(|error| EventWireError::InvalidIdentifier { 471 field: "pubkey", 472 error, 473 })?; 474 canonical_identifier_string("pubkey", raw, parsed.to_hex()) 475 } 476 477 fn take_canonical_signature(object: &mut Map<String, Value>) -> Result<String, EventWireError> { 478 let raw = take_string(object, "sig")?; 479 let parsed = 480 EventSignature::parse(raw.as_str()).map_err(|error| EventWireError::InvalidIdentifier { 481 field: "sig", 482 error, 483 })?; 484 canonical_identifier_string("sig", raw, parsed.into_string()) 485 } 486 487 fn canonical_identifier_string( 488 field: &'static str, 489 raw: String, 490 canonical: String, 491 ) -> Result<String, EventWireError> { 492 if canonical.as_str() != raw.as_str() { 493 return Err(EventWireError::NonCanonicalIdentifier { field }); 494 } 495 Ok(canonical) 496 } 497 498 fn take_u64(object: &mut Map<String, Value>, field: &'static str) -> Result<u64, EventWireError> { 499 match object.remove(field) { 500 Some(Value::Number(value)) => value.as_u64().ok_or(EventWireError::InvalidField(field)), 501 Some(_) => Err(EventWireError::InvalidField(field)), 502 None => Err(EventWireError::MissingField(field)), 503 } 504 } 505 506 fn take_u32(object: &mut Map<String, Value>, field: &'static str) -> Result<u32, EventWireError> { 507 let value = take_u64(object, field)?; 508 u32::try_from(value).map_err(|_| EventWireError::InvalidField(field)) 509 } 510 511 fn take_tags( 512 object: &mut Map<String, Value>, 513 limits: EventWireLimits, 514 ) -> Result<Vec<Vec<String>>, EventWireError> { 515 let raw_tags = match object.remove("tags") { 516 Some(Value::Array(raw_tags)) => raw_tags, 517 Some(_) => return Err(EventWireError::InvalidField("tags")), 518 None => return Err(EventWireError::MissingField("tags")), 519 }; 520 let tag_count = raw_tags.len(); 521 if tag_count > limits.max_tag_count { 522 return Err(EventWireError::TooManyTags { 523 max: limits.max_tag_count, 524 actual: tag_count, 525 }); 526 } 527 let total_tag_elements = raw_tags.iter().try_fold(0usize, |total, raw_tag| { 528 let Value::Array(values) = raw_tag else { 529 return Err(EventWireError::InvalidField("tags")); 530 }; 531 Ok(total.saturating_add(values.len())) 532 })?; 533 if total_tag_elements > limits.max_total_tag_elements { 534 return Err(EventWireError::TooManyTagElements { 535 max: limits.max_total_tag_elements, 536 actual: total_tag_elements, 537 }); 538 } 539 let mut total_tag_bytes = 0usize; 540 let mut tags = Vec::with_capacity(tag_count); 541 for (tag_index, raw_tag) in raw_tags.into_iter().enumerate() { 542 let raw_values = match raw_tag { 543 Value::Array(values) => values, 544 _ => return Err(EventWireError::InvalidField("tags")), 545 }; 546 if raw_values.is_empty() { 547 return Err(EventWireError::EmptyTag { index: tag_index }); 548 } 549 let mut tag = Vec::with_capacity(raw_values.len()); 550 for (element_index, raw_value) in raw_values.into_iter().enumerate() { 551 let value = match raw_value { 552 Value::String(value) => value, 553 _ => return Err(EventWireError::InvalidField("tags")), 554 }; 555 let value_len = value.len(); 556 if value_len > limits.max_tag_element_bytes { 557 return Err(EventWireError::TagElementTooLarge { 558 tag_index, 559 element_index, 560 max: limits.max_tag_element_bytes, 561 actual: value_len, 562 }); 563 } 564 if element_index == 0 { 565 validate_tag_key(tag_index, value.as_str())?; 566 } 567 total_tag_bytes = total_tag_bytes.saturating_add(value_len); 568 if total_tag_bytes > limits.max_total_tag_bytes { 569 return Err(EventWireError::TagsTooLarge { 570 max: limits.max_total_tag_bytes, 571 actual: total_tag_bytes, 572 }); 573 } 574 tag.push(value); 575 } 576 tags.push(tag); 577 } 578 Ok(tags) 579 } 580 581 fn validate_tag_key(index: usize, value: &str) -> Result<(), EventWireError> { 582 if value.is_empty() { 583 return Err(EventWireError::EmptyTagKey { index }); 584 } 585 if value.chars().any(char::is_control) { 586 return Err(EventWireError::ControlCharacterTagKey { index }); 587 } 588 Ok(()) 589 } 590 591 fn validate_extra( 592 object: Map<String, Value>, 593 limits: EventWireLimits, 594 ) -> Result<BTreeMap<String, Value>, EventWireError> { 595 let extra_count = object.len(); 596 if extra_count > limits.max_extra_fields { 597 return Err(EventWireError::TooManyExtraFields { 598 max: limits.max_extra_fields, 599 actual: extra_count, 600 }); 601 } 602 let mut total_json_bytes = 0usize; 603 let mut extra = BTreeMap::new(); 604 for (key, value) in object { 605 let key_json_len = serialized_json_string_len(&key); 606 let value_json_len = serialized_json_value_len(&value); 607 total_json_bytes = total_json_bytes 608 .saturating_add(key_json_len) 609 .saturating_add(1) 610 .saturating_add(value_json_len); 611 if total_json_bytes > limits.max_total_extra_json_bytes { 612 return Err(EventWireError::ExtraJsonTooLarge { 613 max: limits.max_total_extra_json_bytes, 614 actual: total_json_bytes, 615 }); 616 } 617 extra.insert(key, value); 618 } 619 Ok(extra) 620 } 621 622 #[cfg_attr(coverage_nightly, coverage(off))] 623 fn serialized_json_string_len(value: &String) -> usize { 624 serde_json::to_vec(value) 625 .expect("JSON strings always serialize") 626 .len() 627 } 628 629 #[cfg_attr(coverage_nightly, coverage(off))] 630 fn serialized_json_value_len(value: &Value) -> usize { 631 serde_json::to_vec(value) 632 .expect("JSON values always serialize") 633 .len() 634 } 635 636 // This policy guard does not interpret event values. The existing JSON and 637 // event validators remain authoritative for syntax, types, budgets and ID. 638 fn exact_event_json_shape(raw: &str) -> bool { 639 let (mut depth, mut seen) = (0usize, 0u8); 640 let (mut in_string, mut escaped, mut expect_key, mut root_key) = (false, false, false, false); 641 let mut start = 0usize; 642 for (index, byte) in raw.bytes().enumerate() { 643 if in_string { 644 if escaped { 645 escaped = false; 646 continue; 647 } 648 match byte { 649 b'\\' => escaped = true, 650 b'"' => { 651 in_string = false; 652 if root_key { 653 // Every supported ASCII key has at most ten characters; 654 // even its fully escaped spelling fits this bound. 655 if index - start + 1 > 64 { 656 return false; 657 } 658 let Ok(key) = serde_json::from_str::<String>(&raw[start..=index]) else { 659 return false; 660 }; 661 let bit = match key.as_str() { 662 "id" => 1, 663 "pubkey" => 2, 664 "created_at" => 4, 665 "kind" => 8, 666 "tags" => 16, 667 "content" => 32, 668 "sig" => 64, 669 _ => return false, 670 }; 671 if seen & bit != 0 { 672 return false; 673 } 674 seen |= bit; 675 } 676 } 677 _ => {} 678 } 679 continue; 680 } 681 match byte { 682 b'"' => { 683 in_string = true; 684 start = index; 685 root_key = depth == 1 && expect_key; 686 } 687 b'{' | b'[' => { 688 if depth == 0 { 689 if byte != b'{' || seen != 0 { 690 return false; 691 } 692 expect_key = true; 693 } 694 depth += 1; 695 if depth > 16 { 696 return false; 697 } 698 } 699 b'}' | b']' => { 700 let Some(next) = depth.checked_sub(1) else { 701 return false; 702 }; 703 depth = next; 704 } 705 b':' if depth == 1 => expect_key = false, 706 b',' if depth == 1 => expect_key = true, 707 _ => {} 708 } 709 } 710 !in_string && depth == 0 && seen == 127 711 } 712 713 #[cfg(test)] 714 #[cfg_attr(coverage_nightly, coverage(off))] 715 mod tests;