Skip to content

Commit 64e23fc

Browse files
authored
Merge pull request #63 from maciejhirsz/0.8.8
Add `take_string`, closes #62
2 parents bbef847 + 884897d commit 64e23fc

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "json"
3-
version = "0.8.7"
3+
version = "0.8.8"
44
authors = ["Maciej Hirsz <[email protected]>"]
55
description = "JSON implementation in Rust"
66
repository = "https://github.com/maciejhirsz/json-rust"

src/value.rs

+34
Original file line numberDiff line numberDiff 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<()>

0 commit comments

Comments
 (0)