File tree Expand file tree Collapse file tree 2 files changed +35
-1
lines changed
Expand file tree Collapse file tree 2 files changed +35
-1
lines changed Original file line number Diff line number Diff line change 11[package ]
22name = " json"
3- version = " 0.8.7 "
3+ version = " 0.8.8 "
44authors = [" Maciej Hirsz <maciej.hirsz@gmail.com>" ]
55description = " JSON implementation in Rust"
66repository = " https://github.com/maciejhirsz/json-rust"
Original file line number Diff line number Diff line change @@ -198,6 +198,40 @@ impl JsonValue {
198198 mem:: replace ( self , JsonValue :: Null )
199199 }
200200
201+ /// Checks that self is a string, returns an owned Rust `String, leaving
202+ /// `Null` in it's place.
203+ ///
204+ /// This is the cheapest way to obtain an owned `String` from JSON, as no
205+ /// extra heap allocation is performend.
206+ ///
207+ /// ## Example
208+ ///
209+ /// ```
210+ /// # #[macro_use] extern crate json;
211+ /// # fn main() {
212+ /// let mut data = array!["Hello", "World"];
213+ ///
214+ /// let owned = data[0].take_string().expect("Should be a string");
215+ ///
216+ /// assert_eq!(owned, "Hello");
217+ /// assert!(data[0].is_null());
218+ /// # }
219+ /// ```
220+ pub fn take_string ( & mut self ) -> Option < String > {
221+ let mut placeholder = JsonValue :: Null ;
222+
223+ mem:: swap ( self , & mut placeholder) ;
224+
225+ match placeholder {
226+ JsonValue :: String ( string) => return Some ( string) ,
227+
228+ // Not a string? Swap the original value back in place!
229+ _ => mem:: swap ( self , & mut placeholder)
230+ }
231+
232+ None
233+ }
234+
201235 /// Works on `JsonValue::Array` - pushes a new value to the array.
202236 #[ must_use]
203237 pub fn push < T > ( & mut self , value : T ) -> JsonResult < ( ) >
You can’t perform that action at this time.
0 commit comments