1use std::{
8 fmt,
9 io::{Read, Write},
10};
11
12use serde::{
13 Deserialize, Serialize,
14 de::{IgnoredAny, SeqAccess, Visitor},
15};
16use sha2::{Digest, Sha256};
17
18pub const MAX_ENCODED_MANIFEST_BYTES: u64 = 64 * 1024 * 1024;
19pub const MAX_CHUNK_DESCRIPTORS: usize = 262_144;
20pub const MAX_OBJECT_BYTES: u64 = 1024 * 1024 * 1024 * 1024;
21pub const MANIFEST_FORMAT_V1: &str = "folderbase-chunk-manifest-v1";
22pub const CHUNKING_ALGORITHM_V1: &str = "folderbase-cdc-v1+sha256";
23pub const STANDARD_PROFILE_V1: &str = "standard-v1";
24pub const LARGE_PROFILE_V1: &str = "large-v1";
25const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
26pub const TRANSFER_IO_BUFFER_BYTES: usize = 64 * 1024;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub(crate) struct ProfileParameters {
31 pub minimum_chunk_bytes: u64,
32 pub average_chunk_bytes: u64,
33 pub maximum_chunk_bytes: u64,
34}
35
36pub(crate) fn profile_parameters(profile: &str) -> Option<ProfileParameters> {
37 match profile {
38 STANDARD_PROFILE_V1 => Some(ProfileParameters {
39 minimum_chunk_bytes: 256 * 1024,
40 average_chunk_bytes: 1024 * 1024,
41 maximum_chunk_bytes: 4 * 1024 * 1024,
42 }),
43 LARGE_PROFILE_V1 => Some(ProfileParameters {
44 minimum_chunk_bytes: 4 * 1024 * 1024,
45 average_chunk_bytes: 16 * 1024 * 1024,
46 maximum_chunk_bytes: 64 * 1024 * 1024,
47 }),
48 _ => None,
49 }
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
53#[serde(deny_unknown_fields)]
54pub struct ChunkManifest {
55 pub format: String,
56 pub algorithm: String,
57 pub profile: String,
58 #[serde(deserialize_with = "deserialize_chunk_size")]
59 pub minimum_chunk_bytes: u64,
60 #[serde(deserialize_with = "deserialize_chunk_size")]
61 pub average_chunk_bytes: u64,
62 #[serde(deserialize_with = "deserialize_chunk_size")]
63 pub maximum_chunk_bytes: u64,
64 pub object_sha256: String,
65 #[serde(deserialize_with = "deserialize_object_size")]
66 pub object_bytes: u64,
67 #[serde(deserialize_with = "deserialize_bounded_chunks")]
68 pub chunks: Vec<ChunkDescriptor>,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
72#[serde(deny_unknown_fields)]
73pub struct ChunkDescriptor {
74 #[serde(deserialize_with = "deserialize_index")]
75 pub index: u32,
76 #[serde(deserialize_with = "deserialize_object_size")]
77 pub offset: u64,
78 #[serde(deserialize_with = "deserialize_chunk_size")]
79 pub bytes: u64,
80 pub sha256: String,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct VerifiedObject {
86 pub manifest_format: String,
87 pub manifest_digest: String,
88 pub object_sha256: String,
89 pub object_bytes: u64,
90}
91
92#[derive(Debug, thiserror::Error)]
93pub enum ManifestError {
94 #[error("encoded chunk manifest exceeds {maximum_bytes} bytes")]
95 EncodedManifestTooLarge { maximum_bytes: u64 },
96
97 #[error("chunk manifest is not valid JSON: {0}")]
98 InvalidJson(#[from] serde_json::Error),
99
100 #[error("chunk manifest violates the protocol: {0}")]
101 InvalidManifest(#[from] ManifestViolation),
102}
103
104#[derive(Debug, thiserror::Error)]
105pub enum ObjectVerificationError {
106 #[error("chunk manifest violates the protocol: {0}")]
107 InvalidManifest(#[from] ManifestViolation),
108
109 #[error("object input failed: {0}")]
110 Reader(#[source] std::io::Error),
111
112 #[error("verified object output failed: {0}")]
113 Writer(#[source] std::io::Error),
114
115 #[error("object exceeds the v1 maximum of {maximum} bytes")]
116 ObjectTooLarge { maximum: u64 },
117
118 #[error("object length {actual} differs from manifest length {expected}")]
119 ObjectLengthMismatch { expected: u64, actual: u64 },
120
121 #[error("whole-object digest differs from the manifest")]
122 ObjectDigestMismatch,
123
124 #[error("content-defined chunk plan differs from the manifest")]
125 ChunkPlanMismatch,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
129pub enum ManifestViolation {
130 #[error("unsupported manifest format")]
131 UnknownFormat,
132
133 #[error("unsupported chunking algorithm")]
134 UnknownAlgorithm,
135
136 #[error("unsupported chunking profile")]
137 UnknownProfile,
138
139 #[error("chunking parameters do not match the declared profile")]
140 ProfileParameterMismatch,
141
142 #[error("whole-object digest is not lowercase hexadecimal SHA-256")]
143 InvalidObjectDigest,
144
145 #[error("chunk {index} digest is not lowercase hexadecimal SHA-256")]
146 InvalidChunkDigest { index: u32 },
147
148 #[error("chunk manifest has more than {maximum} descriptors")]
149 TooManyDescriptors { maximum: usize },
150
151 #[error("whole-object length exceeds the v1 maximum of {maximum} bytes")]
152 ObjectTooLarge { maximum: u64 },
153
154 #[error("chunk descriptor at position {position} has index {actual}")]
155 NonsequentialIndex { position: usize, actual: u32 },
156
157 #[error("chunk {index} has zero length")]
158 ZeroLengthChunk { index: u32 },
159
160 #[error("chunk {index} exceeds the declared maximum size")]
161 ChunkTooLarge { index: u32 },
162
163 #[error("nonfinal chunk {index} is smaller than the declared minimum size")]
164 NonfinalChunkTooSmall { index: u32 },
165
166 #[error("chunk {index} offset exceeds the v1 maximum of {maximum} bytes")]
167 DescriptorOffsetTooLarge { index: u32, maximum: u64 },
168
169 #[error("chunk {index} begins at {actual}, not contiguous offset {expected}")]
170 NoncontiguousOffset {
171 index: u32,
172 expected: u64,
173 actual: u64,
174 },
175
176 #[error("chunk descriptor total {actual} differs from object length {expected}")]
177 ObjectLengthMismatch { expected: u64, actual: u64 },
178
179 #[error("empty object must have zero descriptors and the SHA-256 of empty bytes")]
180 InvalidEmptyObject,
181}
182
183impl ChunkManifest {
184 pub fn decode_bounded(mut reader: impl Read) -> Result<Self, ManifestError> {
185 let mut encoded = Vec::new();
186 reader
187 .by_ref()
188 .take(MAX_ENCODED_MANIFEST_BYTES + 1)
189 .read_to_end(&mut encoded)
190 .map_err(serde_json::Error::io)?;
191 if encoded.len() as u64 > MAX_ENCODED_MANIFEST_BYTES {
192 return Err(ManifestError::EncodedManifestTooLarge {
193 maximum_bytes: MAX_ENCODED_MANIFEST_BYTES,
194 });
195 }
196 Self::decode_slice_bounded(&encoded)
197 }
198
199 pub(crate) fn decode_slice_bounded(encoded: &[u8]) -> Result<Self, ManifestError> {
200 if encoded.len() as u64 > MAX_ENCODED_MANIFEST_BYTES {
201 return Err(ManifestError::EncodedManifestTooLarge {
202 maximum_bytes: MAX_ENCODED_MANIFEST_BYTES,
203 });
204 }
205 let descriptor_count: DescriptorCountProbe = serde_json::from_slice(encoded)?;
206 if descriptor_count.chunks.exceeds_maximum {
207 return Err(ManifestViolation::TooManyDescriptors {
208 maximum: MAX_CHUNK_DESCRIPTORS,
209 }
210 .into());
211 }
212 let manifest: Self = serde_json::from_slice(encoded)?;
213 manifest.validate()?;
214 Ok(manifest)
215 }
216
217 pub fn validate(&self) -> Result<(), ManifestViolation> {
218 if self.format != MANIFEST_FORMAT_V1 {
219 return Err(ManifestViolation::UnknownFormat);
220 }
221 if self.algorithm != CHUNKING_ALGORITHM_V1 {
222 return Err(ManifestViolation::UnknownAlgorithm);
223 }
224 let expected =
225 profile_parameters(&self.profile).ok_or(ManifestViolation::UnknownProfile)?;
226 if (
227 self.minimum_chunk_bytes,
228 self.average_chunk_bytes,
229 self.maximum_chunk_bytes,
230 ) != (
231 expected.minimum_chunk_bytes,
232 expected.average_chunk_bytes,
233 expected.maximum_chunk_bytes,
234 ) {
235 return Err(ManifestViolation::ProfileParameterMismatch);
236 }
237 if !is_sha256(&self.object_sha256) {
238 return Err(ManifestViolation::InvalidObjectDigest);
239 }
240 if self.chunks.len() > MAX_CHUNK_DESCRIPTORS {
241 return Err(ManifestViolation::TooManyDescriptors {
242 maximum: MAX_CHUNK_DESCRIPTORS,
243 });
244 }
245 if self.object_bytes > MAX_OBJECT_BYTES {
246 return Err(ManifestViolation::ObjectTooLarge {
247 maximum: MAX_OBJECT_BYTES,
248 });
249 }
250
251 let mut expected_offset = 0_u64;
252 for (position, descriptor) in self.chunks.iter().enumerate() {
253 if !is_sha256(&descriptor.sha256) {
254 return Err(ManifestViolation::InvalidChunkDigest {
255 index: descriptor.index,
256 });
257 }
258 if descriptor.index != position as u32 {
259 return Err(ManifestViolation::NonsequentialIndex {
260 position,
261 actual: descriptor.index,
262 });
263 }
264 if descriptor.bytes == 0 {
265 return Err(ManifestViolation::ZeroLengthChunk {
266 index: descriptor.index,
267 });
268 }
269 if descriptor.bytes > self.maximum_chunk_bytes {
270 return Err(ManifestViolation::ChunkTooLarge {
271 index: descriptor.index,
272 });
273 }
274 if position + 1 < self.chunks.len() && descriptor.bytes < self.minimum_chunk_bytes {
275 return Err(ManifestViolation::NonfinalChunkTooSmall {
276 index: descriptor.index,
277 });
278 }
279 if descriptor.offset > MAX_OBJECT_BYTES {
280 return Err(ManifestViolation::DescriptorOffsetTooLarge {
281 index: descriptor.index,
282 maximum: MAX_OBJECT_BYTES,
283 });
284 }
285 let end = descriptor.offset + descriptor.bytes;
288 if descriptor.offset != expected_offset {
289 return Err(ManifestViolation::NoncontiguousOffset {
290 index: descriptor.index,
291 expected: expected_offset,
292 actual: descriptor.offset,
293 });
294 }
295 expected_offset = end;
296 }
297 if expected_offset != self.object_bytes {
298 return Err(ManifestViolation::ObjectLengthMismatch {
299 expected: self.object_bytes,
300 actual: expected_offset,
301 });
302 }
303 if self.object_bytes == 0 && (!self.chunks.is_empty() || self.object_sha256 != EMPTY_SHA256)
304 {
305 return Err(ManifestViolation::InvalidEmptyObject);
306 }
307 Ok(())
308 }
309
310 pub fn canonical_digest(&self) -> Result<String, ManifestViolation> {
311 self.validate()?;
312
313 let mut digest = Sha256::new();
314 digest.update(MANIFEST_FORMAT_V1.as_bytes());
315 digest.update([0]);
316 update_identifier(&mut digest, &self.algorithm);
317 update_identifier(&mut digest, &self.profile);
318 digest.update(self.minimum_chunk_bytes.to_be_bytes());
319 digest.update(self.average_chunk_bytes.to_be_bytes());
320 digest.update(self.maximum_chunk_bytes.to_be_bytes());
321 digest.update(decode_sha256(&self.object_sha256));
322 digest.update(self.object_bytes.to_be_bytes());
323 digest.update((self.chunks.len() as u32).to_be_bytes());
324 for descriptor in &self.chunks {
325 digest.update(descriptor.index.to_be_bytes());
326 digest.update(descriptor.offset.to_be_bytes());
327 digest.update(descriptor.bytes.to_be_bytes());
328 digest.update(decode_sha256(&descriptor.sha256));
329 }
330 Ok(format!("{:x}", digest.finalize()))
331 }
332
333 pub fn verify_object(
338 &self,
339 reader: impl Read,
340 ) -> Result<VerifiedObject, ObjectVerificationError> {
341 self.verify_object_and_copy(reader, std::io::sink())
342 }
343
344 pub(crate) fn verify_object_and_copy(
345 &self,
346 mut reader: impl Read,
347 writer: impl Write,
348 ) -> Result<VerifiedObject, ObjectVerificationError> {
349 self.validate()?;
350 let observed = plan_streamed_manifest_and_copy(
351 reader.by_ref().take(self.object_bytes.saturating_add(1)),
352 &self.profile,
353 writer,
354 )?;
355 if observed.object_bytes != self.object_bytes {
356 return Err(ObjectVerificationError::ObjectLengthMismatch {
357 expected: self.object_bytes,
358 actual: observed.object_bytes,
359 });
360 }
361 if observed.object_sha256 != self.object_sha256 {
362 return Err(ObjectVerificationError::ObjectDigestMismatch);
363 }
364 if observed.chunks != self.chunks {
365 return Err(ObjectVerificationError::ChunkPlanMismatch);
366 }
367 Ok(VerifiedObject {
368 manifest_format: self.format.clone(),
369 manifest_digest: self.canonical_digest()?,
370 object_sha256: self.object_sha256.clone(),
371 object_bytes: self.object_bytes,
372 })
373 }
374}
375
376#[derive(Deserialize)]
377struct DescriptorCountProbe {
378 chunks: DescriptorCount,
379}
380
381struct DescriptorCount {
382 exceeds_maximum: bool,
383}
384
385impl<'de> Deserialize<'de> for DescriptorCount {
386 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
387 where
388 D: serde::Deserializer<'de>,
389 {
390 deserializer.deserialize_seq(DescriptorCountVisitor)
391 }
392}
393
394struct DescriptorCountVisitor;
395
396impl<'de> Visitor<'de> for DescriptorCountVisitor {
397 type Value = DescriptorCount;
398
399 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
400 formatter.write_str("an array of chunk descriptors")
401 }
402
403 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
404 where
405 A: SeqAccess<'de>,
406 {
407 let mut count = 0_usize;
408 while sequence.next_element::<IgnoredAny>()?.is_some() {
409 count = count.saturating_add(1);
410 }
411 Ok(DescriptorCount {
412 exceeds_maximum: count > MAX_CHUNK_DESCRIPTORS,
413 })
414 }
415}
416
417fn deserialize_bounded_chunks<'de, D>(deserializer: D) -> Result<Vec<ChunkDescriptor>, D::Error>
418where
419 D: serde::Deserializer<'de>,
420{
421 deserializer.deserialize_seq(BoundedChunkDescriptorsVisitor)
422}
423
424struct BoundedChunkDescriptorsVisitor;
425
426impl<'de> Visitor<'de> for BoundedChunkDescriptorsVisitor {
427 type Value = Vec<ChunkDescriptor>;
428
429 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
430 formatter.write_str("a bounded array of chunk descriptors")
431 }
432
433 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
434 where
435 A: SeqAccess<'de>,
436 {
437 let initial_capacity = sequence.size_hint().unwrap_or(0).min(MAX_CHUNK_DESCRIPTORS);
438 let mut chunks = Vec::with_capacity(initial_capacity);
439 while chunks.len() < MAX_CHUNK_DESCRIPTORS {
440 match sequence.next_element()? {
441 Some(descriptor) => chunks.push(descriptor),
442 None => return Ok(chunks),
443 }
444 }
445 if sequence.next_element::<IgnoredAny>()?.is_some() {
446 return Err(serde::de::Error::custom(format!(
447 "chunk manifest has more than {MAX_CHUNK_DESCRIPTORS} descriptors"
448 )));
449 }
450 Ok(chunks)
451 }
452}
453
454pub(crate) fn plan_streamed_manifest(
455 reader: impl Read,
456 profile: &str,
457) -> Result<ChunkManifest, ObjectVerificationError> {
458 plan_streamed_manifest_and_copy(reader, profile, std::io::sink())
459}
460
461fn plan_streamed_manifest_and_copy(
462 mut reader: impl Read,
463 profile: &str,
464 mut writer: impl Write,
465) -> Result<ChunkManifest, ObjectVerificationError> {
466 let parameters = profile_parameters(profile).ok_or(ManifestViolation::UnknownProfile)?;
467 let mask = parameters.average_chunk_bytes - 1;
468 let mut chunks = Vec::new();
469 let mut buffer = [0_u8; TRANSFER_IO_BUFFER_BYTES];
470 let mut object_hasher = Sha256::new();
471 let mut chunk_hasher = Sha256::new();
472 let mut object_bytes = 0_u64;
473 let mut chunk_offset = 0_u64;
474 let mut chunk_bytes = 0_u64;
475 let mut rolling = 0_u64;
476
477 loop {
478 let read = reader
479 .read(&mut buffer)
480 .map_err(ObjectVerificationError::Reader)?;
481 if read == 0 {
482 break;
483 }
484 writer
485 .write_all(&buffer[..read])
486 .map_err(ObjectVerificationError::Writer)?;
487 object_bytes = object_bytes
488 .checked_add(read as u64)
489 .filter(|bytes| *bytes <= MAX_OBJECT_BYTES)
490 .ok_or(ObjectVerificationError::ObjectTooLarge {
491 maximum: MAX_OBJECT_BYTES,
492 })?;
493 object_hasher.update(&buffer[..read]);
494 let mut unhashed_start = 0;
495 for (position, byte) in buffer[..read].iter().enumerate() {
496 rolling = rolling
497 .rotate_left(1)
498 .wrapping_add((*byte as u64).wrapping_mul(0x9e37_79b1));
499 chunk_bytes += 1;
500 let at_content_boundary =
501 chunk_bytes >= parameters.minimum_chunk_bytes && (rolling & mask) == 0;
502 let at_maximum = chunk_bytes >= parameters.maximum_chunk_bytes;
503 if at_content_boundary || at_maximum {
504 chunk_hasher.update(&buffer[unhashed_start..=position]);
505 push_streamed_descriptor(
506 &mut chunks,
507 chunk_offset,
508 chunk_bytes,
509 chunk_hasher.finalize_reset(),
510 )?;
511 chunk_offset += chunk_bytes;
512 chunk_bytes = 0;
513 rolling = 0;
514 unhashed_start = position + 1;
515 }
516 }
517 chunk_hasher.update(&buffer[unhashed_start..read]);
518 }
519 if chunk_bytes > 0 {
520 push_streamed_descriptor(
521 &mut chunks,
522 chunk_offset,
523 chunk_bytes,
524 chunk_hasher.finalize(),
525 )?;
526 }
527
528 let manifest = ChunkManifest {
529 format: MANIFEST_FORMAT_V1.to_owned(),
530 algorithm: CHUNKING_ALGORITHM_V1.to_owned(),
531 profile: profile.to_owned(),
532 minimum_chunk_bytes: parameters.minimum_chunk_bytes,
533 average_chunk_bytes: parameters.average_chunk_bytes,
534 maximum_chunk_bytes: parameters.maximum_chunk_bytes,
535 object_sha256: format!("{:x}", object_hasher.finalize()),
536 object_bytes,
537 chunks,
538 };
539 manifest.validate()?;
540 Ok(manifest)
541}
542
543fn push_streamed_descriptor(
544 chunks: &mut Vec<ChunkDescriptor>,
545 offset: u64,
546 bytes: u64,
547 digest: impl AsRef<[u8]>,
548) -> Result<(), ObjectVerificationError> {
549 if chunks.len() >= MAX_CHUNK_DESCRIPTORS {
550 return Err(ManifestViolation::TooManyDescriptors {
551 maximum: MAX_CHUNK_DESCRIPTORS,
552 }
553 .into());
554 }
555 let index = u32::try_from(chunks.len()).expect("manifest descriptor cap fits u32");
556 chunks.push(ChunkDescriptor {
557 index,
558 offset,
559 bytes,
560 sha256: digest_hex(digest.as_ref()),
561 });
562 Ok(())
563}
564
565fn digest_hex(bytes: &[u8]) -> String {
566 let mut encoded = String::with_capacity(bytes.len() * 2);
567 for byte in bytes {
568 use std::fmt::Write as _;
569 write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail");
570 }
571 encoded
572}
573
574pub(crate) fn is_sha256(value: &str) -> bool {
575 value.len() == 64
576 && value
577 .bytes()
578 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
579}
580
581fn update_identifier(digest: &mut Sha256, identifier: &str) {
582 digest.update((identifier.len() as u32).to_be_bytes());
583 digest.update(identifier.as_bytes());
584}
585
586fn decode_sha256(value: &str) -> [u8; 32] {
587 let mut decoded = [0_u8; 32];
588 for (destination, encoded) in decoded.iter_mut().zip(value.as_bytes().chunks_exact(2)) {
589 *destination = (hex_nibble(encoded[0]) << 4) | hex_nibble(encoded[1]);
590 }
591 decoded
592}
593
594fn hex_nibble(byte: u8) -> u8 {
595 match byte {
596 b'0'..=b'9' => byte - b'0',
597 b'a'..=b'f' => byte - b'a' + 10,
598 _ => unreachable!("digest syntax is validated before canonical encoding"),
599 }
600}
601
602fn deserialize_chunk_size<'de, D>(deserializer: D) -> Result<u64, D::Error>
603where
604 D: serde::Deserializer<'de>,
605{
606 deserialize_exact_unsigned(deserializer, 1, 64 * 1024 * 1024, "chunk byte count")
607}
608
609fn deserialize_object_size<'de, D>(deserializer: D) -> Result<u64, D::Error>
610where
611 D: serde::Deserializer<'de>,
612{
613 deserialize_exact_unsigned(
614 deserializer,
615 0,
616 MAX_OBJECT_BYTES,
617 "object byte count or offset",
618 )
619}
620
621fn deserialize_index<'de, D>(deserializer: D) -> Result<u32, D::Error>
622where
623 D: serde::Deserializer<'de>,
624{
625 let value = deserialize_exact_unsigned(deserializer, 0, u32::MAX as u64, "chunk index")?;
626 Ok(value as u32)
627}
628
629fn deserialize_exact_unsigned<'de, D>(
630 deserializer: D,
631 minimum: u64,
632 maximum: u64,
633 label: &'static str,
634) -> Result<u64, D::Error>
635where
636 D: serde::Deserializer<'de>,
637{
638 let raw = Box::<serde_json::value::RawValue>::deserialize(deserializer)?;
639 parse_exact_unsigned(raw.get())
640 .filter(|value| (minimum..=maximum).contains(value))
641 .ok_or_else(|| {
642 serde::de::Error::custom(format!(
643 "{label} must be an exact integer between {minimum} and {maximum}"
644 ))
645 })
646}
647
648fn parse_exact_unsigned(encoded: &str) -> Option<u64> {
649 let (negative, unsigned) = match encoded.strip_prefix('-') {
650 Some(unsigned) => (true, unsigned),
651 None => (false, encoded),
652 };
653 let (coefficient, exponent) = unsigned
654 .split_once(['e', 'E'])
655 .map_or((unsigned, "0"), |parts| parts);
656 let exponent = exponent.parse::<i64>().ok();
657 let (integer, fraction) = coefficient
658 .split_once('.')
659 .map_or((coefficient, ""), |parts| parts);
660 let digits = format!("{integer}{fraction}");
661 let significant = digits.trim_start_matches('0');
662 if significant.is_empty() {
663 return Some(0);
664 }
665 if negative {
666 return None;
667 }
668
669 let exponent = exponent?;
670 let scale = exponent.checked_sub(fraction.len() as i64)?;
671 let mut normalized = significant.to_owned();
672 if scale >= 0 {
673 let zero_count = usize::try_from(scale).ok()?;
674 if normalized.len().checked_add(zero_count)? > 20 {
675 return None;
676 }
677 normalized.extend(std::iter::repeat_n('0', zero_count));
678 } else {
679 let removed = usize::try_from(scale.unsigned_abs()).ok()?;
680 if removed > normalized.len() {
681 return None;
682 }
683 let retained = normalized.len() - removed;
684 if !normalized.as_bytes()[retained..]
685 .iter()
686 .all(|byte| *byte == b'0')
687 {
688 return None;
689 }
690 normalized.truncate(retained);
691 if normalized.is_empty() {
692 return Some(0);
693 }
694 }
695 normalized.parse().ok()
696}