Trait bevy::asset::AsyncReadExt

pub trait AsyncReadExt: AsyncRead {
    // Provided methods
    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self> 
       where Self: Unpin { ... }
    fn read_vectored<'a>(
        &'a mut self,
        bufs: &'a mut [IoSliceMut<'a>]
    ) -> ReadVectoredFuture<'a, Self> 
       where Self: Unpin { ... }
    fn read_to_end<'a>(
        &'a mut self,
        buf: &'a mut Vec<u8>
    ) -> ReadToEndFuture<'a, Self> 
       where Self: Unpin { ... }
    fn read_to_string<'a>(
        &'a mut self,
        buf: &'a mut String
    ) -> ReadToStringFuture<'a, Self> 
       where Self: Unpin { ... }
    fn read_exact<'a>(
        &'a mut self,
        buf: &'a mut [u8]
    ) -> ReadExactFuture<'a, Self> 
       where Self: Unpin { ... }
    fn take(self, limit: u64) -> Take<Self>
       where Self: Sized { ... }
    fn bytes(self) -> Bytes<Self>
       where Self: Sized { ... }
    fn chain<R>(self, next: R) -> Chain<Self, R>
       where R: AsyncRead,
             Self: Sized { ... }
    fn boxed_reader<'a>(self) -> Pin<Box<dyn AsyncRead + Send + 'a>>
       where Self: Sized + Send + 'a { ... }
}
Expand description

Extension trait for AsyncRead.

Provided Methods§

fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>
where Self: Unpin,

Reads some bytes from the byte stream.

On success, returns the total number of bytes read.

If the return value is Ok(n), then it must be guaranteed that 0 <= n <= buf.len(). A nonzero n value indicates that the buffer has been filled with n bytes of data. If n is 0, then it can indicate one of two scenarios:

  1. This reader has reached its “end of file” and will likely no longer be able to produce bytes. Note that this does not mean that the reader will always no longer be able to produce bytes.
  2. The buffer specified was 0 bytes in length.
§Examples
use futures_lite::io::{AsyncReadExt, BufReader};

let input: &[u8] = b"hello";
let mut reader = BufReader::new(input);

let mut buf = vec![0; 1024];
let n = reader.read(&mut buf).await?;

fn read_vectored<'a>( &'a mut self, bufs: &'a mut [IoSliceMut<'a>] ) -> ReadVectoredFuture<'a, Self>
where Self: Unpin,

Like read(), except it reads into a slice of buffers.

Data is copied to fill each buffer in order, with the final buffer possibly being only partially filled. This method must behave same as a single call to read() with the buffers concatenated would.

fn read_to_end<'a>( &'a mut self, buf: &'a mut Vec<u8> ) -> ReadToEndFuture<'a, Self>
where Self: Unpin,

Reads the entire contents and appends them to a Vec.

On success, returns the total number of bytes read.

§Examples
use futures_lite::io::{AsyncReadExt, Cursor};

let mut reader = Cursor::new(vec![1, 2, 3]);
let mut contents = Vec::new();

let n = reader.read_to_end(&mut contents).await?;
assert_eq!(n, 3);
assert_eq!(contents, [1, 2, 3]);
Examples found in repository?
examples/asset/custom_asset.rs (line 43)
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
    async fn load<'a>(
        &'a self,
        reader: &'a mut Reader<'_>,
        _settings: &'a (),
        _load_context: &'a mut LoadContext<'_>,
    ) -> Result<Self::Asset, Self::Error> {
        let mut bytes = Vec::new();
        reader.read_to_end(&mut bytes).await?;
        let custom_asset = ron::de::from_bytes::<CustomAsset>(&bytes)?;
        Ok(custom_asset)
    }

    fn extensions(&self) -> &[&str] {
        &["custom"]
    }
}

#[derive(Asset, TypePath, Debug)]
struct Blob {
    bytes: Vec<u8>,
}

#[derive(Default)]
struct BlobAssetLoader;

/// Possible errors that can be produced by [`BlobAssetLoader`]
#[non_exhaustive]
#[derive(Debug, Error)]
enum BlobAssetLoaderError {
    /// An [IO](std::io) Error
    #[error("Could not load file: {0}")]
    Io(#[from] std::io::Error),
}

impl AssetLoader for BlobAssetLoader {
    type Asset = Blob;
    type Settings = ();
    type Error = BlobAssetLoaderError;

    async fn load<'a>(
        &'a self,
        reader: &'a mut Reader<'_>,
        _settings: &'a (),
        _load_context: &'a mut LoadContext<'_>,
    ) -> Result<Self::Asset, Self::Error> {
        info!("Loading Blob...");
        let mut bytes = Vec::new();
        reader.read_to_end(&mut bytes).await?;

        Ok(Blob { bytes })
    }
More examples
Hide additional examples
examples/asset/processing/asset_processing.rs (line 91)
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
    async fn load<'a>(
        &'a self,
        reader: &'a mut Reader<'_>,
        settings: &'a TextSettings,
        _load_context: &'a mut LoadContext<'_>,
    ) -> Result<Text, Self::Error> {
        let mut bytes = Vec::new();
        reader.read_to_end(&mut bytes).await?;
        let value = if let Some(ref text) = settings.text_override {
            text.clone()
        } else {
            String::from_utf8(bytes).unwrap()
        };
        Ok(Text(value))
    }

    fn extensions(&self) -> &[&str] {
        &["txt"]
    }
}

#[derive(Serialize, Deserialize)]
struct CoolTextRon {
    text: String,
    dependencies: Vec<String>,
    embedded_dependencies: Vec<String>,
}

