|
29 | 29 | use std::fmt::{self, Display, Debug}; |
30 | 30 | use std::iter::FromIterator; |
31 | 31 | use std::ops::{Deref, DerefMut}; |
32 | | -use std::{mem, ptr, slice, vec}; |
| 32 | +use std::{slice, vec}; |
33 | 33 |
|
34 | 34 | use serialize::{Encodable, Decodable, Encoder, Decoder}; |
35 | 35 |
|
@@ -66,45 +66,18 @@ impl<T: 'static> P<T> { |
66 | 66 | pub fn map<F>(mut self, f: F) -> P<T> where |
67 | 67 | F: FnOnce(T) -> T, |
68 | 68 | { |
69 | | - let p: *mut T = &mut *self.ptr; |
| 69 | + let x = f(*self.ptr); |
| 70 | + *self.ptr = x; |
70 | 71 |
|
71 | | - // Leak self in case of panic. |
72 | | - // FIXME(eddyb) Use some sort of "free guard" that |
73 | | - // only deallocates, without dropping the pointee, |
74 | | - // in case the call the `f` below ends in a panic. |
75 | | - mem::forget(self); |
76 | | - |
77 | | - unsafe { |
78 | | - ptr::write(p, f(ptr::read(p))); |
79 | | - |
80 | | - // Recreate self from the raw pointer. |
81 | | - P { ptr: Box::from_raw(p) } |
82 | | - } |
| 72 | + self |
83 | 73 | } |
84 | 74 |
|
85 | 75 | /// Optionally produce a new `P<T>` from `self` without reallocating. |
86 | 76 | pub fn filter_map<F>(mut self, f: F) -> Option<P<T>> where |
87 | 77 | F: FnOnce(T) -> Option<T>, |
88 | 78 | { |
89 | | - let p: *mut T = &mut *self.ptr; |
90 | | - |
91 | | - // Leak self in case of panic. |
92 | | - // FIXME(eddyb) Use some sort of "free guard" that |
93 | | - // only deallocates, without dropping the pointee, |
94 | | - // in case the call the `f` below ends in a panic. |
95 | | - mem::forget(self); |
96 | | - |
97 | | - unsafe { |
98 | | - if let Some(v) = f(ptr::read(p)) { |
99 | | - ptr::write(p, v); |
100 | | - |
101 | | - // Recreate self from the raw pointer. |
102 | | - Some(P { ptr: Box::from_raw(p) }) |
103 | | - } else { |
104 | | - drop(Box::from_raw(p)); |
105 | | - None |
106 | | - } |
107 | | - } |
| 79 | + *self.ptr = f(*self.ptr)?; |
| 80 | + Some(self) |
108 | 81 | } |
109 | 82 | } |
110 | 83 |
|
|
0 commit comments