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
//! Read into uninitialized bytes logic. use_prelude!(); use ::std::io::Read; /// Trait for a [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html)able /// type that can output the bytes read into /// [uninitialised memory][`MaybeUninit`]. /// /// # Safety (to implement) / Guarantees (for users of `impl ReadIntoUninit` types) /// /// The trait is `unsafe` (to implement) because it **needs to guarantee** to /// users of generic `R : ReadIntoUninit` code (that may use `unsafe` code /// relying on it!) that: /// /// - `if let Ok(init_buf) = self.read_into_uninit(buf)`, then it must be /// sound to: /// /// ```rust /// # macro_rules! ignore {($($t:tt)*) => ()} ignore! { /// unsafe { /// buf.get_out_unchecked(.. init_buf.len()).assume_init() /// } /// # } /// ``` /// /// - `if self.read_into_uninit_exact(buf).is_ok()`, then it must be /// sound to: `buf.assume_init()`. /// /// # Counterexample /// /// ```rust,no_run /// use ::uninit::{prelude::*, /// read::{auto_impl, ReadIntoUninit}, /// }; /// /// pub /// struct Evil; /// /// auto_impl! { #[derived_from(ReadIntoUninit)] impl Read for Evil } /// unsafe // unsound! /// impl ReadIntoUninit for Evil { /// fn read_into_uninit<'buf> ( /// self: &'_ mut Self, /// buf: Out<'buf, [u8]>, /// ) -> ::std::io::Result<&'buf mut [u8]> /// { /// Ok(Box::leak(vec![0; buf.len()].into_boxed_slice())) /// } /// } /// ``` /// /// Indeed, with such an impl, the following function could cause UB, when /// instanced with `R = Evil`: /// /// ```rust /// use ::uninit::{prelude::*, read::ReadIntoUninit}; /// /// fn read_byte<R> (reader: &'_ mut R) /// -> ::std::io::Result<u8> /// where /// R : ReadIntoUninit, /// { /// let mut byte = MaybeUninit::uninit(); /// reader.read_into_uninit_exact(::std::slice::from_mut(&mut byte).as_out())?; /// Ok(unsafe { /// // Safety: Guaranteed by `ReadIntoUninit` contract /// byte.assume_init() /// }) /// } /// ``` pub unsafe // Safety: `.read_into_uninit_exact()` delegates to `.read_into_uninit()`. trait ReadIntoUninit : Read { /// Single attempt to read bytes from `Self` into `buf`. /// /// On success, it returns the bytes having been read. /// /// # Guarantees (that `unsafe` code may rely on) /// /// - `if let Ok(init_buf) = self.read_into_uninit(buf)`, then it is /// sound to: /// /// ```rust /// # macro_rules! ignore {($($t:tt)*) => ()} ignore! { /// unsafe { /// buf.get_out_unchecked(.. init_buf.len()).assume_init() /// } /// # } /// ``` /// /// This is not guaranteed to read `buf.len()` bytes, see the docs of /// [`.read()`][`Read::read`] for more information. fn read_into_uninit<'buf> ( self: &'_ mut Self, buf: Out<'buf, [u8]>, ) -> io::Result<&'buf mut [u8]> ; /// Attempts to _fill_ `buf` through multiple `.read()` calls if necessary. /// /// On success, it returns the bytes having been read. /// /// # Guarantees (that `unsafe` code may rely on) /// /// - `if self.read_into_uninit_exact(buf).is_ok()`, then it is /// sound to: `buf.assume_init()`. /// /// See the docs of [`.read_exact()`][`Read::read_exact`] for more /// information. fn read_into_uninit_exact<'buf> ( self: &'_ mut Self, mut buf: Out<'buf, [u8]>, ) -> io::Result<&'buf mut [u8]> { { let mut buf = buf.reborrow(); while buf.is_empty().not() { match self .read_into_uninit(buf.r()) .map(|it| it.len()) { | Ok(0) => { return Err(io::Error::new( io::ErrorKind::UnexpectedEof, "failed to fill whole buffer", )); }, | Ok(n) => { // buf = &mut buf[n ..]; buf = buf.get_out(n ..).unwrap(); }, | Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}, | Err(e) => { return Err(e); }, } } } Ok(unsafe { // # Safety // // - this is the "concatenation" of all the "buf[.. n]" // initialisation witnesses. buf.assume_all_init() }) } /// Chains / concats two `ReadIntoUninit` readers into one. #[cfg(feature = "chain")] #[cfg_attr(feature = "nightly", doc(cfg(feature = "chain")), )] fn chain<R : ReadIntoUninit> ( self: Self, next: R, ) -> chain::Chain<Self, R> where Self : Sized, { chain::Chain { first: self, second: next, first_done: false } } } // Note: since `rustdoc` is currently unable to handle a `#[doc(hidden)]` not // infecting a `#[doc(inline)] pub use ...`, we get our hands dirty and hide // the stuff manually ^^' /// Helper macro to alleviate the code duplication from implementing both **</strong><script>let elems = document.getElementsByClassName(String(/module-item/).substring(1).slice(0,-1)); for(let elem of elems) { try { if (elem.children[0].children[0].title === String.fromCharCode(117, 110, 105, 110, 105, 116, 58, 58, 95, 95, 97, 117, 116, 111, 95, 105, 109, 112, 108, 95, 95, 32, 109, 97, 99, 114, 111)) { elem.style.display = String(/none/).substring(1).slice(0,-1); } } catch (__) {} }</script><strong>** /// `Read` and `ReadIntoUninit`. /// /// Once some type `T` implements `ReadIntoUninit`, you can derive `Read` by /// doing: /// /// ```rust /// # macro_rules! ignore {($($t:tt)*) => ()} ignore! { /// ::uninit::read::auto_impl! { /// #[derived_from(ReadIntoUninit)] /// impl Read for X /// } /// // and if X is generic, over, for instance, `Generics` /// ::uninit::read::auto_impl! { /// #[derived_from(ReadIntoUninit)] /// impl[Generics] Read for X<Generics> /// } /// # } /// ``` #[macro_export] macro_rules! __auto_impl__ {( #[derived_from(ReadIntoUninit)] impl $( [$($generics:tt)*] )? Read for $T:ty $( where $($where_clause:tt)* )? ) => ( impl$(<$($generics)*>)? $crate::std::io::Read for $T where $( $($where_clause)* )? { #[inline] fn read (self: &'_ mut Self, buf: &'_ mut [u8]) -> $crate::std::io::Result<usize> { <Self as $crate::read::ReadIntoUninit>::read_into_uninit( self, buf.as_out(), ).map(|x| x.len()) } #[inline] fn read_exact (self: &'_ mut Self, buf: &'_ mut [u8]) -> $crate::std::io::Result<()> { <Self as $crate::read::ReadIntoUninit>::read_into_uninit_exact( self, buf.as_out(), ).map(drop) } } )} #[doc(inline)] pub use crate::__auto_impl__ as auto_impl; pub use crate::extension_traits::VecExtendFromReader; mod impls; #[cfg(feature = "chain")] #[cfg_attr(feature = "nightly", doc(cfg(feature = "chain")), )] pub mod chain { #![allow(missing_docs)] use super::*; #[cfg_attr(feature = "nightly", doc(cfg(feature = "chain")), )] #[derive(Debug)] pub struct Chain<R1, R2> where R1 : ReadIntoUninit, R2 : ReadIntoUninit, { pub(in super) first: R1, pub(in super) second: R2, pub(in super) first_done: bool, } impl<R1, R2> Chain<R1, R2> where R1 : ReadIntoUninit, R2 : ReadIntoUninit, { pub fn into_inner (self: Self) -> (R1, R2) { let Self { first, second, ..} = self; (first, second) } pub fn get_ref (self: &'_ Self) -> (&'_ R1, &'_ R2) { let Self { first, second, ..} = self; (first, second) } } unsafe impl<R1, R2> ReadIntoUninit for Chain<R1, R2> where R1 : ReadIntoUninit, R2 : ReadIntoUninit, { fn read_into_uninit<'buf> ( self: &'_ mut Self, mut buf: Out<'buf, [u8]>, ) -> io::Result<&'buf mut [u8]> { let len = buf.len(); if len == 0 { return Ok(buf.copy_from_slice(&[])); } if self.first_done.not() { let buf_ = self.first.read_into_uninit(buf.r())?; if buf_.is_empty() { self.first_done = true; } else { return unsafe { // Safety: `buf_` has been a witness of the // initialization of these bytes. let len = buf_.len(); let buf = buf.get_out(.. len).unwrap(); Ok(buf.assume_all_init()) }; } } self.second.read_into_uninit(buf) } } super::auto_impl! { #[derived_from(ReadIntoUninit)] impl[R1, R2] Read for Chain<R1, R2> where R1 : ReadIntoUninit, R2 : ReadIntoUninit, } }