#[derive(Asset, TypePath, Debug)]
struct CoolText {
    text: String,
    #[allow(unused)]
    dependencies: Vec<Handle<Text>>,
}

#[derive(Default)]
struct CoolTextLoader;

#[derive(Debug, Error)]
enum CoolTextLoaderError {
    #[error(transparent)]
    Io(#[from] std::io::Error),
    #[error(transparent)]
    RonSpannedError(#[from] ron::error::SpannedError),
    #[error(transparent)]
    LoadDirectError(#[from] bevy::asset::LoadDirectError),
}

impl AssetLoader for CoolTextLoader {
    type Asset = CoolText;
    type Settings = ();
    type Error = CoolTextLoaderError;

    async fn load<'a>(
        &'a self,
        reader: &'a mut Reader<'_>,
        _settings: &'a Self::Settings,
        load_context: &'a mut LoadContext<'_>,
    ) -> Result<CoolText, Self::Error> {
        let mut bytes = Vec::new();
        reader.read_to_end(&mut bytes).await?;
        let ron: CoolTextRon = ron::de::from_bytes(&bytes)?;
        let mut base_text = ron.text;
        for embedded in ron.embedded_dependencies {
            let loaded = load_context.load_direct(&embedded).await?;
            let text = loaded.get::<Text>().unwrap();
            base_text.push_str(&text.0);
        }
        Ok(CoolText {
            text: base_text,
            dependencies: ron
                .dependencies
                .iter()
                .map(|p| load_context.load(p))
                .collect(),
        })
    }
examples/asset/asset_decompression.rs (line 61)
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
    async fn load<'a>(
        &'a self,
        reader: &'a mut Reader<'_>,
        _settings: &'a (),
        load_context: &'a mut LoadContext<'_>,
    ) -> Result<Self::Asset, Self::Error> {
        let compressed_path = load_context.path();
        let file_name = compressed_path
            .file_name()
            .ok_or(GzAssetLoaderError::IndeterminateFilePath)?
            .to_string_lossy();
        let uncompressed_file_name = file_name
            .strip_suffix(".gz")
            .ok_or(GzAssetLoaderError::IndeterminateFilePath)?;
        let contained_path = compressed_path.join(uncompressed_file_name);

        let mut bytes_compressed = Vec::new();

        reader.read_to_end(&mut bytes_compressed).await?;

        let mut decoder = GzDecoder::new(bytes_compressed.as_slice());

        let mut bytes_uncompressed = Vec::new();

        decoder.read_to_end(&mut bytes_uncompressed)?;

        // Now that we have decompressed the asset, let's pass it back to the
        // context to continue loading

        let mut reader = VecReader::new(bytes_uncompressed);

        let uncompressed = load_context
            .load_direct_with_reader(&mut reader, contained_path)
            .await?;

        Ok(GzAsset { uncompressed })
    }

fn read_to_string<'a>( &'a mut self, buf: &'a mut String ) -> ReadToStringFuture<'a, Self>
where Self: Unpin,

Reads the entire contents and appends them to a String.

On success, returns the total number of bytes read.

§Examples
use futures_lite::io::{AsyncReadExt, Cursor};

let mut reader = Cursor::new(&b"hello");
let mut contents = String::new();

let n = reader.read_to_string(&mut contents).await?;
assert_eq!(n, 5);
assert_eq!(contents, "hello");

fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>
where Self: Unpin,

Reads the exact number of bytes required to fill buf.

On success, returns the total number of bytes read.

§Examples
use futures_lite::io::{AsyncReadExt, Cursor};

let mut reader = Cursor::new(&b"hello");
let mut contents = vec![0; 3];

reader.read_exact(&mut contents).await?;
assert_eq!(contents, b"hel");

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it.

This method returns a new instance of AsyncRead which will read at most limit bytes, after which it will always return Ok(0) indicating EOF.

§Examples
use futures_lite::io::{AsyncReadExt, Cursor};

let mut reader = Cursor::new(&b"hello");
let mut contents = String::new();

let n = reader.take(3).read_to_string(&mut contents).await?;
assert_eq!(n, 3);
assert_eq!(contents, "hel");

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Converts this AsyncRead into a Stream of bytes.

The returned type implements Stream where Item is io::Result<u8>.

use futures_lite::io::{AsyncReadExt, Cursor};
use futures_lite::stream::StreamExt;

let reader = Cursor::new(&b"hello");
let mut bytes = reader.bytes();

while let Some(byte) = bytes.next().await {
    println!("byte: {}", byte?);
}

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: AsyncRead, Self: Sized,

Creates an adapter which will chain this stream with another.

The returned AsyncRead instance will first read all bytes from this reader until EOF is found, and then continue with next.

§Examples
use futures_lite::io::{AsyncReadExt, Cursor};

let r1 = Cursor::new(&b"hello");
let r2 = Cursor::new(&b"world");
let mut reader = r1.chain(r2);

let mut contents = String::new();
reader.read_to_string(&mut contents).await?;
assert_eq!(contents, "helloworld");

fn boxed_reader<'a>(self) -> Pin<Box<dyn AsyncRead + Send + 'a>>
where Self: Sized + Send + 'a,

Available on crate feature alloc only.

Boxes the reader and changes its type to dyn AsyncRead + Send + 'a.

§Examples
use futures_lite::io::AsyncReadExt;

let reader = [1, 2, 3].boxed_reader();

Object Safety§

This trait is not object safe.

Implementors§

§

impl<R> AsyncReadExt for R
where R: AsyncRead + ?Sized,