qubit-fs 0.3.2

Provider-neutral synchronous and asynchronous filesystem abstraction for Rust
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Concrete asynchronous file writer handle.

use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;
use std::io::Result as IoResult;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;

use qubit_io::AsyncOutput;

use crate::error::FsEffectState;
use crate::error::FsError;
use crate::error::FsErrorKind;
use crate::error::FsOperation;
use crate::error::RecoveryCleanupState;
use crate::facade::facade_core::FacadeCore;
use crate::facade::internal::ByteBudget;
use crate::facade::internal::FileSystemResource;
use crate::facade::internal::RecoveryCleanupGuard;
use crate::metadata::AchievedAtomicity;
use crate::metadata::AtomicityRequirement;
use crate::metadata::DurabilityRequirement;
use crate::metadata::OpenedFileInfo;
use crate::metadata::WriteOutcome;
use crate::spi::AsyncFileWriteSession;
use crate::spi::SpiFuture;
use crate::write::WriteAbortOutcome;
use crate::write::WriteFailure;
use crate::write::WriteFailureState;
use crate::write::WriterState;

/// Type-erased asynchronous provider write session associated with a file.
///
/// # Examples
///
/// This example uses an isolated in-memory provider fixture.
///
/// ```rust
/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
/// # use support::*;
/// # let (filesystem, _) = async_recording_spi::async_recording_file_system(Default::default());
/// # poll_support::ready(async {
/// use qubit_fs::Path;
/// use qubit_fs::write::WriteOptions;
/// use qubit_fs::write::WriterState;
/// use qubit_io::AsyncOutput;
///
/// let mut writer = filesystem.open_writer(&Path::parse("/report")?, WriteOptions::default()).await?;
/// writer.write_fully_async(b"bytes").await?;
/// writer.commit_async().await?;
/// assert_eq!(WriterState::Committed, writer.state());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// ```
pub struct AsyncFileWriter {
    /// Pinned provider write session.
    session: Pin<Box<dyn AsyncFileWriteSession>>,
    /// Stable identity and metadata captured at open time.
    info: OpenedFileInfo,
    /// Current publication lifecycle state.
    state: WriterState,
    /// Whether this session has ever had confirmed publication evidence.
    confirmed_publication: bool,
    /// Current state of explicit provider cleanup.
    cleanup_state: RecoveryCleanupState,
    /// Atomicity required by the caller.
    atomicity: AtomicityRequirement,
    /// Durability required by the caller.
    durability: DurabilityRequirement,
    /// Provider identifier attached to facade-generated errors.
    provider: Box<str>,
    /// Optional inclusive byte limit for this write session.
    write_budget: Option<ByteBudget>,
    /// Bytes accepted by the provider session so far.
    written_bytes: u64,
}

impl AsyncFileWriter {
    /// Wraps an already-open asynchronous provider write session.
    ///
    /// # Parameters
    /// - `session`: Runtime-neutral asynchronous write session.
    /// - `info`: File identity and optional open-time metadata snapshot.
    ///
    /// # Returns
    /// A concrete writer in [`WriterState::Open`].
    #[inline]
    #[must_use]
    pub(crate) fn new(
        info: OpenedFileInfo,
        session: Box<dyn AsyncFileWriteSession>,
        atomicity: AtomicityRequirement,
        durability: DurabilityRequirement,
        provider: &str,
        max_write_bytes: Option<u64>,
    ) -> Self {
        Self {
            session: Box::into_pin(session),
            info,
            state: WriterState::Open,
            confirmed_publication: false,
            cleanup_state: RecoveryCleanupState::Pending,
            atomicity,
            durability,
            provider: provider.into(),
            write_budget: max_write_bytes
                .map(|maximum| FacadeCore::byte_budget(FileSystemResource::WriteBytes, maximum)),
            written_bytes: 0,
        }
    }

    /// Returns the fixed identity and open-time metadata snapshot.
    ///
    /// # Returns
    /// Information captured when the writer was opened.
    #[inline]
    #[must_use]
    pub fn info(&self) -> &OpenedFileInfo {
        &self.info
    }

    /// Returns the current lifecycle state.
    ///
    /// # Returns
    /// Current writer state.
    #[inline]
    #[must_use]
    pub const fn state(&self) -> WriterState {
        self.state
    }

