tokio/io/util/
async_write_ext.rs

1use crate::io::util::flush::{flush, Flush};
2use crate::io::util::shutdown::{shutdown, Shutdown};
3use crate::io::util::write::{write, Write};
4use crate::io::util::write_all::{write_all, WriteAll};
5use crate::io::util::write_all_buf::{write_all_buf, WriteAllBuf};
6use crate::io::util::write_buf::{write_buf, WriteBuf};
7use crate::io::util::write_int::{WriteF32, WriteF32Le, WriteF64, WriteF64Le};
8use crate::io::util::write_int::{
9    WriteI128, WriteI128Le, WriteI16, WriteI16Le, WriteI32, WriteI32Le, WriteI64, WriteI64Le,
10    WriteI8,
11};
12use crate::io::util::write_int::{
13    WriteU128, WriteU128Le, WriteU16, WriteU16Le, WriteU32, WriteU32Le, WriteU64, WriteU64Le,
14    WriteU8,
15};
16use crate::io::util::write_vectored::{write_vectored, WriteVectored};
17use crate::io::AsyncWrite;
18use std::io::IoSlice;
19
20use bytes::Buf;
21
22cfg_io_util! {
23    /// Defines numeric writer.
24    macro_rules! write_impl {
25        (
26            $(
27                $(#[$outer:meta])*
28                fn $name:ident(&mut self, n: $ty:ty) -> $($fut:ident)*;
29            )*
30        ) => {
31            $(
32                $(#[$outer])*
33                fn $name(&mut self, n: $ty) -> $($fut)*<&mut Self> where Self: Unpin {
34                    $($fut)*::new(self, n)
35                }
36            )*
37        }
38    }
39
40    /// Writes bytes to a sink.
41    ///
42    /// Implemented as an extension trait, adding utility methods to all
43    /// [`AsyncWrite`] types. Callers will tend to import this trait instead of
44    /// [`AsyncWrite`].
45    ///
46    /// ```no_run
47    /// # #[cfg(not(target_family = "wasm"))]
48    /// # {
49    /// use tokio::io::{self, AsyncWriteExt};
50    /// use tokio::fs::File;
51    ///
52    /// #[tokio::main]
53    /// async fn main() -> io::Result<()> {
54    ///     let data = b"some bytes";
55    ///
56    ///     let mut pos = 0;
57    ///     let mut buffer = File::create("foo.txt").await?;
58    ///
59    ///     while pos < data.len() {
60    ///         let bytes_written = buffer.write(&data[pos..]).await?;
61    ///         pos += bytes_written;
62    ///     }
63    ///
64    ///     Ok(())
65    /// }
66    /// # }
67    /// ```
68    ///
69    /// See [module][crate::io] documentation for more details.
70    ///
71    /// [`AsyncWrite`]: AsyncWrite
72    pub trait AsyncWriteExt: AsyncWrite {
73        /// Writes a buffer into this writer, returning how many bytes were
74        /// written.
75        ///
76        /// Equivalent to:
77        ///
78        /// ```ignore
79        /// async fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
80        /// ```
81        ///
82        /// This function will attempt to write the entire contents of `buf`, but
83        /// the entire write may not succeed, or the write may also generate an
84        /// error. A call to `write` represents *at most one* attempt to write to
85        /// any wrapped object.
86        ///
87        /// # Return
88        ///
89        /// If the return value is `Ok(n)` then it must be guaranteed that `n <=
90        /// buf.len()`. A return value of `0` typically means that the
91        /// underlying object is no longer able to accept bytes and will likely
92        /// not be able to in the future as well, or that the buffer provided is
93        /// empty.
94        ///
95        /// # Errors
96        ///
97        /// Each call to `write` may generate an I/O error indicating that the
98        /// operation could not be completed. If an error is returned then no bytes
99        /// in the buffer were written to this writer.
100        ///
101        /// It is **not** considered an error if the entire buffer could not be
102        /// written to this writer.
103        ///
104        /// # Cancel safety
105        ///
106        /// This method is cancellation safe in the sense that if it is used as
107        /// the event in a [`tokio::select!`](crate::select) statement and some
108        /// other branch completes first, then it is guaranteed that no data was
109        /// written to this `AsyncWrite`.
110        ///
111        /// # Examples
112        ///
113        /// ```no_run
114        /// # #[cfg(not(target_family = "wasm"))]
115        /// # {
116        /// use tokio::io::{self, AsyncWriteExt};
117        /// use tokio::fs::File;
118        ///
119        /// #[tokio::main]
120        /// async fn main() -> io::Result<()> {
121        ///     let mut file = File::create("foo.txt").await?;
122        ///
123        ///     // Writes some prefix of the byte string, not necessarily all of it.
124        ///     file.write(b"some bytes").await?;
125        ///     file.flush().await?;
126        ///     Ok(())
127        /// }
128        /// # }
129        /// ```
130        fn write<'a>(&'a mut self, src: &'a [u8]) -> Write<'a, Self>
131        where
132            Self: Unpin,
133        {
134            write(self, src)
135        }
136
137        /// Like [`write`], except that it writes from a slice of buffers.
138        ///
139        /// Equivalent to:
140        ///
141        /// ```ignore
142        /// async fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>;
143        /// ```
144        ///
145        /// See [`AsyncWrite::poll_write_vectored`] for more details.
146        ///
147        /// # Cancel safety
148        ///
149        /// This method is cancellation safe in the sense that if it is used as
150        /// the event in a [`tokio::select!`](crate::select) statement and some
151        /// other branch completes first, then it is guaranteed that no data was
152        /// written to this `AsyncWrite`.
153        ///
154        /// # Examples
155        ///
156        /// ```no_run
157        /// # #[cfg(not(target_family = "wasm"))]
158        /// # {
159        /// use tokio::io::{self, AsyncWriteExt};
160        /// use tokio::fs::File;
161        /// use std::io::IoSlice;
162        ///
163        /// #[tokio::main]
164        /// async fn main() -> io::Result<()> {
165        ///     let mut file = File::create("foo.txt").await?;
166        ///
167        ///     let bufs: &[_] = &[
168        ///         IoSlice::new(b"hello"),
169        ///         IoSlice::new(b" "),
170        ///         IoSlice::new(b"world"),
171        ///     ];
172        ///
173        ///     file.write_vectored(&bufs).await?;
174        ///     file.flush().await?;
175        ///
176        ///     Ok(())
177        /// }
178        /// # }
179        /// ```
180        ///
181        /// [`write`]: AsyncWriteExt::write
182        fn write_vectored<'a, 'b>(&'a mut self, bufs: &'a [IoSlice<'b>]) -> WriteVectored<'a, 'b, Self>
183        where
184            Self: Unpin,
185        {
186            write_vectored(self, bufs)
187        }
188
189        /// Writes a buffer into this writer, advancing the buffer's internal
190        /// cursor.
191        ///
192        /// Equivalent to:
193        ///
194        /// ```ignore
195        /// async fn write_buf<B: Buf>(&mut self, buf: &mut B) -> io::Result<usize>;
196        /// ```
197        ///
198        /// This function will attempt to write the entire contents of `buf`, but
199        /// the entire write may not succeed, or the write may also generate an
200        /// error. After the operation completes, the buffer's
201        /// internal cursor is advanced by the number of bytes written. A
202        /// subsequent call to `write_buf` using the **same** `buf` value will
203        /// resume from the point that the first call to `write_buf` completed.
204        /// A call to `write_buf` represents *at most one* attempt to write to any
205        /// wrapped object.
206        ///
207        /// # Return
208        ///
209        /// If the return value is `Ok(n)` then it must be guaranteed that `n <=
210        /// buf.len()`. A return value of `0` typically means that the
211        /// underlying object is no longer able to accept bytes and will likely
212        /// not be able to in the future as well, or that the buffer provided is
213        /// empty.
214        ///
215        /// # Errors
216        ///
217        /// Each call to `write` may generate an I/O error indicating that the
218        /// operation could not be completed. If an error is returned then no bytes
219        /// in the buffer were written to this writer.
220        ///
221        /// It is **not** considered an error if the entire buffer could not be
222        /// written to this writer.
223        ///
224        /// # Cancel safety
225        ///
226        /// This method is cancellation safe in the sense that if it is used as
227        /// the event in a [`tokio::select!`](crate::select) statement and some
228        /// other branch completes first, then it is guaranteed that no data was
229        /// written to this `AsyncWrite`.
230        ///
231        /// # Examples
232        ///
233        /// [`File`] implements [`AsyncWrite`] and [`Cursor`]`<&[u8]>` implements [`Buf`]:
234        ///
235        /// [`File`]: crate::fs::File
236        /// [`Buf`]: bytes::Buf
237        /// [`Cursor`]: std::io::Cursor
238        ///
239        /// ```no_run
240        /// # #[cfg(not(target_family = "wasm"))]
241        /// # {
242        /// use tokio::io::{self, AsyncWriteExt};
243        /// use tokio::fs::File;
244        ///
245        /// use bytes::Buf;
246        /// use std::io::Cursor;
247        ///
248        /// #[tokio::main]
249        /// async fn main() -> io::Result<()> {
250        ///     let mut file = File::create("foo.txt").await?;
251        ///     let mut buffer = Cursor::new(b"data to write");
252        ///
253        ///     // Loop until the entire contents of the buffer are written to
254        ///     // the file.
255        ///     while buffer.has_remaining() {
256        ///         // Writes some prefix of the byte string, not necessarily
257        ///         // all of it.
258        ///         file.write_buf(&mut buffer).await?;
259        ///     }
260        ///     file.flush().await?;
261        ///
262        ///     Ok(())
263        /// }
264        /// # }
265        /// ```
266        fn write_buf<'a, B>(&'a mut self, src: &'a mut B) -> WriteBuf<'a, Self, B>
267        where
268            Self: Sized + Unpin,
269            B: Buf,
270        {
271            write_buf(self, src)
272        }
273
274        /// Attempts to write an entire buffer into this writer.
275        ///
276        /// Equivalent to:
277        ///
278        /// ```ignore
279        /// async fn write_all_buf(&mut self, buf: impl Buf) -> Result<(), io::Error> {
280        ///     while buf.has_remaining() {
281        ///         self.write_buf(&mut buf).await?;
282        ///     }
283        ///     Ok(())
284        /// }
285        /// ```
286        ///
287        /// This method will continuously call [`write`] until
288        /// [`buf.has_remaining()`](bytes::Buf::has_remaining) returns false. This method will not
289        /// return until the entire buffer has been successfully written or an error occurs. The
290        /// first error generated will be returned.
291        ///
292        /// The buffer is advanced after each chunk is successfully written. After failure,
293        /// `src.chunk()` will return the chunk that failed to write.
294        ///
295        /// # Cancel safety
296        ///
297        /// If `write_all_buf` is used as the event in a
298        /// [`tokio::select!`](crate::select) statement and some other branch
299        /// completes first, then the data in the provided buffer may have been
300        /// partially written. However, it is guaranteed that the provided
301        /// buffer has been [advanced] by the amount of bytes that have been
302        /// partially written.
303        ///
304        /// # Examples
305        ///
306        /// [`File`] implements [`AsyncWrite`] and [`Cursor`]`<&[u8]>` implements [`Buf`]:
307        ///
308        /// [`File`]: crate::fs::File
309        /// [`Buf`]: bytes::Buf
310        /// [`Cursor`]: std::io::Cursor
311        /// [advanced]: bytes::Buf::advance
312        ///
313        /// ```no_run
314        /// # #[cfg(not(target_family = "wasm"))]
315        /// # {
316        /// use tokio::io::{self, AsyncWriteExt};
317        /// use tokio::fs::File;
318        ///
319        /// use std::io::Cursor;
320        ///
321        /// #[tokio::main]
322        /// async fn main() -> io::Result<()> {
323        ///     let mut file = File::create("foo.txt").await?;
324        ///     let mut buffer = Cursor::new(b"data to write");
325        ///
326        ///     file.write_all_buf(&mut buffer).await?;
327        ///     file.flush().await?;
328        ///     Ok(())
329        /// }
330        /// # }
331        /// ```
332        ///
333        /// [`write`]: AsyncWriteExt::write
334        fn write_all_buf<'a, B>(&'a mut self, src: &'a mut B) -> WriteAllBuf<'a, Self, B>
335        where
336            Self: Sized + Unpin,
337            B: Buf,
338        {
339            write_all_buf(self, src)
340        }
341
342        /// Attempts to write an entire buffer into this writer.
343        ///
344        /// Equivalent to:
345        ///
346        /// ```ignore
347        /// async fn write_all(&mut self, buf: &[u8]) -> io::Result<()>;
348        /// ```
349        ///
350        /// This method will continuously call [`write`] until there is no more data
351        /// to be written. This method will not return until the entire buffer
352        /// has been successfully written or such an error occurs. The first
353        /// error generated from this method will be returned.
354        ///
355        /// # Cancel safety
356        ///
357        /// This method is not cancellation safe. If it is used as the event
358        /// in a [`tokio::select!`](crate::select) statement and some other
359        /// branch completes first, then the provided buffer may have been
360        /// partially written, but future calls to `write_all` will start over
361        /// from the beginning of the buffer.
362        ///
363        /// # Errors
364        ///
365        /// This function will return the first error that [`write`] returns.
366        ///
367        /// # Examples
368        ///
369        /// ```no_run
370        /// # #[cfg(not(target_family = "wasm"))]
371        /// # {
372        /// use tokio::io::{self, AsyncWriteExt};
373        /// use tokio::fs::File;
374        ///
375        /// #[tokio::main]
376        /// async fn main() -> io::Result<()> {
377        ///     let mut file = File::create("foo.txt").await?;
378        ///
379        ///     file.write_all(b"some bytes").await?;
380        ///     file.flush().await?;
381        ///     Ok(())
382        /// }
383        /// # }
384        /// ```
385        ///
386        /// [`write`]: AsyncWriteExt::write
387        fn write_all<'a>(&'a mut self, src: &'a [u8]) -> WriteAll<'a, Self>
388        where
389            Self: Unpin,
390        {
391            write_all(self, src)
392        }
393
394        write_impl! {
395            /// Writes an unsigned 8-bit integer to the underlying writer.
396            ///
397            /// Equivalent to:
398            ///
399            /// ```ignore
400            /// async fn write_u8(&mut self, n: u8) -> io::Result<()>;
401            /// ```
402            ///
403            /// It is recommended to use a buffered writer to avoid excessive
404            /// syscalls.
405            ///
406            /// # Errors
407            ///
408            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
409            ///
410            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
411            ///
412            /// # Examples
413            ///
414            /// Write unsigned 8 bit integers to a `AsyncWrite`:
415            ///
416            /// ```rust
417            /// use tokio::io::{self, AsyncWriteExt};
418            ///
419            /// # #[tokio::main(flavor = "current_thread")]
420            /// # async fn main() -> io::Result<()> {
421            /// let mut writer = Vec::new();
422            ///
423            /// writer.write_u8(2).await?;
424            /// writer.write_u8(5).await?;
425            ///
426            /// assert_eq!(writer, b"\x02\x05");
427            /// Ok(())
428            /// # }
429            /// ```
430            fn write_u8(&mut self, n: u8) -> WriteU8;
431
432            /// Writes a signed 8-bit integer to the underlying writer.
433            ///
434            /// Equivalent to:
435            ///
436            /// ```ignore
437            /// async fn write_i8(&mut self, n: i8) -> io::Result<()>;
438            /// ```
439            ///
440            /// It is recommended to use a buffered writer to avoid excessive
441            /// syscalls.
442            ///
443            /// # Errors
444            ///
445            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
446            ///
447            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
448            ///
449            /// # Examples
450            ///
451            /// Write signed 8 bit integers to a `AsyncWrite`:
452            ///
453            /// ```rust
454            /// use tokio::io::{self, AsyncWriteExt};
455            ///
456            /// # #[tokio::main(flavor = "current_thread")]
457            /// # async fn main() -> io::Result<()> {
458            /// let mut writer = Vec::new();
459            ///
460            /// writer.write_i8(-2).await?;
461            /// writer.write_i8(126).await?;
462            ///
463            /// assert_eq!(writer, b"\xFE\x7E");
464            /// Ok(())
465            /// # }
466            /// ```
467            fn write_i8(&mut self, n: i8) -> WriteI8;
468
469            /// Writes an unsigned 16-bit integer in big-endian order to the
470            /// underlying writer.
471            ///
472            /// Equivalent to:
473            ///
474            /// ```ignore
475            /// async fn write_u16(&mut self, n: u16) -> io::Result<()>;
476            /// ```
477            ///
478            /// It is recommended to use a buffered writer to avoid excessive
479            /// syscalls.
480            ///
481            /// # Errors
482            ///
483            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
484            ///
485            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
486            ///
487            /// # Examples
488            ///
489            /// Write unsigned 16-bit integers to a `AsyncWrite`:
490            ///
491            /// ```rust
492            /// use tokio::io::{self, AsyncWriteExt};
493            ///
494            /// # #[tokio::main(flavor = "current_thread")]
495            /// # async fn main() -> io::Result<()> {
496            /// let mut writer = Vec::new();
497            ///
498            /// writer.write_u16(517).await?;
499            /// writer.write_u16(768).await?;
500            ///
501            /// assert_eq!(writer, b"\x02\x05\x03\x00");
502            /// Ok(())
503            /// # }
504            /// ```
505            fn write_u16(&mut self, n: u16) -> WriteU16;
506
507            /// Writes a signed 16-bit integer in big-endian order to the
508            /// underlying writer.
509            ///
510            /// Equivalent to:
511            ///
512            /// ```ignore
513            /// async fn write_i16(&mut self, n: i16) -> io::Result<()>;
514            /// ```
515            ///
516            /// It is recommended to use a buffered writer to avoid excessive
517            /// syscalls.
518            ///
519            /// # Errors
520            ///
521            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
522            ///
523            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
524            ///
525            /// # Examples
526            ///
527            /// Write signed 16-bit integers to a `AsyncWrite`:
528            ///
529            /// ```rust
530            /// use tokio::io::{self, AsyncWriteExt};
531            ///
532            /// # #[tokio::main(flavor = "current_thread")]
533            /// # async fn main() -> io::Result<()> {
534            /// let mut writer = Vec::new();
535            ///
536            /// writer.write_i16(193).await?;
537            /// writer.write_i16(-132).await?;
538            ///
539            /// assert_eq!(writer, b"\x00\xc1\xff\x7c");
540            /// Ok(())
541            /// # }
542            /// ```
543            fn write_i16(&mut self, n: i16) -> WriteI16;
544
545            /// Writes an unsigned 32-bit integer in big-endian order to the
546            /// underlying writer.
547            ///
548            /// Equivalent to:
549            ///
550            /// ```ignore
551            /// async fn write_u32(&mut self, n: u32) -> io::Result<()>;
552            /// ```
553            ///
554            /// It is recommended to use a buffered writer to avoid excessive
555            /// syscalls.
556            ///
557            /// # Errors
558            ///
559            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
560            ///
561            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
562            ///
563            /// # Examples
564            ///
565            /// Write unsigned 32-bit integers to a `AsyncWrite`:
566            ///
567            /// ```rust
568            /// use tokio::io::{self, AsyncWriteExt};
569            ///
570            /// # #[tokio::main(flavor = "current_thread")]
571            /// # async fn main() -> io::Result<()> {
572            /// let mut writer = Vec::new();
573            ///
574            /// writer.write_u32(267).await?;
575            /// writer.write_u32(1205419366).await?;
576            ///
577            /// assert_eq!(writer, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66");
578            /// Ok(())
579            /// # }
580            /// ```
581            fn write_u32(&mut self, n: u32) -> WriteU32;
582
583            /// Writes a signed 32-bit integer in big-endian order to the
584            /// underlying writer.
585            ///
586            /// Equivalent to:
587            ///
588            /// ```ignore
589            /// async fn write_i32(&mut self, n: i32) -> io::Result<()>;
590            /// ```
591            ///
592            /// It is recommended to use a buffered writer to avoid excessive
593            /// syscalls.
594            ///
595            /// # Errors
596            ///
597            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
598            ///
599            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
600            ///
601            /// # Examples
602            ///
603            /// Write signed 32-bit integers to a `AsyncWrite`:
604            ///
605            /// ```rust
606            /// use tokio::io::{self, AsyncWriteExt};
607            ///
608            /// # #[tokio::main(flavor = "current_thread")]
609            /// # async fn main() -> io::Result<()> {
610            /// let mut writer = Vec::new();
611            ///
612            /// writer.write_i32(267).await?;
613            /// writer.write_i32(1205419366).await?;
614            ///
615            /// assert_eq!(writer, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66");
616            /// Ok(())
617            /// # }
618            /// ```
619            fn write_i32(&mut self, n: i32) -> WriteI32;
620
621            /// Writes an unsigned 64-bit integer in big-endian order to the
622            /// underlying writer.
623            ///
624            /// Equivalent to:
625            ///
626            /// ```ignore
627            /// async fn write_u64(&mut self, n: u64) -> io::Result<()>;
628            /// ```
629            ///
630            /// It is recommended to use a buffered writer to avoid excessive
631            /// syscalls.
632            ///
633            /// # Errors
634            ///
635            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
636            ///
637            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
638            ///
639            /// # Examples
640            ///
641            /// Write unsigned 64-bit integers to a `AsyncWrite`:
642            ///
643            /// ```rust
644            /// use tokio::io::{self, AsyncWriteExt};
645            ///
646            /// # #[tokio::main(flavor = "current_thread")]
647            /// # async fn main() -> io::Result<()> {
648            /// let mut writer = Vec::new();
649            ///
650            /// writer.write_u64(918733457491587).await?;
651            /// writer.write_u64(143).await?;
652            ///
653            /// assert_eq!(writer, b"\x00\x03\x43\x95\x4d\x60\x86\x83\x00\x00\x00\x00\x00\x00\x00\x8f");
654            /// Ok(())
655            /// # }
656            /// ```
657            fn write_u64(&mut self, n: u64) -> WriteU64;
658
659            /// Writes an signed 64-bit integer in big-endian order to the
660            /// underlying writer.
661            ///
662            /// Equivalent to:
663            ///
664            /// ```ignore
665            /// async fn write_i64(&mut self, n: i64) -> io::Result<()>;
666            /// ```
667            ///
668            /// It is recommended to use a buffered writer to avoid excessive
669            /// syscalls.
670            ///
671            /// # Errors
672            ///
673            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
674            ///
675            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
676            ///
677            /// # Examples
678            ///
679            /// Write signed 64-bit integers to a `AsyncWrite`:
680            ///
681            /// ```rust
682            /// use tokio::io::{self, AsyncWriteExt};
683            ///
684            /// # #[tokio::main(flavor = "current_thread")]
685            /// # async fn main() -> io::Result<()> {
686            /// let mut writer = Vec::new();
687            ///
688            /// writer.write_i64(i64::MIN).await?;
689            /// writer.write_i64(i64::MAX).await?;
690            ///
691            /// assert_eq!(writer, b"\x80\x00\x00\x00\x00\x00\x00\x00\x7f\xff\xff\xff\xff\xff\xff\xff");
692            /// Ok(())
693            /// # }
694            /// ```
695            fn write_i64(&mut self, n: i64) -> WriteI64;
696
697            /// Writes an unsigned 128-bit integer in big-endian order to the
698            /// underlying writer.
699            ///
700            /// Equivalent to:
701            ///
702            /// ```ignore
703            /// async fn write_u128(&mut self, n: u128) -> io::Result<()>;
704            /// ```
705            ///
706            /// It is recommended to use a buffered writer to avoid excessive
707            /// syscalls.
708            ///
709            /// # Errors
710            ///
711            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
712            ///
713            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
714            ///
715            /// # Examples
716            ///
717            /// Write unsigned 128-bit integers to a `AsyncWrite`:
718            ///
719            /// ```rust
720            /// use tokio::io::{self, AsyncWriteExt};
721            ///
722            /// # #[tokio::main(flavor = "current_thread")]
723            /// # async fn main() -> io::Result<()> {
724            /// let mut writer = Vec::new();
725            ///
726            /// writer.write_u128(16947640962301618749969007319746179).await?;
727            ///
728            /// assert_eq!(writer, vec![
729            ///     0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83,
730            ///     0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83
731            /// ]);
732            /// Ok(())
733            /// # }
734            /// ```
735            fn write_u128(&mut self, n: u128) -> WriteU128;
736
737            /// Writes an signed 128-bit integer in big-endian order to the
738            /// underlying writer.
739            ///
740            /// Equivalent to:
741            ///
742            /// ```ignore
743            /// async fn write_i128(&mut self, n: i128) -> io::Result<()>;
744            /// ```
745            ///
746            /// It is recommended to use a buffered writer to avoid excessive
747            /// syscalls.
748            ///
749            /// # Errors
750            ///
751            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
752            ///
753            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
754            ///
755            /// # Examples
756            ///
757            /// Write signed 128-bit integers to a `AsyncWrite`:
758            ///
759            /// ```rust
760            /// use tokio::io::{self, AsyncWriteExt};
761            ///
762            /// # #[tokio::main(flavor = "current_thread")]
763            /// # async fn main() -> io::Result<()> {
764            /// let mut writer = Vec::new();
765            ///
766            /// writer.write_i128(i128::MIN).await?;
767            ///
768            /// assert_eq!(writer, vec![
769            ///     0x80, 0, 0, 0, 0, 0, 0, 0,
770            ///     0, 0, 0, 0, 0, 0, 0, 0
771            /// ]);
772            /// Ok(())
773            /// # }
774            /// ```
775            fn write_i128(&mut self, n: i128) -> WriteI128;
776
777            /// Writes an 32-bit floating point type in big-endian order to the
778            /// underlying writer.
779            ///
780            /// Equivalent to:
781            ///
782            /// ```ignore
783            /// async fn write_f32(&mut self, n: f32) -> io::Result<()>;
784            /// ```
785            ///
786            /// It is recommended to use a buffered writer to avoid excessive
787            /// syscalls.
788            ///
789            /// # Errors
790            ///
791            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
792            ///
793            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
794            ///
795            /// # Examples
796            ///
797            /// Write 32-bit floating point type to a `AsyncWrite`:
798            ///
799            /// ```rust
800            /// use tokio::io::{self, AsyncWriteExt};
801            ///
802            /// # #[tokio::main(flavor = "current_thread")]
803            /// # async fn main() -> io::Result<()> {
804            /// let mut writer = Vec::new();
805            ///
806            /// writer.write_f32(f32::MIN).await?;
807            ///
808            /// assert_eq!(writer, vec![0xff, 0x7f, 0xff, 0xff]);
809            /// Ok(())
810            /// # }
811            /// ```
812            fn write_f32(&mut self, n: f32) -> WriteF32;
813
814            /// Writes an 64-bit floating point type in big-endian order to the
815            /// underlying writer.
816            ///
817            /// Equivalent to:
818            ///
819            /// ```ignore
820            /// async fn write_f64(&mut self, n: f64) -> io::Result<()>;
821            /// ```
822            ///
823            /// It is recommended to use a buffered writer to avoid excessive
824            /// syscalls.
825            ///
826            /// # Errors
827            ///
828            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
829            ///
830            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
831            ///
832            /// # Examples
833            ///
834            /// Write 64-bit floating point type to a `AsyncWrite`:
835            ///
836            /// ```rust
837            /// use tokio::io::{self, AsyncWriteExt};
838            ///
839            /// # #[tokio::main(flavor = "current_thread")]
840            /// # async fn main() -> io::Result<()> {
841            /// let mut writer = Vec::new();
842            ///
843            /// writer.write_f64(f64::MIN).await?;
844            ///
845            /// assert_eq!(writer, vec![
846            ///     0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
847            /// ]);
848            /// Ok(())
849            /// # }
850            /// ```
851            fn write_f64(&mut self, n: f64) -> WriteF64;
852
853            /// Writes an unsigned 16-bit integer in little-endian order to the
854            /// underlying writer.
855            ///
856            /// Equivalent to:
857            ///
858            /// ```ignore
859            /// async fn write_u16_le(&mut self, n: u16) -> io::Result<()>;
860            /// ```
861            ///
862            /// It is recommended to use a buffered writer to avoid excessive
863            /// syscalls.
864            ///
865            /// # Errors
866            ///
867            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
868            ///
869            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
870            ///
871            /// # Examples
872            ///
873            /// Write unsigned 16-bit integers to a `AsyncWrite`:
874            ///
875            /// ```rust
876            /// use tokio::io::{self, AsyncWriteExt};
877            ///
878            /// # #[tokio::main(flavor = "current_thread")]
879            /// # async fn main() -> io::Result<()> {
880            /// let mut writer = Vec::new();
881            ///
882            /// writer.write_u16_le(517).await?;
883            /// writer.write_u16_le(768).await?;
884            ///
885            /// assert_eq!(writer, b"\x05\x02\x00\x03");
886            /// Ok(())
887            /// # }
888            /// ```
889            fn write_u16_le(&mut self, n: u16) -> WriteU16Le;
890
891            /// Writes a signed 16-bit integer in little-endian order to the
892            /// underlying writer.
893            ///
894            /// Equivalent to:
895            ///
896            /// ```ignore
897            /// async fn write_i16_le(&mut self, n: i16) -> io::Result<()>;
898            /// ```
899            ///
900            /// It is recommended to use a buffered writer to avoid excessive
901            /// syscalls.
902            ///
903            /// # Errors
904            ///
905            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
906            ///
907            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
908            ///
909            /// # Examples
910            ///
911            /// Write signed 16-bit integers to a `AsyncWrite`:
912            ///
913            /// ```rust
914            /// use tokio::io::{self, AsyncWriteExt};
915            ///
916            /// # #[tokio::main(flavor = "current_thread")]
917            /// # async fn main() -> io::Result<()> {
918            /// let mut writer = Vec::new();
919            ///
920            /// writer.write_i16_le(193).await?;
921            /// writer.write_i16_le(-132).await?;
922            ///
923            /// assert_eq!(writer, b"\xc1\x00\x7c\xff");
924            /// Ok(())
925            /// # }
926            /// ```
927            fn write_i16_le(&mut self, n: i16) -> WriteI16Le;
928
929            /// Writes an unsigned 32-bit integer in little-endian order to the
930            /// underlying writer.
931            ///
932            /// Equivalent to:
933            ///
934            /// ```ignore
935            /// async fn write_u32_le(&mut self, n: u32) -> io::Result<()>;
936            /// ```
937            ///
938            /// It is recommended to use a buffered writer to avoid excessive
939            /// syscalls.
940            ///
941            /// # Errors
942            ///
943            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
944            ///
945            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
946            ///
947            /// # Examples
948            ///
949            /// Write unsigned 32-bit integers to a `AsyncWrite`:
950            ///
951            /// ```rust
952            /// use tokio::io::{self, AsyncWriteExt};
953            ///
954            /// # #[tokio::main(flavor = "current_thread")]
955            /// # async fn main() -> io::Result<()> {
956            /// let mut writer = Vec::new();
957            ///
958            /// writer.write_u32_le(267).await?;
959            /// writer.write_u32_le(1205419366).await?;
960            ///
961            /// assert_eq!(writer, b"\x0b\x01\x00\x00\x66\x3d\xd9\x47");
962            /// Ok(())
963            /// # }
964            /// ```
965            fn write_u32_le(&mut self, n: u32) -> WriteU32Le;
966
967            /// Writes a signed 32-bit integer in little-endian order to the
968            /// underlying writer.
969            ///
970            /// Equivalent to:
971            ///
972            /// ```ignore
973            /// async fn write_i32_le(&mut self, n: i32) -> io::Result<()>;
974            /// ```
975            ///
976            /// It is recommended to use a buffered writer to avoid excessive
977            /// syscalls.
978            ///
979            /// # Errors
980            ///
981            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
982            ///
983            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
984            ///
985            /// # Examples
986            ///
987            /// Write signed 32-bit integers to a `AsyncWrite`:
988            ///
989            /// ```rust
990            /// use tokio::io::{self, AsyncWriteExt};
991            ///
992            /// # #[tokio::main(flavor = "current_thread")]
993            /// # async fn main() -> io::Result<()> {
994            /// let mut writer = Vec::new();
995            ///
996            /// writer.write_i32_le(267).await?;
997            /// writer.write_i32_le(1205419366).await?;
998            ///
999            /// assert_eq!(writer, b"\x0b\x01\x00\x00\x66\x3d\xd9\x47");
1000            /// Ok(())
1001            /// # }
1002            /// ```
1003            fn write_i32_le(&mut self, n: i32) -> WriteI32Le;
1004
1005            /// Writes an unsigned 64-bit integer in little-endian order to the
1006            /// underlying writer.
1007            ///
1008            /// Equivalent to:
1009            ///
1010            /// ```ignore
1011            /// async fn write_u64_le(&mut self, n: u64) -> io::Result<()>;
1012            /// ```
1013            ///
1014            /// It is recommended to use a buffered writer to avoid excessive
1015            /// syscalls.
1016            ///
1017            /// # Errors
1018            ///
1019            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
1020            ///
1021            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
1022            ///
1023            /// # Examples
1024            ///
1025            /// Write unsigned 64-bit integers to a `AsyncWrite`:
1026            ///
1027            /// ```rust
1028            /// use tokio::io::{self, AsyncWriteExt};
1029            ///
1030            /// # #[tokio::main(flavor = "current_thread")]
1031            /// # async fn main() -> io::Result<()> {
1032            /// let mut writer = Vec::new();
1033            ///
1034            /// writer.write_u64_le(918733457491587).await?;
1035            /// writer.write_u64_le(143).await?;
1036            ///
1037            /// assert_eq!(writer, b"\x83\x86\x60\x4d\x95\x43\x03\x00\x8f\x00\x00\x00\x00\x00\x00\x00");
1038            /// Ok(())
1039            /// # }
1040            /// ```
1041            fn write_u64_le(&mut self, n: u64) -> WriteU64Le;
1042
1043            /// Writes an signed 64-bit integer in little-endian order to the
1044            /// underlying writer.
1045            ///
1046            /// Equivalent to:
1047            ///
1048            /// ```ignore
1049            /// async fn write_i64_le(&mut self, n: i64) -> io::Result<()>;
1050            /// ```
1051            ///
1052            /// It is recommended to use a buffered writer to avoid excessive
1053            /// syscalls.
1054            ///
1055            /// # Errors
1056            ///
1057            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
1058            ///
1059            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
1060            ///
1061            /// # Examples
1062            ///
1063            /// Write signed 64-bit integers to a `AsyncWrite`:
1064            ///
1065            /// ```rust
1066            /// use tokio::io::{self, AsyncWriteExt};
1067            ///
1068            /// # #[tokio::main(flavor = "current_thread")]
1069            /// # async fn main() -> io::Result<()> {
1070            /// let mut writer = Vec::new();
1071            ///
1072            /// writer.write_i64_le(i64::MIN).await?;
1073            /// writer.write_i64_le(i64::MAX).await?;
1074            ///
1075            /// assert_eq!(writer, b"\x00\x00\x00\x00\x00\x00\x00\x80\xff\xff\xff\xff\xff\xff\xff\x7f");
1076            /// Ok(())
1077            /// # }
1078            /// ```
1079            fn write_i64_le(&mut self, n: i64) -> WriteI64Le;
1080
1081            /// Writes an unsigned 128-bit integer in little-endian order to the
1082            /// underlying writer.
1083            ///
1084            /// Equivalent to:
1085            ///
1086            /// ```ignore
1087            /// async fn write_u128_le(&mut self, n: u128) -> io::Result<()>;
1088            /// ```
1089            ///
1090            /// It is recommended to use a buffered writer to avoid excessive
1091            /// syscalls.
1092            ///
1093            /// # Errors
1094            ///
1095            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
1096            ///
1097            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
1098            ///
1099            /// # Examples
1100            ///
1101            /// Write unsigned 128-bit integers to a `AsyncWrite`:
1102            ///
1103            /// ```rust
1104            /// use tokio::io::{self, AsyncWriteExt};
1105            ///
1106            /// # #[tokio::main(flavor = "current_thread")]
1107            /// # async fn main() -> io::Result<()> {
1108            /// let mut writer = Vec::new();
1109            ///
1110            /// writer.write_u128_le(16947640962301618749969007319746179).await?;
1111            ///
1112            /// assert_eq!(writer, vec![
1113            ///     0x83, 0x86, 0x60, 0x4d, 0x95, 0x43, 0x03, 0x00,
1114            ///     0x83, 0x86, 0x60, 0x4d, 0x95, 0x43, 0x03, 0x00,
1115            /// ]);
1116            /// Ok(())
1117            /// # }
1118            /// ```
1119            fn write_u128_le(&mut self, n: u128) -> WriteU128Le;
1120
1121            /// Writes an signed 128-bit integer in little-endian order to the
1122            /// underlying writer.
1123            ///
1124            /// Equivalent to:
1125            ///
1126            /// ```ignore
1127            /// async fn write_i128_le(&mut self, n: i128) -> io::Result<()>;
1128            /// ```
1129            ///
1130            /// It is recommended to use a buffered writer to avoid excessive
1131            /// syscalls.
1132            ///
1133            /// # Errors
1134            ///
1135            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
1136            ///
1137            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
1138            ///
1139            /// # Examples
1140            ///
1141            /// Write signed 128-bit integers to a `AsyncWrite`:
1142            ///
1143            /// ```rust
1144            /// use tokio::io::{self, AsyncWriteExt};
1145            ///
1146            /// # #[tokio::main(flavor = "current_thread")]
1147            /// # async fn main() -> io::Result<()> {
1148            /// let mut writer = Vec::new();
1149            ///
1150            /// writer.write_i128_le(i128::MIN).await?;
1151            ///
1152            /// assert_eq!(writer, vec![
1153            ///     0, 0, 0, 0, 0, 0, 0,
1154            ///     0, 0, 0, 0, 0, 0, 0, 0, 0x80
1155            /// ]);
1156            /// Ok(())
1157            /// # }
1158            /// ```
1159            fn write_i128_le(&mut self, n: i128) -> WriteI128Le;
1160
1161            /// Writes an 32-bit floating point type in little-endian order to the
1162            /// underlying writer.
1163            ///
1164            /// Equivalent to:
1165            ///
1166            /// ```ignore
1167            /// async fn write_f32_le(&mut self, n: f32) -> io::Result<()>;
1168            /// ```
1169            ///
1170            /// It is recommended to use a buffered writer to avoid excessive
1171            /// syscalls.
1172            ///
1173            /// # Errors
1174            ///
1175            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
1176            ///
1177            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
1178            ///
1179            /// # Examples
1180            ///
1181            /// Write 32-bit floating point type to a `AsyncWrite`:
1182            ///
1183            /// ```rust
1184            /// use tokio::io::{self, AsyncWriteExt};
1185            ///
1186            /// # #[tokio::main(flavor = "current_thread")]
1187            /// # async fn main() -> io::Result<()> {
1188            /// let mut writer = Vec::new();
1189            ///
1190            /// writer.write_f32_le(f32::MIN).await?;
1191            ///
1192            /// assert_eq!(writer, vec![0xff, 0xff, 0x7f, 0xff]);
1193            /// Ok(())
1194            /// # }
1195            /// ```
1196            fn write_f32_le(&mut self, n: f32) -> WriteF32Le;
1197
1198            /// Writes an 64-bit floating point type in little-endian order to the
1199            /// underlying writer.
1200            ///
1201            /// Equivalent to:
1202            ///
1203            /// ```ignore
1204            /// async fn write_f64_le(&mut self, n: f64) -> io::Result<()>;
1205            /// ```
1206            ///
1207            /// It is recommended to use a buffered writer to avoid excessive
1208            /// syscalls.
1209            ///
1210            /// # Errors
1211            ///
1212            /// This method returns the same errors as [`AsyncWriteExt::write_all`].
1213            ///
1214            /// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
1215            ///
1216            /// # Examples
1217            ///
1218            /// Write 64-bit floating point type to a `AsyncWrite`:
1219            ///
1220            /// ```rust
1221            /// use tokio::io::{self, AsyncWriteExt};
1222            ///
1223            /// # #[tokio::main(flavor = "current_thread")]
1224            /// # async fn main() -> io::Result<()> {
1225            /// let mut writer = Vec::new();
1226            ///
1227            /// writer.write_f64_le(f64::MIN).await?;
1228            ///
1229            /// assert_eq!(writer, vec![
1230            ///     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff
1231            /// ]);
1232            /// Ok(())
1233            /// # }
1234            /// ```
1235            fn write_f64_le(&mut self, n: f64) -> WriteF64Le;
1236        }
1237
1238        /// Flushes this output stream, ensuring that all intermediately buffered
1239        /// contents reach their destination.
1240        ///
1241        /// Equivalent to:
1242        ///
1243        /// ```ignore
1244        /// async fn flush(&mut self) -> io::Result<()>;
1245        /// ```
1246        ///
1247        /// # Errors
1248        ///
1249        /// It is considered an error if not all bytes could be written due to
1250        /// I/O errors or EOF being reached.
1251        ///
1252        /// # Cancel safety
1253        ///
1254        /// This method is cancel safe.
1255        ///
1256        /// If `flush` is used as the event in a [`tokio::select!`](crate::select)
1257        /// statement and some other branch completes first, then the data in the
1258        /// buffered data in this `AsyncWrite` may have been partially flushed.
1259        /// However, it is guaranteed that the buffer is advanced by the amount of
1260        /// bytes that have been partially flushed.
1261        ///
1262        /// # Examples
1263        ///
1264        /// ```no_run
1265        /// # #[cfg(not(target_family = "wasm"))]
1266        /// # {
1267        /// use tokio::io::{self, BufWriter, AsyncWriteExt};
1268        /// use tokio::fs::File;
1269        ///
1270        /// #[tokio::main]
1271        /// async fn main() -> io::Result<()> {
1272        ///     let f = File::create("foo.txt").await?;
1273        ///     let mut buffer = BufWriter::new(f);
1274        ///
1275        ///     buffer.write_all(b"some bytes").await?;
1276        ///     buffer.flush().await?;
1277        ///     Ok(())
1278        /// }
1279        /// # }
1280        /// ```
1281        fn flush(&mut self) -> Flush<'_, Self>
1282        where
1283            Self: Unpin,
1284        {
1285            flush(self)
1286        }
1287
1288        /// Shuts down the output stream, ensuring that the value can be dropped
1289        /// cleanly.
1290        ///
1291        /// Equivalent to:
1292        ///
1293        /// ```ignore
1294        /// async fn shutdown(&mut self) -> io::Result<()>;
1295        /// ```
1296        ///
1297        /// Similar to [`flush`], all intermediately buffered is written to the
1298        /// underlying stream. Once the operation completes, the caller should
1299        /// no longer attempt to write to the stream. For example, the
1300        /// `TcpStream` implementation will issue a `shutdown(Write)` sys call.
1301        ///
1302        /// [`flush`]: fn@crate::io::AsyncWriteExt::flush
1303        ///
1304        /// # Examples
1305        ///
1306        /// ```no_run
1307        /// # #[cfg(not(target_family = "wasm"))]
1308        /// # {
1309        /// use tokio::io::{self, BufWriter, AsyncWriteExt};
1310        /// use tokio::fs::File;
1311        ///
1312        /// #[tokio::main]
1313        /// async fn main() -> io::Result<()> {
1314        ///     let f = File::create("foo.txt").await?;
1315        ///     let mut buffer = BufWriter::new(f);
1316        ///
1317        ///     buffer.write_all(b"some bytes").await?;
1318        ///     buffer.shutdown().await?;
1319        ///     Ok(())
1320        /// }
1321        /// # }
1322        /// ```
1323        fn shutdown(&mut self) -> Shutdown<'_, Self>
1324        where
1325            Self: Unpin,
1326        {
1327            shutdown(self)
1328        }
1329    }
1330}
1331
1332impl<W: AsyncWrite + ?Sized> AsyncWriteExt for W {}