1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::ops::Index;
use flate2::Compression;
use flate2::read::{GzDecoder, ZlibDecoder};
use flate2::write::{GzEncoder, ZlibEncoder};
use error::{Error, Result};
use value::Value;
#[derive(Clone, Debug, PartialEq)]
pub struct Blob {
title: String,
content: Value
}
impl Blob {
pub fn new(title: String) -> Blob {
let map: HashMap<String, Value> = HashMap::new();
Blob { title: title, content: Value::Compound(map) }
}
pub fn from_reader(mut src: &mut io::Read) -> Result<Blob> {
let header = try!(Value::read_header(src));
if header.0 != 0x0a {
return Err(Error::NoRootCompound);
}
let content = try!(Value::from_reader(header.0, src));
Ok(Blob { title: header.1, content: content })
}
pub fn from_gzip(src: &mut io::Read) -> Result<Blob> {
let mut data = try!(GzDecoder::new(src));
Blob::from_reader(&mut data)
}
pub fn from_zlib(src: &mut io::Read) -> Result<Blob> {
Blob::from_reader(&mut ZlibDecoder::new(src))
}
pub fn write(&self, dst: &mut io::Write) -> Result<()> {
try!(self.content.write_header(dst, &self.title));
self.content.write(dst)
}
pub fn write_gzip(&self, dst: &mut io::Write) -> Result<()> {
self.write(&mut GzEncoder::new(dst, Compression::Default))
}
pub fn write_zlib(&self, dst: &mut io::Write) -> Result<()> {
self.write(&mut ZlibEncoder::new(dst, Compression::Default))
}
pub fn insert<V>(&mut self, name: String, value: V) -> Result<()>
where V: Into<Value> {
let nvalue = value.into();
if let Value::List(ref vals) = nvalue {
if vals.len() != 0 {
let first_id = vals[0].id();
for nbt in vals {
if nbt.id() != first_id {
return Err(Error::HeterogeneousList)
}
}
}
}
if let Value::Compound(ref mut v) = self.content {
v.insert(name, nvalue);
} else {
unreachable!();
}
Ok(())
}
pub fn len(&self) -> usize {
1 + 2 + self.title.len() + self.content.len()
}
}
impl<'a> Index<&'a str> for Blob {
type Output = Value;
fn index<'b>(&'b self, s: &'a str) -> &'b Value {
match self.content {
Value::Compound(ref v) => v.get(s).unwrap(),
_ => unreachable!()
}
}
}
impl fmt::Display for Blob {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TAG_Compound(\"{}\"): {}", self.title, self.content)
}
}