    /// Returns whether this writer session has confirmed publication at any
    /// time.
    ///
    /// # Returns
    /// `true` when a commit or abort outcome confirmed publication. `false`
    /// does not prove that publication did not occur.
    #[inline]
    #[must_use]
    pub const fn has_confirmed_publication(&self) -> bool {
        self.confirmed_publication
    }

    /// Returns the state of explicit provider cleanup for this session.
    ///
    /// # Returns
    /// The latest cleanup state, independently of publication history.
    #[inline]
    #[must_use]
    pub const fn cleanup_state(&self) -> RecoveryCleanupState {
        self.cleanup_state
    }

    /// Asynchronously publishes bytes accepted by this session.
    ///
    /// A definite failure retains the open session for retry or abort. An
    /// indeterminate failure retains the session and changes its observable
    /// state to [`WriterState::Indeterminate`]. Once the returned future has
    /// been polled, dropping it before completion also makes the writer
    /// indeterminate because publication may already have started. Dropping an
    /// unpolled future leaves the writer open. Only a failure in
    /// [`WriteFailureState::RetryableNotPublished`] leaves the writer open for
    /// another explicit commit attempt. [`WriteFailureState::NotPublished`]
    /// allows only a valid abort; it does not make commit retryable.
    ///
    /// # Returns
    /// A future resolving to the actual publication outcome.
    ///
    /// # Errors
    /// The future returns [`WriteFailure`] when the provider fails publication
    /// or violates the requested atomicity, durability, or byte-count
    /// contract. The failure state records what is known about publication.
    pub fn commit_async(&mut self) -> SpiFuture<'_, Result<WriteOutcome, WriteFailure>> {
        if self.state != WriterState::Open {
            let publication_state = if self.confirmed_publication {
                WriteFailureState::Published
            } else {
                self.state.publication_failure_state()
            };
            let error = self.invalid_state(
                FsOperation::CommitWriter,
                "writer cannot be committed in its current state",
            );
            return Box::pin(async move { Err(WriteFailure::new(error, publication_state)) });
        }
        Box::pin(async move {
            self.state = WriterState::Indeterminate;
            let result = self.session.as_mut().commit_async().await;
            match result {
                Ok(outcome) => {
                    self.confirmed_publication = true;
                    self.state = WriterState::Committed;
                    if self.atomicity == AtomicityRequirement::Required
                        && outcome.atomicity() != AchievedAtomicity::Atomic
                    {
                        self.state = WriterState::Published;
                        return Err(WriteFailure::new(
                            FsError::new(
                                FsErrorKind::ProviderContractViolation,
                                FsOperation::CommitWriter,
                                "provider reported non-atomic success for an atomic-required write",
                            )
                            .with_path(self.info.path().clone())
                            .with_provider(&self.provider)
                            .with_effect_state(FsEffectState::Applied),
                            WriteFailureState::Published,
                        ));
                    }
                    if self.durability == DurabilityRequirement::Required && !outcome.durable() {
                        self.state = WriterState::Published;
                        return Err(WriteFailure::new(
                            FsError::new(
                                FsErrorKind::ProviderContractViolation,
                                FsOperation::CommitWriter,
                                "provider reported non-durable success for a durability-required write",
                            )
                            .with_path(self.info.path().clone())
                            .with_provider(&self.provider)
                            .with_effect_state(FsEffectState::Applied),
                            WriteFailureState::Published,
                        ));
                    }
                    if let Some(bytes_written) = outcome.bytes_written()
                        && bytes_written != self.written_bytes
                    {
                        self.state = WriterState::Published;
                        return Err(WriteFailure::new(
                            FsError::new(
                                FsErrorKind::ProviderContractViolation,
                                FsOperation::CommitWriter,
                                "provider reported a byte count different from the bytes accepted by the writer",
                            )
                            .with_path(self.info.path().clone())
                            .with_provider(&self.provider)
                            .with_effect_state(FsEffectState::Applied),
                            WriteFailureState::Published,
                        ));
                    }
                    Ok(outcome)
                }
                Err(failure) => {
                    if failure.state() == WriteFailureState::Published {
                        self.confirmed_publication = true;
                    }
                    self.state = match failure.state() {
                        WriteFailureState::RetryableNotPublished => WriterState::Open,
                        WriteFailureState::NotPublished => WriterState::NotPublished,
                        WriteFailureState::Published => WriterState::Published,
                        WriteFailureState::Indeterminate => WriterState::Indeterminate,
                    };
                    let (error, state) = failure.into_parts();
                    Err(WriteFailure::new(
                        self.contextual_error(error, FsOperation::CommitWriter),
                        state,
                    ))
                }
            }
        })
    }

    /// Asynchronously aborts this session and its provider staging resources.
    ///
    /// Once polled, cancellation before completion leaves the writer
    /// indeterminate. A definite provider failure restores the state from
    /// which abort was started; an indeterminate provider failure does not.
    /// Automatic drop cancellation is disabled for an indeterminate writer.
    ///
    /// # Returns
    /// A future resolving to the provider-confirmed destination publication
    /// state after cleanup. Every `Ok` confirms cleanup;
    /// `Indeterminate` means only that destination publication is unknown.
    ///
    /// # Errors
    /// The future returns an [`FsError`] when provider cleanup fails. The error
    /// includes the operation context available from the facade.
    pub fn abort_async(&mut self) -> SpiFuture<'_, crate::error::FsResult<WriteAbortOutcome>> {
        if self.cleanup_state == RecoveryCleanupState::Completed
            || !matches!(
                self.state,
                WriterState::Open | WriterState::NotPublished | WriterState::Published | WriterState::Indeterminate
            )
        {
            let error = self.invalid_state(
                FsOperation::AbortWriter,
                "writer cannot be aborted in its current state",
            );
            return Box::pin(async move { Err(error) });
        }
        Box::pin(async move {
            let previous_state = self.state;
            self.state = WriterState::Indeterminate;
            let mut cleanup = RecoveryCleanupGuard::start(&mut self.cleanup_state);
            let result = self.session.as_mut().abort_async().await;
            cleanup.finish(result.is_ok());
            drop(cleanup);
            match result {
                Ok(outcome) => {
                    if outcome == WriteAbortOutcome::Published {
                        self.confirmed_publication = true;
                    }
                    self.state = match outcome {
                        WriteAbortOutcome::NotPublished => WriterState::Aborted,
                        WriteAbortOutcome::Published => WriterState::Published,
                        WriteAbortOutcome::Indeterminate => WriterState::Indeterminate,
                    };
                    Ok(outcome)
                }
                Err(error) => {
                    if !error.has_indeterminate_effect() {
                        self.state = previous_state;
                    }
                    Err(self.contextual_error(error, FsOperation::AbortWriter))
                }
            }
        })
    }

    /// Returns the bytes accepted by the underlying write session.
    #[inline]
    #[must_use]
    pub(crate) const fn written_bytes(&self) -> u64 {
        self.written_bytes
    }

    /// Records that cancellation interrupted an operation using this writer.
    #[inline]
    pub(crate) fn mark_indeterminate(&mut self) {
        self.state = WriterState::Indeterminate;
    }

    /// Builds a stable invalid-state error.
    /// # Parameters
    /// - `operation`: Filesystem operation associated with the error.
    /// - `message`: Stable description included in the invalid-state error.
    fn invalid_state(&self, operation: FsOperation, message: &str) -> FsError {
        FsError::new(FsErrorKind::InvalidState, operation, message)
            .with_path(self.info.path().clone())
            .with_provider(&self.provider)
    }

    /// Builds a byte-transfer error after lifecycle completion.
    fn closed_io_error(&self) -> IoError {
        IoError::new(
            IoErrorKind::BrokenPipe,
            self.invalid_state(FsOperation::Write, "writer no longer accepts bytes"),
        )
    }

    /// Checks whether a provider write can fit in the session budget.
    /// # Parameters
    /// - `count`: Byte count checked against or added to the session budget.
    fn check_write_limit(&self, count: usize) -> IoResult<u64> {
        let count = FacadeCore::quantity_from_usize(count, FsOperation::Write, self.info.path(), &self.provider)
            .map_err(FsError::into_io_error)?;
        if let Some(budget) = &self.write_budget
            && let Err(error) = budget.check_available(count)
        {
            return Err(FacadeCore::budget_error(
                error,
                FsOperation::Write,
                self.info.path(),
                &self.provider,
                "write session exceeds the provider byte limit",
            )
            .into_io_error());
        }
        Ok(count)
    }

    /// Records bytes accepted by the provider in the public `u64` accounting
    /// domain.
    ///
    /// Returns an I/O error when the native byte count or accumulated total
    /// cannot be represented by the filesystem API's `u64` byte counters.
    /// # Parameters
    /// - `count`: Byte count checked against or added to the session budget.
    fn record_written_bytes(&mut self, count: usize) -> IoResult<()> {
        let count = FacadeCore::quantity_from_usize(count, FsOperation::Write, self.info.path(), &self.provider)
            .map_err(FsError::into_io_error)?;
        if let Some(error) = self
            .write_budget
            .as_mut()
            .and_then(|budget| budget.try_consume(count).err())
        {
            return Err(FacadeCore::budget_error(
                error,
                FsOperation::Write,
                self.info.path(),
                &self.provider,
                "write session exceeds the provider byte limit",
            )
            .into_io_error());
        }
        self.written_bytes = self
            .written_bytes
            .checked_add(count)
            .ok_or_else(|| self.byte_count_error())?;
        Ok(())
    }

    /// Builds the error used when native byte accounting exceeds the public
    /// filesystem API's `u64` reporting range.
    fn byte_count_error(&self) -> IoError {
        FsError::new(
            FsErrorKind::ResourceLimitExceeded,
            FsOperation::Write,
            "write byte count exceeds the filesystem API reporting range",
        )
        .with_path(self.info.path().clone())
        .with_provider(&self.provider)
        .into_io_error()
    }

    /// Adds only missing facade context to a provider lifecycle error.
    /// # Parameters
    /// - `error`: Failure whose trusted filesystem context is being restored.
    /// - `operation`: Filesystem operation associated with the error.
    fn contextual_error(&self, error: FsError, operation: FsOperation) -> FsError {
        error
            .with_operation(operation)
            .with_missing_context(self.info.path(), None, &self.provider)
    }
}

