rollup merge of #19224: frewsxcv/unprefix-json-types

Addressing the issues brought up in [this thread](https://github.com/rust-lang/rust/pull/19114#discussion_r20614461)

This pull request:

* Unpublicizes reexports
* Renames type aliases:
 * `json::JsonArray` ☞ `json::Array`
 * `json::JsonObject` ☞ `json::Object`
This commit is contained in:
Alex Crichton 2014-11-26 09:44:03 -08:00
commit 97495da163
2 changed files with 92 additions and 92 deletions

View file

@ -194,12 +194,11 @@ fn main() {
*/ */
pub use self::JsonEvent::*; use self::JsonEvent::*;
pub use self::StackElement::*; use self::StackElement::*;
pub use self::Json::*; use self::ErrorCode::*;
pub use self::ErrorCode::*; use self::ParserError::*;
pub use self::ParserError::*; use self::DecoderError::*;
pub use self::DecoderError::*;
use self::ParserState::*; use self::ParserState::*;
use self::InternalStackElement::*; use self::InternalStackElement::*;
@ -223,13 +222,13 @@ pub enum Json {
F64(f64), F64(f64),
String(string::String), String(string::String),
Boolean(bool), Boolean(bool),
Array(JsonArray), Array(self::Array),
Object(JsonObject), Object(self::Object),
Null, Null,
} }
pub type JsonArray = Vec<Json>; pub type Array = Vec<Json>;
pub type JsonObject = TreeMap<string::String, Json>; pub type Object = TreeMap<string::String, Json>;
/// The errors that can arise while parsing a JSON stream. /// The errors that can arise while parsing a JSON stream.
#[deriving(Clone, PartialEq)] #[deriving(Clone, PartialEq)]
@ -274,7 +273,7 @@ pub enum DecoderError {
/// Returns a readable error string for a given error code. /// Returns a readable error string for a given error code.
pub fn error_str(error: ErrorCode) -> &'static str { pub fn error_str(error: ErrorCode) -> &'static str {
return match error { match error {
InvalidSyntax => "invalid syntax", InvalidSyntax => "invalid syntax",
InvalidNumber => "invalid number", InvalidNumber => "invalid number",
EOFWhileParsingObject => "EOF While parsing object", EOFWhileParsingObject => "EOF While parsing object",
@ -863,14 +862,14 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
impl<E: ::Encoder<S>, S> Encodable<E, S> for Json { impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
fn encode(&self, e: &mut E) -> Result<(), S> { fn encode(&self, e: &mut E) -> Result<(), S> {
match *self { match *self {
I64(v) => v.encode(e), Json::I64(v) => v.encode(e),
U64(v) => v.encode(e), Json::U64(v) => v.encode(e),
F64(v) => v.encode(e), Json::F64(v) => v.encode(e),
String(ref v) => v.encode(e), Json::String(ref v) => v.encode(e),
Boolean(v) => v.encode(e), Json::Boolean(v) => v.encode(e),
Array(ref v) => v.encode(e), Json::Array(ref v) => v.encode(e),
Object(ref v) => v.encode(e), Json::Object(ref v) => v.encode(e),
Null => e.emit_nil(), Json::Null => e.emit_nil(),
} }
} }
} }
@ -900,7 +899,7 @@ impl Json {
/// Otherwise, returns None. /// Otherwise, returns None.
pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{ pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
match self { match self {
&Object(ref map) => map.get(key), &Json::Object(ref map) => map.get(key),
_ => None _ => None
} }
} }
@ -924,7 +923,7 @@ impl Json {
/// or the Json value is not an Object, returns None. /// or the Json value is not an Object, returns None.
pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> { pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
match self { match self {
&Object(ref map) => { &Json::Object(ref map) => {
match map.get(key) { match map.get(key) {
Some(json_value) => Some(json_value), Some(json_value) => Some(json_value),
None => { None => {
@ -949,9 +948,9 @@ impl Json {
/// If the Json value is an Object, returns the associated TreeMap. /// If the Json value is an Object, returns the associated TreeMap.
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_object<'a>(&'a self) -> Option<&'a JsonObject> { pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
match self { match self {
&Object(ref map) => Some(map), &Json::Object(ref map) => Some(map),
_ => None _ => None
} }
} }
@ -963,9 +962,9 @@ impl Json {
/// If the Json value is an Array, returns the associated vector. /// If the Json value is an Array, returns the associated vector.
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_array<'a>(&'a self) -> Option<&'a JsonArray> { pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
match self { match self {
&Array(ref array) => Some(&*array), &Json::Array(ref array) => Some(&*array),
_ => None _ => None
} }
} }
@ -979,7 +978,7 @@ impl Json {
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_string<'a>(&'a self) -> Option<&'a str> { pub fn as_string<'a>(&'a self) -> Option<&'a str> {
match *self { match *self {
String(ref s) => Some(s.as_slice()), Json::String(ref s) => Some(s.as_slice()),
_ => None _ => None
} }
} }
@ -987,7 +986,7 @@ impl Json {
/// Returns true if the Json value is a Number. Returns false otherwise. /// Returns true if the Json value is a Number. Returns false otherwise.
pub fn is_number(&self) -> bool { pub fn is_number(&self) -> bool {
match *self { match *self {
I64(_) | U64(_) | F64(_) => true, Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
_ => false, _ => false,
} }
} }
@ -995,7 +994,7 @@ impl Json {
/// Returns true if the Json value is a i64. Returns false otherwise. /// Returns true if the Json value is a i64. Returns false otherwise.
pub fn is_i64(&self) -> bool { pub fn is_i64(&self) -> bool {
match *self { match *self {
I64(_) => true, Json::I64(_) => true,
_ => false, _ => false,
} }
} }
@ -1003,7 +1002,7 @@ impl Json {
/// Returns true if the Json value is a u64. Returns false otherwise. /// Returns true if the Json value is a u64. Returns false otherwise.
pub fn is_u64(&self) -> bool { pub fn is_u64(&self) -> bool {
match *self { match *self {
U64(_) => true, Json::U64(_) => true,
_ => false, _ => false,
} }
} }
@ -1011,7 +1010,7 @@ impl Json {
/// Returns true if the Json value is a f64. Returns false otherwise. /// Returns true if the Json value is a f64. Returns false otherwise.
pub fn is_f64(&self) -> bool { pub fn is_f64(&self) -> bool {
match *self { match *self {
F64(_) => true, Json::F64(_) => true,
_ => false, _ => false,
} }
} }
@ -1020,8 +1019,8 @@ impl Json {
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_i64(&self) -> Option<i64> { pub fn as_i64(&self) -> Option<i64> {
match *self { match *self {
I64(n) => Some(n), Json::I64(n) => Some(n),
U64(n) => num::cast(n), Json::U64(n) => num::cast(n),
_ => None _ => None
} }
} }
@ -1030,8 +1029,8 @@ impl Json {
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_u64(&self) -> Option<u64> { pub fn as_u64(&self) -> Option<u64> {
match *self { match *self {
I64(n) => num::cast(n), Json::I64(n) => num::cast(n),
U64(n) => Some(n), Json::U64(n) => Some(n),
_ => None _ => None
} }
} }
@ -1040,9 +1039,9 @@ impl Json {
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_f64(&self) -> Option<f64> { pub fn as_f64(&self) -> Option<f64> {
match *self { match *self {
I64(n) => num::cast(n), Json::I64(n) => num::cast(n),
U64(n) => num::cast(n), Json::U64(n) => num::cast(n),
F64(n) => Some(n), Json::F64(n) => Some(n),
_ => None _ => None
} }
} }
@ -1056,7 +1055,7 @@ impl Json {
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_boolean(&self) -> Option<bool> { pub fn as_boolean(&self) -> Option<bool> {
match self { match self {
&Boolean(b) => Some(b), &Json::Boolean(b) => Some(b),
_ => None _ => None
} }
} }
@ -1070,7 +1069,7 @@ impl Json {
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_null(&self) -> Option<()> { pub fn as_null(&self) -> Option<()> {
match self { match self {
&Null => Some(()), &Json::Null => Some(()),
_ => None _ => None
} }
} }
@ -1085,7 +1084,7 @@ impl<'a> ops::Index<&'a str, Json> for Json {
impl ops::Index<uint, Json> for Json { impl ops::Index<uint, Json> for Json {
fn index<'a>(&'a self, idx: &uint) -> &'a Json { fn index<'a>(&'a self, idx: &uint) -> &'a Json {
match self { match self {
&Array(ref v) => v.index(idx), &Json::Array(ref v) => v.index(idx),
_ => panic!("can only index Json with uint if it is an array") _ => panic!("can only index Json with uint if it is an array")
} }
} }
@ -1844,16 +1843,16 @@ impl<T: Iterator<char>> Builder<T> {
} }
fn build_value(&mut self) -> Result<Json, BuilderError> { fn build_value(&mut self) -> Result<Json, BuilderError> {
match self.token { return match self.token {
Some(NullValue) => Ok(Null), Some(NullValue) => Ok(Json::Null),
Some(I64Value(n)) => Ok(I64(n)), Some(I64Value(n)) => Ok(Json::I64(n)),
Some(U64Value(n)) => Ok(U64(n)), Some(U64Value(n)) => Ok(Json::U64(n)),
Some(F64Value(n)) => Ok(F64(n)), Some(F64Value(n)) => Ok(Json::F64(n)),
Some(BooleanValue(b)) => Ok(Boolean(b)), Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
Some(StringValue(ref mut s)) => { Some(StringValue(ref mut s)) => {
let mut temp = string::String::new(); let mut temp = string::String::new();
swap(s, &mut temp); swap(s, &mut temp);
Ok(String(temp)) Ok(Json::String(temp))
} }
Some(Error(e)) => Err(e), Some(Error(e)) => Err(e),
Some(ArrayStart) => self.build_array(), Some(ArrayStart) => self.build_array(),
@ -1870,7 +1869,7 @@ impl<T: Iterator<char>> Builder<T> {
loop { loop {
if self.token == Some(ArrayEnd) { if self.token == Some(ArrayEnd) {
return Ok(Array(values.into_iter().collect())); return Ok(Json::Array(values.into_iter().collect()));
} }
match self.build_value() { match self.build_value() {
Ok(v) => values.push(v), Ok(v) => values.push(v),
@ -1887,7 +1886,7 @@ impl<T: Iterator<char>> Builder<T> {
loop { loop {
match self.token { match self.token {
Some(ObjectEnd) => { return Ok(Object(values)); } Some(ObjectEnd) => { return Ok(Json::Object(values)); }
Some(Error(e)) => { return Err(e); } Some(Error(e)) => { return Err(e); }
None => { break; } None => { break; }
_ => {} _ => {}
@ -1947,14 +1946,14 @@ impl Decoder {
macro_rules! expect( macro_rules! expect(
($e:expr, Null) => ({ ($e:expr, Null) => ({
match $e { match $e {
Null => Ok(()), Json::Null => Ok(()),
other => Err(ExpectedError("Null".to_string(), other => Err(ExpectedError("Null".to_string(),
format!("{}", other))) format!("{}", other)))
} }
}); });
($e:expr, $t:ident) => ({ ($e:expr, $t:ident) => ({
match $e { match $e {
$t(v) => Ok(v), Json::$t(v) => Ok(v),
other => { other => {
Err(ExpectedError(stringify!($t).to_string(), Err(ExpectedError(stringify!($t).to_string(),
format!("{}", other))) format!("{}", other)))
@ -1967,25 +1966,25 @@ macro_rules! read_primitive {
($name:ident, $ty:ty) => { ($name:ident, $ty:ty) => {
fn $name(&mut self) -> DecodeResult<$ty> { fn $name(&mut self) -> DecodeResult<$ty> {
match self.pop() { match self.pop() {
I64(f) => { Json::I64(f) => {
match num::cast(f) { match num::cast(f) {
Some(f) => Ok(f), Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_string(), format!("{}", f))), None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
} }
} }
U64(f) => { Json::U64(f) => {
match num::cast(f) { match num::cast(f) {
Some(f) => Ok(f), Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_string(), format!("{}", f))), None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
} }
} }
F64(f) => { Json::F64(f) => {
match num::cast(f) { match num::cast(f) {
Some(f) => Ok(f), Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_string(), format!("{}", f))), None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
} }
} }
String(s) => { Json::String(s) => {
// re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc) // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
// is going to have a string here, as per JSON spec. // is going to have a string here, as per JSON spec.
match std::str::from_str(s.as_slice()) { match std::str::from_str(s.as_slice()) {
@ -2021,10 +2020,10 @@ impl ::Decoder<DecoderError> for Decoder {
fn read_f64(&mut self) -> DecodeResult<f64> { fn read_f64(&mut self) -> DecodeResult<f64> {
debug!("read_f64"); debug!("read_f64");
match self.pop() { match self.pop() {
I64(f) => Ok(f as f64), Json::I64(f) => Ok(f as f64),
U64(f) => Ok(f as f64), Json::U64(f) => Ok(f as f64),
F64(f) => Ok(f), Json::F64(f) => Ok(f),
String(s) => { Json::String(s) => {
// re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc) // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
// is going to have a string here, as per JSON spec. // is going to have a string here, as per JSON spec.
match std::str::from_str(s.as_slice()) { match std::str::from_str(s.as_slice()) {
@ -2032,7 +2031,7 @@ impl ::Decoder<DecoderError> for Decoder {
None => Err(ExpectedError("Number".to_string(), s)), None => Err(ExpectedError("Number".to_string(), s)),
} }
}, },
Null => Ok(f64::NAN), Json::Null => Ok(f64::NAN),
value => Err(ExpectedError("Number".to_string(), format!("{}", value))) value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
} }
} }
@ -2073,10 +2072,10 @@ impl ::Decoder<DecoderError> for Decoder {
-> DecodeResult<T> { -> DecodeResult<T> {
debug!("read_enum_variant(names={})", names); debug!("read_enum_variant(names={})", names);
let name = match self.pop() { let name = match self.pop() {
String(s) => s, Json::String(s) => s,
Object(mut o) => { Json::Object(mut o) => {
let n = match o.remove(&"variant".to_string()) { let n = match o.remove(&"variant".to_string()) {
Some(String(s)) => s, Some(Json::String(s)) => s,
Some(val) => { Some(val) => {
return Err(ExpectedError("String".to_string(), format!("{}", val))) return Err(ExpectedError("String".to_string(), format!("{}", val)))
} }
@ -2085,7 +2084,7 @@ impl ::Decoder<DecoderError> for Decoder {
} }
}; };
match o.remove(&"fields".to_string()) { match o.remove(&"fields".to_string()) {
Some(Array(l)) => { Some(Json::Array(l)) => {
for field in l.into_iter().rev() { for field in l.into_iter().rev() {
self.stack.push(field); self.stack.push(field);
} }
@ -2158,7 +2157,7 @@ impl ::Decoder<DecoderError> for Decoder {
None => { None => {
// Add a Null and try to parse it as an Option<_> // Add a Null and try to parse it as an Option<_>
// to get None as a default value. // to get None as a default value.
self.stack.push(Null); self.stack.push(Json::Null);
match f(self) { match f(self) {
Ok(x) => x, Ok(x) => x,
Err(_) => return Err(MissingFieldError(name.to_string())), Err(_) => return Err(MissingFieldError(name.to_string())),
@ -2169,7 +2168,7 @@ impl ::Decoder<DecoderError> for Decoder {
try!(f(self)) try!(f(self))
} }
}; };
self.stack.push(Object(obj)); self.stack.push(Json::Object(obj));
Ok(value) Ok(value)
} }
@ -2214,7 +2213,7 @@ impl ::Decoder<DecoderError> for Decoder {
fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> { fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
debug!("read_option()"); debug!("read_option()");
match self.pop() { match self.pop() {
Null => f(self, false), Json::Null => f(self, false),
value => { self.stack.push(value); f(self, true) } value => { self.stack.push(value); f(self, true) }
} }
} }
@ -2242,7 +2241,7 @@ impl ::Decoder<DecoderError> for Decoder {
let len = obj.len(); let len = obj.len();
for (key, value) in obj.into_iter() { for (key, value) in obj.into_iter() {
self.stack.push(value); self.stack.push(value);
self.stack.push(String(key)); self.stack.push(Json::String(key));
} }
f(self, len) f(self, len)
} }
@ -2273,7 +2272,7 @@ pub trait ToJson for Sized? {
macro_rules! to_json_impl_i64( macro_rules! to_json_impl_i64(
($($t:ty), +) => ( ($($t:ty), +) => (
$(impl ToJson for $t { $(impl ToJson for $t {
fn to_json(&self) -> Json { I64(*self as i64) } fn to_json(&self) -> Json { Json::I64(*self as i64) }
})+ })+
) )
) )
@ -2283,7 +2282,7 @@ to_json_impl_i64!(int, i8, i16, i32, i64)
macro_rules! to_json_impl_u64( macro_rules! to_json_impl_u64(
($($t:ty), +) => ( ($($t:ty), +) => (
$(impl ToJson for $t { $(impl ToJson for $t {
fn to_json(&self) -> Json { U64(*self as u64) } fn to_json(&self) -> Json { Json::U64(*self as u64) }
})+ })+
) )
) )
@ -2301,26 +2300,26 @@ impl ToJson for f32 {
impl ToJson for f64 { impl ToJson for f64 {
fn to_json(&self) -> Json { fn to_json(&self) -> Json {
match self.classify() { match self.classify() {
FPNaN | FPInfinite => Null, FPNaN | FPInfinite => Json::Null,
_ => F64(*self) _ => Json::F64(*self)
} }
} }
} }
impl ToJson for () { impl ToJson for () {
fn to_json(&self) -> Json { Null } fn to_json(&self) -> Json { Json::Null }
} }
impl ToJson for bool { impl ToJson for bool {
fn to_json(&self) -> Json { Boolean(*self) } fn to_json(&self) -> Json { Json::Boolean(*self) }
} }
impl ToJson for str { impl ToJson for str {
fn to_json(&self) -> Json { String(self.into_string()) } fn to_json(&self) -> Json { Json::String(self.into_string()) }
} }
impl ToJson for string::String { impl ToJson for string::String {
fn to_json(&self) -> Json { String((*self).clone()) } fn to_json(&self) -> Json { Json::String((*self).clone()) }
} }
macro_rules! tuple_impl { macro_rules! tuple_impl {
@ -2335,7 +2334,7 @@ macro_rules! tuple_impl {
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn to_json(&self) -> Json { fn to_json(&self) -> Json {
match *self { match *self {
($(ref $tyvar),*,) => Array(vec![$($tyvar.to_json()),*]) ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
} }
} }
} }
@ -2356,11 +2355,11 @@ tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
impl<A: ToJson> ToJson for [A] { impl<A: ToJson> ToJson for [A] {
fn to_json(&self) -> Json { Array(self.iter().map(|elt| elt.to_json()).collect()) } fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
} }
impl<A: ToJson> ToJson for Vec<A> { impl<A: ToJson> ToJson for Vec<A> {
fn to_json(&self) -> Json { Array(self.iter().map(|elt| elt.to_json()).collect()) } fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
} }
impl<A: ToJson> ToJson for TreeMap<string::String, A> { impl<A: ToJson> ToJson for TreeMap<string::String, A> {
@ -2369,7 +2368,7 @@ impl<A: ToJson> ToJson for TreeMap<string::String, A> {
for (key, value) in self.iter() { for (key, value) in self.iter() {
d.insert((*key).clone(), value.to_json()); d.insert((*key).clone(), value.to_json());
} }
Object(d) Json::Object(d)
} }
} }
@ -2379,14 +2378,14 @@ impl<A: ToJson> ToJson for HashMap<string::String, A> {
for (key, value) in self.iter() { for (key, value) in self.iter() {
d.insert((*key).clone(), value.to_json()); d.insert((*key).clone(), value.to_json());
} }
Object(d) Json::Object(d)
} }
} }
impl<A:ToJson> ToJson for Option<A> { impl<A:ToJson> ToJson for Option<A> {
fn to_json(&self) -> Json { fn to_json(&self) -> Json {
match *self { match *self {
None => Null, None => Json::Null,
Some(ref value) => value.to_json() Some(ref value) => value.to_json()
} }
} }
@ -2412,15 +2411,16 @@ mod tests {
use self::DecodeEnum::*; use self::DecodeEnum::*;
use self::test::Bencher; use self::test::Bencher;
use {Encodable, Decodable}; use {Encodable, Decodable};
use super::{Array, Encoder, Decoder, Error, Boolean, I64, U64, F64, String, Null, use super::Json::*;
PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError, use super::ErrorCode::*;
MissingFieldError, UnknownVariantError, DecodeResult, DecoderError, use super::ParserError::*;
JsonEvent, Parser, StackElement, use super::DecoderError::*;
ObjectStart, ObjectEnd, ArrayStart, ArrayEnd, BooleanValue, U64Value, use super::JsonEvent::*;
F64Value, StringValue, NullValue, SyntaxError, Key, Index, Stack, use super::ParserState::*;
InvalidSyntax, InvalidNumber, EOFWhileParsingObject, EOFWhileParsingArray, use super::StackElement::*;
EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon, use super::InternalStackElement::*;
TrailingCharacters, TrailingComma}; use super::{PrettyEncoder, Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
StackElement, Stack, Encoder, Decoder};
use std::{i64, u64, f32, f64, io}; use std::{i64, u64, f32, f64, io};
use std::collections::TreeMap; use std::collections::TreeMap;
use std::num::Float; use std::num::Float;

View file

@ -21,7 +21,7 @@ enum object {
int_value(i64), int_value(i64),
} }
fn lookup(table: json::JsonObject, key: String, default: String) -> String fn lookup(table: json::Object, key: String, default: String) -> String
{ {
match table.find(&key.to_string()) { match table.find(&key.to_string()) {
option::Some(&json::String(ref s)) => { option::Some(&json::String(ref s)) => {