Debian Codegraph @

third_party/rust/replace_with/src/lib.rs

raw
1 //! Temporarily take ownership of a value at a mutable location, and replace it with a new value
2 //! based on the old one.
3 //!
4 //! <p style="font-family: 'Fira Sans',sans-serif;padding:0.3em 0"><strong>
5 //! <a href="https://crates.io/crates/replace_with">📦&nbsp;&nbsp;Crates.io</a>&nbsp;&nbsp;│&nbsp;&nbsp;<a href="https://github.com/alecmocatta/replace_with">📑&nbsp;&nbsp;GitHub</a>&nbsp;&nbsp;│&nbsp;&nbsp;<a href="https://constellation.zulipchat.com/#narrow/stream/213236-subprojects">💬&nbsp;&nbsp;Chat</a>
6 //! </strong></p>
7 //!
8 //! This crate provides the function [`replace_with()`], which is like [`std::mem::replace()`]
9 //! except it allows the replacement value to be mapped from the original value.
10 //!
11 //! See [RFC 1736](https://github.com/rust-lang/rfcs/pull/1736) for a lot of discussion as to its
12 //! merits. It was never merged, and the desired ability to temporarily move out of `&mut T` doesn't
13 //! exist yet, so this crate is my interim solution.
14 //!
15 //! It's very akin to [`take_mut`](https://github.com/Sgeo/take_mut), though uses `Drop` instead of
16 //! [`std::panic::catch_unwind()`] to react to unwinding, which avoids the optimisation barrier of
17 //! calling the `extern "C" __rust_maybe_catch_panic()`. As such it's up to ∞x faster. The API also
18 //! attempts to make slightly more explicit the behavior on panic – [`replace_with()`] accepts two
19 //! closures such that aborting in the "standard case" where the mapping closure (`FnOnce(T) -> T`)
20 //! panics (as [`take_mut::take()`](https://docs.rs/take_mut/0.2.2/take_mut/fn.take.html) does) is
21 //! avoided. If the second closure (`FnOnce() -> T`) panics, however, then it does indeed abort.
22 //! The "abort on first panic" behaviour is available with [`replace_with_or_abort()`].
23 //!
24 //! # Example
25 //!
26 //! Consider this motivating example:
27 //!
28 //! ```compile_fail
29 //! # use replace_with::*;
30 //! enum States {
31 //! A(String),
32 //! B(String),
33 //! }
34 //!
35 //! impl States {
36 //! fn poll(&mut self) {
37 //! // error[E0507]: cannot move out of borrowed content
38 //! *self = match *self {
39 //! // ^^^^^ cannot move out of borrowed content
40 //! States::A(a) => States::B(a),
41 //! States::B(a) => States::A(a),
42 //! };
43 //! }
44 //! }
45 //! ```
46 //!
47 //! Depending on context this can be quite tricky to work around. With this crate, however:
48 //!
49 //! ```
50 //! # use replace_with::*;
51 //! enum States {
52 //! A(String),
53 //! B(String),
54 //! }
55 //!
56 //! # #[cfg(any(feature = "std", feature = "nightly"))]
57 //! impl States {
58 //! fn poll(&mut self) {
59 //! replace_with_or_abort(self, |self_| match self_ {
60 //! States::A(a) => States::B(a),
61 //! States::B(a) => States::A(a),
62 //! });
63 //! }
64 //! }
65 //! ```
66 //!
67 //! Huzzah!
68
69 #![cfg_attr(not(feature = "std"), no_std)]
70 #![cfg_attr(
71 all(not(feature = "std"), feature = "nightly"),
72 feature(core_intrinsics)
73 )]
74 #![doc(html_root_url = "https://docs.rs/replace_with/0.1.7")]
75 #![warn(
76 missing_copy_implementations,
77 missing_debug_implementations,
78 missing_docs,
79 trivial_casts,
80 trivial_numeric_casts,
81 unused_import_braces,
82 unused_qualifications,
83 unused_results,
84 // clippy::pedantic
85 )]
86 // #![allow(clippy::inline_always)]
87
88 #[cfg(not(feature = "std"))]
89 use core as std;
90
91 use std::{mem, ptr};
92
93 struct OnDrop<F: FnOnce()>(mem::ManuallyDrop<F>);
94 impl<F: FnOnce()> Drop for OnDrop<F> {
95 #[inline(always)]
96 fn drop(&mut self) {
97 (unsafe { ptr::read(&*self.0) })();
98 }
99 }
100
101 #[doc(hidden)]
102 #[inline(always)]
103 pub fn on_unwind<F: FnOnce() -> T, T, P: FnOnce()>(f: F, p: P) -> T {
104 let x = OnDrop(mem::ManuallyDrop::new(p));
105 let t = f();
106 let mut x = mem::ManuallyDrop::new(x);
107 unsafe { mem::ManuallyDrop::drop(&mut x.0) };
108 t
109 }
110
111 #[doc(hidden)]
112 #[inline(always)]
113 pub fn on_return_or_unwind<F: FnOnce() -> T, T, P: FnOnce()>(f: F, p: P) -> T {
114 let _x = OnDrop(mem::ManuallyDrop::new(p));
115 f()
116 }
117
118 /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
119 /// based on the old one.
120 ///
121 /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which
122 /// is then placed at the original value's location.
123 ///
124 /// # An important note
125 ///
126 /// On panic (or to be more precise, unwinding) of the closure `f`, `default` will be called to
127 /// provide a replacement value. `default` should not panic – doing so will constitute a double
128 /// panic and will most likely abort the process.
129 ///
130 /// # Example
131 ///
132 /// ```
133 /// # use replace_with::*;
134 /// enum States {
135 /// A(String),
136 /// B(String),
137 /// }
138 ///
139 /// impl States {
140 /// fn poll(&mut self) {
141 /// replace_with(
142 /// self,
143 /// || States::A(String::new()),
144 /// |self_| match self_ {
145 /// States::A(a) => States::B(a),
146 /// States::B(a) => States::A(a),
147 /// },
148 /// );
149 /// }
150 /// }
151 /// ```
152 #[inline]
153 pub fn replace_with<T, D: FnOnce() -> T, F: FnOnce(T) -> T>(dest: &mut T, default: D, f: F) {
154 unsafe {
155 let old = ptr::read(dest);
156 let new = on_unwind(move || f(old), || ptr::write(dest, default()));
157 ptr::write(dest, new);
158 }
159 }
160
161 /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
162 /// based on the old one. Replaces with [`Default::default()`] on panic.
163 ///
164 /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which
165 /// is then placed at the original value's location.
166 ///
167 /// # An important note
168 ///
169 /// On panic (or to be more precise, unwinding) of the closure `f`, `T::default()` will be called to
170 /// provide a replacement value. `T::default()` should not panic – doing so will constitute a double
171 /// panic and will most likely abort the process.
172 ///
173 /// Equivalent to `replace_with(dest, T::default, f)`.
174 ///
175 /// Differs from `*dest = mem::replace(dest, Default::default())` in that `Default::default()` will
176 /// only be called on panic.
177 ///
178 /// # Example
179 ///
180 /// ```
181 /// # use replace_with::*;
182 /// enum States {
183 /// A(String),
184 /// B(String),
185 /// }
186 ///
187 /// impl Default for States {
188 /// fn default() -> Self {
189 /// States::A(String::new())
190 /// }
191 /// }
192 ///
193 /// impl States {
194 /// fn poll(&mut self) {
195 /// replace_with_or_default(self, |self_| match self_ {
196 /// States::A(a) => States::B(a),
197 /// States::B(a) => States::A(a),
198 /// });
199 /// }
200 /// }
201 /// ```
202 #[inline]
203 pub fn replace_with_or_default<T: Default, F: FnOnce(T) -> T>(dest: &mut T, f: F) {
204 replace_with(dest, T::default, f);
205 }
206
207 /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
208 /// based on the old one. Aborts on panic.
209 ///
210 /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which
211 /// is then placed at the original value's location.
212 ///
213 /// # An important note
214 ///
215 /// On panic (or to be more precise, unwinding) of the closure `f`, the process will **abort** to
216 /// avoid returning control while `dest` is in a potentially invalid state.
217 ///
218 /// If this behaviour is undesirable, use [`replace_with`] or [`replace_with_or_default`].
219 ///
220 /// Equivalent to `replace_with(dest, || process::abort(), f)`.
221 ///
222 /// # Example
223 ///
224 /// ```
225 /// # use replace_with::*;
226 /// enum States {
227 /// A(String),
228 /// B(String),
229 /// }
230 ///
231 /// # #[cfg(any(feature = "std", feature = "nightly"))]
232 /// impl States {
233 /// fn poll(&mut self) {
234 /// replace_with_or_abort(self, |self_| match self_ {
235 /// States::A(a) => States::B(a),
236 /// States::B(a) => States::A(a),
237 /// });
238 /// }
239 /// }
240 /// ```
241 #[inline]
242 #[cfg(feature = "std")]
243 pub fn replace_with_or_abort<T, F: FnOnce(T) -> T>(dest: &mut T, f: F) {
244 replace_with(dest, || std::process::abort(), f);
245 }
246
247 #[inline]
248 #[cfg(all(not(feature = "std"), feature = "nightly"))]
249 pub fn replace_with_or_abort<T, F: FnOnce(T) -> T>(dest: &mut T, f: F) {
250 replace_with(dest, || unsafe { std::intrinsics::abort() }, f);
251 }
252
253 /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
254 /// based on the old one. Aborts on panic.
255 ///
256 /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which
257 /// is then placed at the original value's location.
258 ///
259 /// # An important note
260 ///
261 /// On panic (or to be more precise, unwinding) of the closure `f`, the process will **abort** to
262 /// avoid returning control while `dest` is in a potentially invalid state.
263 ///
264 /// Unlike for `replace_with_or_abort()` users of `replace_with_or_abort_unchecked()` are expected
265 /// to have `features = ["panic_abort", …]` defined in `Cargo.toml`
266 /// and `panic = "abort"` defined in their profile for it to behave semantically correct:
267 ///
268 /// ```toml
269 /// # Cargo.toml
270 ///
271 /// [profile.debug]
272 /// panic = "abort"
273 ///
274 /// [profile.release]
275 /// panic = "abort"
276 /// ```
277 ///
278 /// # Safety
279 ///
280 /// It is crucial to only ever use this function having defined `panic = "abort"`, or else bad
281 /// things may happen. It's *up to you* to uphold this invariant!
282 ///
283 /// If this behaviour is undesirable, use [`replace_with`] or [`replace_with_or_default`].
284 ///
285 /// Equivalent to `replace_with(dest, || process::abort(), f)`.
286 ///
287 /// # Example
288 ///
289 /// ```
290 /// # use replace_with::*;
291 /// enum States {
292 /// A(String),
293 /// B(String),
294 /// }
295 ///
296 /// impl States {
297 /// fn poll(&mut self) {
298 /// unsafe {
299 /// replace_with_or_abort_unchecked(self, |self_| match self_ {
300 /// States::A(a) => States::B(a),
301 /// States::B(a) => States::A(a),
302 /// });
303 /// }
304 /// }
305 /// }
306 /// ```
307 ///
308 #[inline]
309 #[cfg(feature = "panic_abort")]
310 pub unsafe fn replace_with_or_abort_unchecked<T, F: FnOnce(T) -> T>(dest: &mut T, f: F) {
311 ptr::write(dest, f(ptr::read(dest)));
312 }
313
314 /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
315 /// based on the old one. Lets the closure return a custom value as well.
316 ///
317 /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which
318 /// is then placed at the original value's location.
319 ///
320 /// This is effectively the same function as [`replace_with`], but it lets the closure return a
321 /// custom value as well.
322 ///
323 /// # An important note
324 ///
325 /// On panic (or to be more precise, unwinding) of the closure `f`, `default` will be called to
326 /// provide a replacement value. `default` should not panic – doing so will constitute a double
327 /// panic and will most likely abort the process.
328 ///
329 /// # Example
330 ///
331 /// ```
332 /// # use replace_with::*;
333 ///
334 /// fn take<T>(option: &mut Option<T>) -> Option<T> {
335 /// replace_with_and_return(option, || None, |option| (option, None))
336 /// }
337 ///
338 /// let mut opt = Some(3);
339 /// assert_eq!(take(&mut opt), Some(3));
340 /// assert_eq!(take(&mut opt), None);
341 /// ```
342 #[inline]
343 pub fn replace_with_and_return<T, U, D: FnOnce() -> T, F: FnOnce(T) -> (U, T)>(
344 dest: &mut T, default: D, f: F,
345 ) -> U {
346 unsafe {
347 let old = ptr::read(dest);
348 let (res, new) = on_unwind(move || f(old), || ptr::write(dest, default()));
349 ptr::write(dest, new);
350 res
351 }
352 }
353
354 /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
355 /// based on the old one. Replaces with [`Default::default()`] on panic.
356 /// Lets the closure return a custom value as well.
357 ///
358 /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which
359 /// is then placed at the original value's location.
360 ///
361 /// This is effectively the same function as [`replace_with_or_default`], but it lets the closure
362 /// return a custom value as well.
363 ///
364 /// # An important note
365 ///
366 /// On panic (or to be more precise, unwinding) of the closure `f`, `T::default()` will be called to
367 /// provide a replacement value. `T::default()` should not panic – doing so will constitute a double
368 /// panic and will most likely abort the process.
369 ///
370 /// Equivalent to `replace_with_and_return(dest, T::default, f)`.
371 ///
372 /// # Example
373 ///
374 /// ```
375 /// # use replace_with::*;
376 ///
377 /// fn take<T>(option: &mut Option<T>) -> Option<T> {
378 /// replace_with_or_default_and_return(option, |option| (option, None))
379 /// }
380 /// ```
381 #[inline]
382 pub fn replace_with_or_default_and_return<T: Default, U, F: FnOnce(T) -> (U, T)>(
383 dest: &mut T, f: F,
384 ) -> U {
385 replace_with_and_return(dest, T::default, f)
386 }
387
388 /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
389 /// based on the old one. Aborts on panic. Lets the closure return a custom value as well.
390 ///
391 /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which
392 /// is then placed at the original value's location.
393 ///
394 /// This is effectively the same function as [`replace_with_or_abort`], but it lets the closure
395 /// return a custom value as well.
396 ///
397 /// # An important note
398 ///
399 /// On panic (or to be more precise, unwinding) of the closure `f`, the process will **abort** to
400 /// avoid returning control while `dest` is in a potentially invalid state.
401 ///
402 /// If this behaviour is undesirable, use [`replace_with_and_return`] or
403 /// [`replace_with_or_default_and_return`] instead.
404 ///
405 /// Equivalent to `replace_with_and_return(dest, || process::abort(), f)`.
406 ///
407 /// # Example
408 ///
409 /// ```
410 /// # use replace_with::*;
411 ///
412 /// fn take<T>(option: &mut Option<T>) -> Option<T> {
413 /// replace_with_or_abort_and_return(option, |option| (option, None))
414 /// }
415 /// ```
416 #[inline]
417 #[cfg(feature = "std")]
418 pub fn replace_with_or_abort_and_return<T, U, F: FnOnce(T) -> (U, T)>(dest: &mut T, f: F) -> U {
419 replace_with_and_return(dest, || std::process::abort(), f)
420 }
421
422 #[inline]
423 #[cfg(all(not(feature = "std"), feature = "nightly"))]
424 pub fn replace_with_or_abort_and_return<T, U, F: FnOnce(T) -> (U, T)>(dest: &mut T, f: F) -> U {
425 replace_with_and_return(dest, || unsafe { std::intrinsics::abort() }, f)
426 }
427
428 /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
429 /// based on the old one. Aborts on panic. Lets the closure return a custom value as well.
430 ///
431 /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which
432 /// is then placed at the original value's location.
433 ///
434 /// This is effectively the same function as [`replace_with_or_abort_unchecked`], but it lets the
435 /// closure return a custom value as well.
436 ///
437 /// # An important note
438 ///
439 /// On panic (or to be more precise, unwinding) of the closure `f`, the process will **abort** to
440 /// avoid returning control while `dest` is in a potentially invalid state.
441 ///
442 /// Unlike for `replace_with_or_abort()` users of `replace_with_or_abort_unchecked()` are expected
443 /// to have `features = ["panic_abort", …]` defined in `Cargo.toml`
444 /// and `panic = "abort"` defined in their profile for it to behave semantically correct:
445 ///
446 /// ```toml
447 /// # Cargo.toml
448 ///
449 /// [profile.debug]
450 /// panic = "abort"
451 ///
452 /// [profile.release]
453 /// panic = "abort"
454 /// ```
455 ///
456 /// # Safety
457 ///
458 /// It is crucial to only ever use this function having defined `panic = "abort"`, or else bad
459 /// things may happen. It's *up to you* to uphold this invariant!
460 ///
461 /// If this behaviour is undesirable, use [`replace_with_and_return`] or
462 /// [`replace_with_or_default_and_return`].
463 ///
464 /// Equivalent to `replace_with_and_return(dest, || process::abort(), f)`.
465 ///
466 /// # Example
467 ///
468 /// ```
469 /// # use replace_with::*;
470 ///
471 /// unsafe fn take<T>(option: &mut Option<T>) -> Option<T> {
472 /// replace_with_or_abort_and_return_unchecked(option, |option| (option, None))
473 /// }
474 /// ```
475 #[inline]
476 #[cfg(feature = "std")]
477 #[cfg(feature = "panic_abort")]
478 pub unsafe fn replace_with_or_abort_and_return_unchecked<T, U, F: FnOnce(T) -> (U, T)>(
479 dest: &mut T, f: F,
480 ) -> U {
481 let (res, new) = f(ptr::read(dest));
482 ptr::write(dest, new);
483 res
484 }
485
486 #[cfg(test)]
487 mod test {
488 // These functions copied from https://github.com/Sgeo/take_mut/blob/1bd70d842c6febcd16ec1fe3a954a84032b89f52/src/lib.rs#L102-L147
489
490 // Copyright (c) 2016 Sgeo
491
492 // Permission is hereby granted, free of charge, to any person obtaining a copy
493 // of this software and associated documentation files (the "Software"), to deal
494 // in the Software without restriction, including without limitation the rights
495 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
496 // copies of the Software, and to permit persons to whom the Software is
497 // furnished to do so, subject to the following conditions:
498
499 // The above copyright notice and this permission notice shall be included in all
500 // copies or substantial portions of the Software.
501
502 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
503 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
504 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
505 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
506 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
507 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
508 // SOFTWARE.
509
510 use super::*;
511
512 #[test]
513 fn it_works_recover() {
514 #[derive(PartialEq, Eq, Debug)]
515 enum Foo {
516 A,
517 B,
518 };
519 impl Drop for Foo {
520 #[cfg(feature = "std")]
521 fn drop(&mut self) {
522 match *self {
523 Foo::A => println!("Foo::A dropped"),
524 Foo::B => println!("Foo::B dropped"),
525 }
526 }
527
528 #[cfg(not(feature = "std"))]
529 fn drop(&mut self) {
530 match *self {
531 Foo::A | Foo::B => (),
532 }
533 }
534 }
535 let mut quax = Foo::A;
536 replace_with(
537 &mut quax,
538 || Foo::A,
539 |f| {
540 drop(f);
541 Foo::B
542 },
543 );
544 assert_eq!(&quax, &Foo::B);
545
546 let n = replace_with_and_return(
547 &mut quax,
548 || Foo::B,
549 |f| {
550 drop(f);
551 (3, Foo::A)
552 },
553 );
554 assert_eq!(n, 3);
555 assert_eq!(&quax, &Foo::A);
556 }
557
558 #[cfg(all(feature = "std", not(miri)))] // https://github.com/rust-lang/miri/issues/658
559 #[test]
560 fn it_works_recover_panic() {
561 use std::panic;
562
563 #[derive(PartialEq, Eq, Debug)]
564 enum Foo {
565 A,
566 B,
567 C,
568 };
569 impl Drop for Foo {
570 fn drop(&mut self) {
571 match *self {
572 Foo::A => println!("Foo::A dropped"),
573 Foo::B => println!("Foo::B dropped"),
574 Foo::C => println!("Foo::C dropped"),
575 }
576 }
577 }
578 let mut quax = Foo::A;
579
580 let res = panic::catch_unwind(panic::AssertUnwindSafe(|| {
581 replace_with(
582 &mut quax,
583 || Foo::C,
584 |f| {
585 drop(f);
586 panic!("panic");
587 #[allow(unreachable_code)]
588 Foo::B
589 },
590 );
591 }));
592
593 assert!(res.is_err());
594 assert_eq!(&quax, &Foo::C);
595 }
596 }