impl AsyncOutput for AsyncFileWriter {
    /// The byte unit accepted by this writer.
    type Item = u8;

    /// Reports whether the provider session buffers output before flushing.
    #[inline]
    fn is_buffered(&self) -> bool {
        self.session.is_buffered()
    }

    /// Polls a provider write while tracking accepted bytes and uncertainty.
    ///
    /// # Safety
    /// `index` and `count` must identify a valid range within `input`.
    /// # Parameters
    /// - `cx`: Task context used to poll the provider session.
    /// - `input`: Input bytes containing the requested range.
    /// - `index`: Starting offset of the requested input range.
    /// - `count`: Maximum number of bytes requested from the provider.
    unsafe fn poll_write_unchecked(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        input: &[u8],
        index: usize,
        count: usize,
    ) -> Poll<IoResult<usize>> {
        let this = self.get_mut();
        if count == 0 {
            return Poll::Ready(Ok(0));
        }
        if this.state != WriterState::Open {
            return Poll::Ready(Err(this.closed_io_error()));
        }
        if let Err(error) = this.check_write_limit(count) {
            return Poll::Ready(Err(error));
        }
        // SAFETY: The caller guarantees the same range contract required by
        // the wrapped asynchronous output session.
        match unsafe { this.session.as_mut().poll_write_unchecked(cx, input, index, count) } {
            Poll::Ready(Ok(written)) => {
                if written > count {
                    this.state = WriterState::Indeterminate;
                    return Poll::Ready(Err(FsError::new(
                        FsErrorKind::ProviderContractViolation,
                        FsOperation::Write,
                        "provider reported accepting more bytes than requested",
                    )
                    .with_effect_state(FsEffectState::Indeterminate)
                    .with_path(this.info.path().clone())
                    .with_provider(&this.provider)
                    .into_io_error()));
                }
                if let Err(error) = this.record_written_bytes(written) {
                    this.state = WriterState::Indeterminate;
                    return Poll::Ready(Err(error));
                }
                if count > 0 && written == 0 && this.written_bytes > 0 {
                    this.state = WriterState::Indeterminate;
                }
                Poll::Ready(Ok(written))
            }
            Poll::Ready(Err(error)) => {
                this.state = WriterState::Indeterminate;
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }

    /// Polls the provider flush and marks the writer indeterminate on failure.
    /// # Parameters
    /// - `cx`: Task context used to poll the provider session.
    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        let this = self.get_mut();
        if this.state != WriterState::Open {
            return Poll::Ready(Err(this.closed_io_error()));
        }
        match this.session.as_mut().poll_flush(cx) {
            Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
            Poll::Ready(Err(error)) => {
                this.state = WriterState::Indeterminate;
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Debug for AsyncFileWriter {
    /// Formats lifecycle facts without exposing the provider session.
    /// # Parameters
    /// - `formatter`: Formatter receiving the diagnostic representation.
    #[inline]
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter
            .debug_struct("AsyncFileWriter")
            .field("info", &self.info)
            .field("state", &self.state)
            .finish_non_exhaustive()
    }
}

impl Drop for AsyncFileWriter {
    /// Requests provider cancellation when this writer still owns live work.
    fn drop(&mut self) {
        if self.cleanup_state != RecoveryCleanupState::Completed
            && matches!(
                self.state,
                WriterState::Open | WriterState::NotPublished | WriterState::Published
            )
        {
            self.session.as_mut().cancel_on_drop();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::pin::Pin;
    use std::task::Context;
    use std::task::Poll;
    use std::task::Waker;

    use qubit_io::AsyncOutput;

    use super::AsyncFileWriter;
    use crate::error::FsResult;
    use crate::metadata::AchievedAtomicity;
    use crate::metadata::AtomicityRequirement;
    use crate::metadata::DurabilityRequirement;
    use crate::metadata::FileSystemId;
    use crate::metadata::OpenedFileInfo;
    use crate::metadata::PublicationMethod;
    use crate::metadata::WriteOutcome;
    use crate::path::Path;
    use crate::spi::AsyncFileWriteSession;
    use crate::spi::SpiFuture;
    use crate::write::WriteAbortOutcome;
    use crate::write::WriteFailure;

    struct Session;

    impl AsyncOutput for Session {
        type Item = u8;

        fn is_buffered(&self) -> bool {
            false
        }

        unsafe fn poll_write_unchecked(
            self: Pin<&mut Self>,
            _: &mut Context<'_>,
            _: &[u8],
            _: usize,
            count: usize,
        ) -> Poll<std::io::Result<usize>> {
            Poll::Ready(Ok(count))
        }

        fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Poll::Ready(Ok(()))
        }
    }

    impl AsyncFileWriteSession for Session {
        fn commit_async<'a>(self: Pin<&'a mut Self>) -> SpiFuture<'a, Result<WriteOutcome, WriteFailure>> {
            Box::pin(async {
                Ok(WriteOutcome::new(
                    AchievedAtomicity::Atomic,
                    PublicationMethod::AtomicRename,
                ))
            })
        }

        fn abort_async<'a>(self: Pin<&'a mut Self>) -> SpiFuture<'a, FsResult<WriteAbortOutcome>> {
            Box::pin(async { Ok(WriteAbortOutcome::NotPublished) })
        }
    }

    #[test]
    fn test_zero_length_write_preserves_bytes_after_nonempty_write() {
        let info = OpenedFileInfo::new(
            FileSystemId::new("async-writer-test").unwrap(),
            Path::parse("/zero-write").unwrap(),
        );
        let mut writer = AsyncFileWriter::new(
            info,
            Box::new(Session),
            AtomicityRequirement::default(),
            DurabilityRequirement::default(),
            "async-writer-test",
            None,
        );
        let mut cx = Context::from_waker(Waker::noop());
        assert!(matches!(
            unsafe { Pin::new(&mut writer).poll_write_unchecked(&mut cx, b"x", 0, 1) },
            Poll::Ready(Ok(1))
        ));
        assert_eq!(1, writer.written_bytes());

        let written_bytes = writer.written_bytes();
        assert!(matches!(
            unsafe { Pin::new(&mut writer).poll_write_unchecked(&mut cx, b"", 0, 0) },
            Poll::Ready(Ok(0))
        ));
        assert_eq!(written_bytes, writer.written_bytes());
    }
}