Reformat using rustfmt

This commit is contained in:
Thinkofdeath 2015-10-07 19:36:59 +01:00
parent 46adad0555
commit d9e9ddc2b2
3 changed files with 186 additions and 130 deletions

View File

@ -139,7 +139,7 @@ pub trait Serializable: Sized {
} }
impl Serializable for Vec<u8> { impl Serializable for Vec<u8> {
fn read_from(buf: &mut io::Read) -> Result<Vec<u8> , io::Error> { fn read_from(buf: &mut io::Read) -> Result<Vec<u8>, io::Error> {
let mut v = Vec::new(); let mut v = Vec::new();
try!(buf.read_to_end(&mut v)); try!(buf.read_to_end(&mut v));
Ok(v) Ok(v)
@ -206,7 +206,7 @@ impl Serializable for format::Component {
let len = try!(VarInt::read_from(buf)).0; let len = try!(VarInt::read_from(buf)).0;
let mut ret = String::new(); let mut ret = String::new();
try!(buf.take(len as u64).read_to_string(&mut ret)); try!(buf.take(len as u64).read_to_string(&mut ret));
let val : serde_json::Value = serde_json::from_str(&ret[..]).unwrap(); let val: serde_json::Value = serde_json::from_str(&ret[..]).unwrap();
Result::Ok(Self::from_value(&val)) Result::Ok(Self::from_value(&val))
} }
fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> { fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> {
@ -232,7 +232,11 @@ impl Serializable for bool {
Result::Ok(try!(buf.read_u8()) != 0) Result::Ok(try!(buf.read_u8()) != 0)
} }
fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> { fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> {
try!(buf.write_u8(if *self { 1 } else { 0 })); try!(buf.write_u8(if *self {
1
} else {
0
}));
Result::Ok(()) Result::Ok(())
} }
} }
@ -321,17 +325,15 @@ impl Serializable for f64 {
pub struct UUID(u64, u64); pub struct UUID(u64, u64);
impl Default for UUID { impl Default for UUID {
fn default() -> Self { UUID(0, 0) } fn default() -> Self {
UUID(0, 0)
}
} }
impl Serializable for UUID { impl Serializable for UUID {
fn read_from(buf: &mut io::Read) -> Result<UUID, io::Error> { fn read_from(buf: &mut io::Read) -> Result<UUID, io::Error> {
Result::Ok( Result::Ok(UUID(try!(buf.read_u64::<BigEndian>()),
UUID( try!(buf.read_u64::<BigEndian>())))
try!(buf.read_u64::<BigEndian>()),
try!(buf.read_u64::<BigEndian>()),
)
)
} }
fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> { fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> {
try!(buf.write_u64::<BigEndian>(self.0)); try!(buf.write_u64::<BigEndian>(self.0));
@ -348,7 +350,7 @@ pub trait Lengthable : Serializable + Copy + Default {
pub struct LenPrefixed<L: Lengthable, V> { pub struct LenPrefixed<L: Lengthable, V> {
len: L, len: L,
pub data: Vec<V> pub data: Vec<V>,
} }
impl <L: Lengthable, V: Default> LenPrefixed<L, V> { impl <L: Lengthable, V: Default> LenPrefixed<L, V> {
@ -362,17 +364,20 @@ impl <L: Lengthable, V: Default> LenPrefixed<L, V> {
impl <L: Lengthable, V: Serializable> Serializable for LenPrefixed<L, V> { impl <L: Lengthable, V: Serializable> Serializable for LenPrefixed<L, V> {
fn read_from(buf: &mut io::Read) -> Result<LenPrefixed<L, V>, io::Error> { fn read_from(buf: &mut io::Read) -> Result<LenPrefixed<L, V>, io::Error> {
let len_data : L = try!(Serializable::read_from(buf)); let len_data: L = try!(Serializable::read_from(buf));
let len : usize = len_data.into(); let len: usize = len_data.into();
let mut data : Vec<V> = Vec::with_capacity(len); let mut data: Vec<V> = Vec::with_capacity(len);
for _ in 0 .. len { for _ in 0..len {
data.push(try!(Serializable::read_from(buf))); data.push(try!(Serializable::read_from(buf)));
} }
Result::Ok(LenPrefixed{len: len_data, data: data}) Result::Ok(LenPrefixed {
len: len_data,
data: data,
})
} }
fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> { fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> {
let len_data : L = L::from(self.data.len()); let len_data: L = L::from(self.data.len());
try!(len_data.write_to(buf)); try!(len_data.write_to(buf));
let data = &self.data; let data = &self.data;
for val in data { for val in data {
@ -387,7 +392,7 @@ impl <L: Lengthable, V: Default> Default for LenPrefixed<L, V> {
fn default() -> Self { fn default() -> Self {
LenPrefixed { LenPrefixed {
len: default::Default::default(), len: default::Default::default(),
data: default::Default::default() data: default::Default::default(),
} }
} }
} }
@ -401,7 +406,7 @@ impl <L: Lengthable, V: fmt::Debug> fmt::Debug for LenPrefixed<L, V> {
// Optimization // Optimization
pub struct LenPrefixedBytes<L: Lengthable> { pub struct LenPrefixedBytes<L: Lengthable> {
len: L, len: L,
pub data: Vec<u8> pub data: Vec<u8>,
} }
impl <L: Lengthable> LenPrefixedBytes<L> { impl <L: Lengthable> LenPrefixedBytes<L> {
@ -415,15 +420,18 @@ impl <L: Lengthable> LenPrefixedBytes<L> {
impl <L: Lengthable> Serializable for LenPrefixedBytes<L> { impl <L: Lengthable> Serializable for LenPrefixedBytes<L> {
fn read_from(buf: &mut io::Read) -> Result<LenPrefixedBytes<L>, io::Error> { fn read_from(buf: &mut io::Read) -> Result<LenPrefixedBytes<L>, io::Error> {
let len_data : L = try!(Serializable::read_from(buf)); let len_data: L = try!(Serializable::read_from(buf));
let len : usize = len_data.into(); let len: usize = len_data.into();
let mut data : Vec<u8> = Vec::with_capacity(len); let mut data: Vec<u8> = Vec::with_capacity(len);
try!(buf.take(len as u64).read_to_end(&mut data)); try!(buf.take(len as u64).read_to_end(&mut data));
Result::Ok(LenPrefixedBytes{len: len_data, data: data}) Result::Ok(LenPrefixedBytes {
len: len_data,
data: data,
})
} }
fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> { fn write_to(&self, buf: &mut io::Write) -> Result<(), io::Error> {
let len_data : L = L::from(self.data.len()); let len_data: L = L::from(self.data.len());
try!(len_data.write_to(buf)); try!(len_data.write_to(buf));
try!(buf.write_all(&self.data[..])); try!(buf.write_all(&self.data[..]));
Result::Ok(()) Result::Ok(())
@ -435,7 +443,7 @@ impl <L: Lengthable> Default for LenPrefixedBytes<L> {
fn default() -> Self { fn default() -> Self {
LenPrefixedBytes { LenPrefixedBytes {
len: default::Default::default(), len: default::Default::default(),
data: default::Default::default() data: default::Default::default(),
} }
} }
} }
@ -490,9 +498,10 @@ impl Serializable for VarInt {
loop { loop {
let b = try!(buf.read_u8()) as u32; let b = try!(buf.read_u8()) as u32;
val |= (b & PART) << (size * 7); val |= (b & PART) << (size * 7);
size+=1; size += 1;
if size > 5 { if size > 5 {
return Result::Err(io::Error::new(io::ErrorKind::InvalidInput, Error::Err("VarInt too big".to_owned()))) return Result::Err(io::Error::new(io::ErrorKind::InvalidInput,
Error::Err("VarInt too big".to_owned())))
} }
if (b & 0x80) == 0 { if (b & 0x80) == 0 {
break break
@ -518,7 +527,9 @@ impl Serializable for VarInt {
} }
impl default::Default for VarInt { impl default::Default for VarInt {
fn default() -> VarInt { VarInt(0) } fn default() -> VarInt {
VarInt(0)
}
} }
impl fmt::Debug for VarInt { impl fmt::Debug for VarInt {
@ -551,9 +562,10 @@ impl Serializable for VarLong {
loop { loop {
let b = try!(buf.read_u8()) as u64; let b = try!(buf.read_u8()) as u64;
val |= (b & PART) << (size * 7); val |= (b & PART) << (size * 7);
size+=1; size += 1;
if size > 10 { if size > 10 {
return Result::Err(io::Error::new(io::ErrorKind::InvalidInput, Error::Err("VarLong too big".to_owned()))) return Result::Err(io::Error::new(io::ErrorKind::InvalidInput,
Error::Err("VarLong too big".to_owned())))
} }
if (b & 0x80) == 0 { if (b & 0x80) == 0 {
break break
@ -579,7 +591,9 @@ impl Serializable for VarLong {
} }
impl default::Default for VarLong { impl default::Default for VarLong {
fn default() -> VarLong { VarLong(0) } fn default() -> VarLong {
VarLong(0)
}
} }
impl fmt::Debug for VarLong { impl fmt::Debug for VarLong {
@ -593,7 +607,7 @@ impl fmt::Debug for VarLong {
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub enum Direction { pub enum Direction {
Serverbound, Serverbound,
Clientbound Clientbound,
} }
/// The protocol has multiple 'sub-protocols' or states which control which /// The protocol has multiple 'sub-protocols' or states which control which
@ -603,7 +617,7 @@ pub enum State {
Handshaking, Handshaking,
Play, Play,
Status, Status,
Login Login,
} }
/// Return for any protocol related error. /// Return for any protocol related error.
@ -614,7 +628,7 @@ pub enum Error {
} }
impl convert::From<io::Error> for Error { impl convert::From<io::Error> for Error {
fn from(e : io::Error) -> Error { fn from(e: io::Error) -> Error {
Error::IOError(e) Error::IOError(e)
} }
} }
@ -629,10 +643,10 @@ impl ::std::error::Error for Error {
} }
impl ::std::fmt::Display for Error { impl ::std::fmt::Display for Error {
fn fmt(&self, f : &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match *self { match *self {
Error::Err(ref val) => write!(f, "protocol error: {}", val), Error::Err(ref val) => write!(f, "protocol error: {}", val),
Error::IOError(ref e) => e.fmt(f) Error::IOError(ref e) => e.fmt(f),
} }
} }
} }
@ -647,12 +661,12 @@ pub struct Conn {
cipher: Option<openssl::EVPCipher>, cipher: Option<openssl::EVPCipher>,
compression_threshold: i32, compression_threshold: i32,
compression_read: Option<ZlibDecoder<io::Cursor<Vec<u8>>>>, compression_read: Option<ZlibDecoder<io::Cursor<Vec<u8>>>>,
compression_write: Option<ZlibEncoder<io::Cursor<Vec<u8>>>>, compression_write: Option<ZlibEncoder<io::Cursor<Vec<u8>>>>,
} }
impl Conn { impl Conn {
pub fn new(target: &str) -> Result<Conn, Error>{ pub fn new(target: &str) -> Result<Conn, Error> {
// TODO SRV record support // TODO SRV record support
let mut parts = target.split(":").collect::<Vec<&str>>(); let mut parts = target.split(":").collect::<Vec<&str>>();
let address = if parts.len() == 1 { let address = if parts.len() == 1 {
@ -680,7 +694,11 @@ impl Conn {
try!(VarInt(packet.packet_id()).write_to(&mut buf)); try!(VarInt(packet.packet_id()).write_to(&mut buf));
try!(packet.write(&mut buf)); try!(packet.write(&mut buf));
let mut extra = if self.compression_threshold >= 0 { 1 } else { 0 }; let mut extra = if self.compression_threshold >= 0 {
1
} else {
0
};
if self.compression_threshold >= 0 && buf.len() as i32 > self.compression_threshold { if self.compression_threshold >= 0 && buf.len() as i32 > self.compression_threshold {
extra = 0; extra = 0;
let uncompressed_size = buf.len(); let uncompressed_size = buf.len();
@ -734,11 +752,14 @@ impl Conn {
let pos = buf.position() as usize; let pos = buf.position() as usize;
let ibuf = buf.into_inner(); let ibuf = buf.into_inner();
if ibuf.len() != pos { if ibuf.len() != pos {
return Result::Err(Error::Err(format!("Failed to read all of packet 0x{:X}, had {} bytes left", id, ibuf.len() - pos))) return Result::Err(Error::Err(format!("Failed to read all of packet 0x{:X}, \
had {} bytes left",
id,
ibuf.len() - pos)))
} }
Result::Ok(val) Result::Ok(val)
}, }
None => Result::Err(Error::Err("missing packet".to_owned())) None => Result::Err(Error::Err("missing packet".to_owned())),
} }
} }
@ -749,28 +770,29 @@ impl Conn {
pub fn set_compresssion(&mut self, threshold: i32, read: bool) { pub fn set_compresssion(&mut self, threshold: i32, read: bool) {
self.compression_threshold = threshold; self.compression_threshold = threshold;
if !read { if !read {
self.compression_write = Some(ZlibEncoder::new(io::Cursor::new(Vec::new()), flate2::Compression::Default)); self.compression_write = Some(ZlibEncoder::new(io::Cursor::new(Vec::new()),
flate2::Compression::Default));
} else { } else {
self.compression_read = Some(ZlibDecoder::new(io::Cursor::new(Vec::new()))); self.compression_read = Some(ZlibDecoder::new(io::Cursor::new(Vec::new())));
} }
} }
pub fn do_status(mut self) -> Result<(Status, time::Duration), Error>{ pub fn do_status(mut self) -> Result<(Status, time::Duration), Error> {
use serde_json::Value; use serde_json::Value;
use self::packet::status::serverbound::*; use self::packet::status::serverbound::*;
use self::packet::handshake::serverbound::*; use self::packet::handshake::serverbound::*;
use self::packet::Packet; use self::packet::Packet;
let host = self.host.clone(); let host = self.host.clone();
let port = self.port; let port = self.port;
try!(self.write_packet(Handshake{ try!(self.write_packet(Handshake {
protocol_version: VarInt(SUPPORTED_PROTOCOL), protocol_version: VarInt(SUPPORTED_PROTOCOL),
host: host, host: host,
port: port, port: port,
next: VarInt(1), next: VarInt(1),
})); }));
self.state = State::Status; self.state = State::Status;
try!(self.write_packet(StatusRequest{empty: ()})); try!(self.write_packet(StatusRequest { empty: () }));
let status = if let Packet::StatusResponse(res) = try!(self.read_packet()) { let status = if let Packet::StatusResponse(res) = try!(self.read_packet()) {
res.status res.status
@ -779,7 +801,7 @@ impl Conn {
}; };
let start = time::now(); let start = time::now();
try!(self.write_packet(StatusPing{ping: 42})); try!(self.write_packet(StatusPing { ping: 42 }));
if let Packet::StatusPong(_) = try!(self.read_packet()) { if let Packet::StatusPong(_) = try!(self.read_packet()) {
} else { } else {
@ -800,17 +822,26 @@ impl Conn {
Ok((Status { Ok((Status {
version: StatusVersion { version: StatusVersion {
name: try!(version.find("name").and_then(Value::as_string).ok_or(invalid_status())).to_owned(), name: try!(version.find("name").and_then(Value::as_string).ok_or(invalid_status()))
protocol: try!(version.find("protocol").and_then(Value::as_i64).ok_or(invalid_status())) as i32, .to_owned(),
protocol: try!(version.find("protocol")
.and_then(Value::as_i64)
.ok_or(invalid_status())) as i32,
}, },
players: StatusPlayers { players: StatusPlayers {
max: try!(players.find("max").and_then(Value::as_i64).ok_or(invalid_status())) as i32, max: try!(players.find("max")
online: try!(players.find("online").and_then(Value::as_i64).ok_or(invalid_status())) as i32, .and_then(Value::as_i64)
sample: Vec::new(), // TODO .ok_or(invalid_status())) as i32,
online: try!(players.find("online")
.and_then(Value::as_i64)
.ok_or(invalid_status())) as i32,
sample: Vec::new(), /* TODO */
}, },
description: format::Component::from_value(try!(val.find("description").ok_or(invalid_status()))), description: format::Component::from_value(try!(val.find("description")
.ok_or(invalid_status()))),
favicon: val.find("favicon").and_then(Value::as_string).map(|v| v.to_owned()), favicon: val.find("favicon").and_then(Value::as_string).map(|v| v.to_owned()),
}, ping)) },
ping))
} }
} }
@ -848,11 +879,11 @@ impl Read for Conn {
Option::Some(cipher) => { Option::Some(cipher) => {
let ret = try!(self.stream.read(buf)); let ret = try!(self.stream.read(buf));
let data = cipher.decrypt(&buf[..ret]); let data = cipher.decrypt(&buf[..ret]);
for i in 0 .. ret { for i in 0..ret {
buf[i] = data[i]; buf[i] = data[i];
} }
Ok(ret) Ok(ret)
}, }
} }
} }
} }
@ -865,7 +896,7 @@ impl Write for Conn {
let data = cipher.encrypt(buf); let data = cipher.encrypt(buf);
try!(self.stream.write_all(&data[..])); try!(self.stream.write_all(&data[..]));
Ok(buf.len()) Ok(buf.len())
}, }
} }
} }
@ -901,14 +932,16 @@ pub trait PacketType: Sized {
pub fn test() { pub fn test() {
let mut c = Conn::new("localhost:25565").unwrap(); let mut c = Conn::new("localhost:25565").unwrap();
c.write_packet(packet::handshake::serverbound::Handshake{ c.write_packet(packet::handshake::serverbound::Handshake {
protocol_version: VarInt(71), protocol_version: VarInt(71),
host: "localhost".to_owned(), host: "localhost".to_owned(),
port: 25565, port: 25565,
next: VarInt(2), next: VarInt(2),
}).unwrap(); })
.unwrap();
c.state = State::Login; c.state = State::Login;
c.write_packet(packet::login::serverbound::LoginStart{username: "Think".to_owned()}).unwrap(); c.write_packet(packet::login::serverbound::LoginStart { username: "Think".to_owned() })
.unwrap();
let packet = match c.read_packet().unwrap() { let packet = match c.read_packet().unwrap() {
packet::Packet::EncryptionRequest(val) => val, packet::Packet::EncryptionRequest(val) => val,
@ -921,18 +954,19 @@ pub fn test() {
let shared_e = key.encrypt(&shared); let shared_e = key.encrypt(&shared);
let token_e = key.encrypt(&packet.verify_token.data); let token_e = key.encrypt(&packet.verify_token.data);
let profile = mojang::Profile{ let profile = mojang::Profile {
username: "Think".to_owned(), username: "Think".to_owned(),
id: "b1184d43168441cfa2128b9a3df3b6ab".to_owned(), id: "b1184d43168441cfa2128b9a3df3b6ab".to_owned(),
access_token: "".to_owned() access_token: "".to_owned(),
}; };
profile.join_server(&packet.server_id, &shared, &packet.public_key.data); profile.join_server(&packet.server_id, &shared, &packet.public_key.data);
c.write_packet(packet::login::serverbound::EncryptionResponse{ c.write_packet(packet::login::serverbound::EncryptionResponse {
shared_secret: LenPrefixedBytes::new(shared_e), shared_secret: LenPrefixedBytes::new(shared_e),
verify_token: LenPrefixedBytes::new(token_e), verify_token: LenPrefixedBytes::new(token_e),
}).unwrap(); })
.unwrap();
let mut read = c.clone(); let mut read = c.clone();
let mut write = c.clone(); let mut write = c.clone();
@ -940,35 +974,39 @@ pub fn test() {
read.enable_encyption(&shared, true); read.enable_encyption(&shared, true);
write.enable_encyption(&shared, false); write.enable_encyption(&shared, false);
loop { match read.read_packet().unwrap() { loop {
packet::Packet::LoginDisconnect(val) => { match read.read_packet().unwrap() {
panic!("Discconect {}", val.reason); packet::Packet::LoginDisconnect(val) => {
}, panic!("Discconect {}", val.reason);
packet::Packet::SetInitialCompression(val) => { }
read.set_compresssion(val.threshold.0, true); packet::Packet::SetInitialCompression(val) => {
write.set_compresssion(val.threshold.0, false); read.set_compresssion(val.threshold.0, true);
println!("Compression: {}", val.threshold.0) write.set_compresssion(val.threshold.0, false);
}, println!("Compression: {}", val.threshold.0)
packet::Packet::LoginSuccess(val) => { }
println!("Login: {} {}", val.username, val.uuid); packet::Packet::LoginSuccess(val) => {
read.state = State::Play; println!("Login: {} {}", val.username, val.uuid);
write.state = State::Play; read.state = State::Play;
break; write.state = State::Play;
break;
}
_ => panic!("Unknown packet"),
} }
_ => panic!("Unknown packet"), }
} }
let mut first = true; let mut first = true;
let mut count = 0; let mut count = 0;
loop { match read.read_packet().unwrap() { loop {
match read.read_packet().unwrap() {
packet::Packet::ServerMessage(val) => println!("MSG: {}", val.message), packet::Packet::ServerMessage(val) => println!("MSG: {}", val.message),
packet::Packet::ChunkData(_) => {}, packet::Packet::ChunkData(_) => {}
val => { val => {
println!("{:?}", val); println!("{:?}", val);
if first { if first {
write.write_packet(packet::play::serverbound::ChatMessage{ write.write_packet(packet::play::serverbound::ChatMessage {
message: "Hello world".to_owned(), message: "Hello world".to_owned(),
}).unwrap(); })
.unwrap();
first = false; first = false;
} }
count += 1; count += 1;
@ -976,7 +1014,8 @@ pub fn test() {
break; break;
} }
} }
} } }
}
unimplemented!(); unimplemented!();
} }

View File

@ -19,7 +19,7 @@ use hyper;
pub struct Profile { pub struct Profile {
pub username: String, pub username: String,
pub id: String, pub id: String,
pub access_token: String pub access_token: String,
} }
const JOIN_URL: &'static str = "https://sessionserver.mojang.com/session/minecraft/join"; const JOIN_URL: &'static str = "https://sessionserver.mojang.com/session/minecraft/join";
@ -34,7 +34,7 @@ impl Profile {
// Mojang uses a hex method which allows for // Mojang uses a hex method which allows for
// negatives so we have to account for that. // negatives so we have to account for that.
let negative = hash[0] & 0x80 == 0x80; let negative = hash[0] & 0x80 == 0x80;
if negative { if negative {
twos_compliment(&mut hash); twos_compliment(&mut hash);
} }
@ -47,17 +47,18 @@ impl Profile {
}; };
let join_msg = serde_json::builder::ObjectBuilder::new() let join_msg = serde_json::builder::ObjectBuilder::new()
.insert("accessToken", &self.access_token) .insert("accessToken", &self.access_token)
.insert("selectedProfile", &self.id) .insert("selectedProfile", &self.id)
.insert("serverId", hash_str) .insert("serverId", hash_str)
.unwrap(); .unwrap();
let join = serde_json::to_string(&join_msg).unwrap(); let join = serde_json::to_string(&join_msg).unwrap();
let client = hyper::Client::new(); let client = hyper::Client::new();
let res = client.post(JOIN_URL) let res = client.post(JOIN_URL)
.body(&join) .body(&join)
.header(hyper::header::ContentType("application/json".parse().unwrap())) .header(hyper::header::ContentType("application/json".parse().unwrap()))
.send().unwrap(); .send()
.unwrap();
let ret: serde_json::Value = match serde_json::from_reader(res) { let ret: serde_json::Value = match serde_json::from_reader(res) {
Result::Ok(val) => val, Result::Ok(val) => val,
@ -69,7 +70,7 @@ impl Profile {
fn twos_compliment(data: &mut Vec<u8>) { fn twos_compliment(data: &mut Vec<u8>) {
let mut carry = true; let mut carry = true;
for i in (0 .. data.len()).rev() { for i in (0..data.len()).rev() {
data[i] = !data[i]; data[i] = !data[i];
if carry { if carry {
carry = data[i] == 0xFF; carry = data[i] == 0xFF;

View File

@ -91,7 +91,7 @@ state_packets!(
button: u8 =, button: u8 =,
action_number: u16 =, action_number: u16 =,
mode: u8 =, mode: u8 =,
clicked_item: Option<item::Stack> =, // TODO clicked_item: Option<item::Stack> =,
} }
// CloseWindow is sent when the client closes a window. // CloseWindow is sent when the client closes a window.
CloseWindow => 0x07 { CloseWindow => 0x07 {
@ -936,7 +936,7 @@ pub struct BlockChangeRecord {
impl Serializable for BlockChangeRecord { impl Serializable for BlockChangeRecord {
fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> { fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> {
Ok(BlockChangeRecord{ Ok(BlockChangeRecord {
xz: try!(Serializable::read_from(buf)), xz: try!(Serializable::read_from(buf)),
y: try!(Serializable::read_from(buf)), y: try!(Serializable::read_from(buf)),
block_id: try!(Serializable::read_from(buf)), block_id: try!(Serializable::read_from(buf)),
@ -959,7 +959,7 @@ pub struct ExplosionRecord {
impl Serializable for ExplosionRecord { impl Serializable for ExplosionRecord {
fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> { fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> {
Ok(ExplosionRecord{ Ok(ExplosionRecord {
x: try!(Serializable::read_from(buf)), x: try!(Serializable::read_from(buf)),
y: try!(Serializable::read_from(buf)), y: try!(Serializable::read_from(buf)),
z: try!(Serializable::read_from(buf)), z: try!(Serializable::read_from(buf)),
@ -982,7 +982,7 @@ pub struct MapIcon {
impl Serializable for MapIcon { impl Serializable for MapIcon {
fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> { fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> {
Ok(MapIcon{ Ok(MapIcon {
direction_type: try!(Serializable::read_from(buf)), direction_type: try!(Serializable::read_from(buf)),
x: try!(Serializable::read_from(buf)), x: try!(Serializable::read_from(buf)),
z: try!(Serializable::read_from(buf)), z: try!(Serializable::read_from(buf)),
@ -998,7 +998,7 @@ impl Serializable for MapIcon {
impl Default for MapIcon { impl Default for MapIcon {
fn default() -> Self { fn default() -> Self {
MapIcon { MapIcon {
direction_type: 0, direction_type: 0,
x: 0, x: 0,
z: 0, z: 0,
@ -1015,7 +1015,7 @@ pub struct EntityProperty {
impl Serializable for EntityProperty { impl Serializable for EntityProperty {
fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> { fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> {
Ok(EntityProperty{ Ok(EntityProperty {
key: try!(Serializable::read_from(buf)), key: try!(Serializable::read_from(buf)),
value: try!(Serializable::read_from(buf)), value: try!(Serializable::read_from(buf)),
modifiers: try!(Serializable::read_from(buf)), modifiers: try!(Serializable::read_from(buf)),
@ -1038,7 +1038,7 @@ pub struct PropertyModifier {
impl Serializable for PropertyModifier { impl Serializable for PropertyModifier {
fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> { fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> {
Ok(PropertyModifier{ Ok(PropertyModifier {
uuid: try!(Serializable::read_from(buf)), uuid: try!(Serializable::read_from(buf)),
amount: try!(Serializable::read_from(buf)), amount: try!(Serializable::read_from(buf)),
operation: try!(Serializable::read_from(buf)), operation: try!(Serializable::read_from(buf)),
@ -1060,19 +1060,19 @@ pub struct PlayerInfoData {
impl Serializable for PlayerInfoData { impl Serializable for PlayerInfoData {
fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> { fn read_from(buf: &mut io::Read) -> Result<Self, io::Error> {
let mut m = PlayerInfoData{ let mut m = PlayerInfoData {
action: try!(Serializable::read_from(buf)), action: try!(Serializable::read_from(buf)),
players: Vec::new(), players: Vec::new(),
}; };
let len = try!(VarInt::read_from(buf)); let len = try!(VarInt::read_from(buf));
for _ in 0 .. len.0 { for _ in 0..len.0 {
let uuid = try!(UUID::read_from(buf)); let uuid = try!(UUID::read_from(buf));
match m.action.0 { match m.action.0 {
0 => { 0 => {
let name = try!(String::read_from(buf)); let name = try!(String::read_from(buf));
let mut props = Vec::new(); let mut props = Vec::new();
let plen = try!(VarInt::read_from(buf)).0; let plen = try!(VarInt::read_from(buf)).0;
for _ in 0 .. plen { for _ in 0..plen {
let mut prop = PlayerProperty { let mut prop = PlayerProperty {
name: try!(String::read_from(buf)), name: try!(String::read_from(buf)),
value: try!(String::read_from(buf)), value: try!(String::read_from(buf)),
@ -1098,21 +1098,21 @@ impl Serializable for PlayerInfoData {
}, },
}; };
m.players.push(p); m.players.push(p);
}, }
1 => { 1 => {
m.players.push(PlayerDetail::UpdateGamemode{ m.players.push(PlayerDetail::UpdateGamemode {
uuid: uuid, uuid: uuid,
gamemode: try!(Serializable::read_from(buf)), gamemode: try!(Serializable::read_from(buf)),
}) })
}, }
2 => { 2 => {
m.players.push(PlayerDetail::UpdateLatency{ m.players.push(PlayerDetail::UpdateLatency {
uuid: uuid, uuid: uuid,
ping: try!(Serializable::read_from(buf)), ping: try!(Serializable::read_from(buf)),
}) })
}, }
3 => { 3 => {
m.players.push(PlayerDetail::UpdateDisplayName{ m.players.push(PlayerDetail::UpdateDisplayName {
uuid: uuid, uuid: uuid,
display: { display: {
if try!(bool::read_from(buf)) { if try!(bool::read_from(buf)) {
@ -1122,12 +1122,10 @@ impl Serializable for PlayerInfoData {
} }
}, },
}) })
}, }
4 => { 4 => {
m.players.push(PlayerDetail::Remove{ m.players.push(PlayerDetail::Remove { uuid: uuid })
uuid: uuid, }
})
},
_ => panic!(), _ => panic!(),
} }
} }
@ -1150,11 +1148,29 @@ impl Default for PlayerInfoData {
#[derive(Debug)] #[derive(Debug)]
pub enum PlayerDetail { pub enum PlayerDetail {
Add{uuid: UUID, name: String, properties: Vec<PlayerProperty>, gamemode: VarInt, ping: VarInt, display: Option<format::Component>}, Add {
UpdateGamemode{uuid: UUID, gamemode: VarInt}, uuid: UUID,
UpdateLatency{uuid: UUID, ping: VarInt}, name: String,
UpdateDisplayName{uuid: UUID, display: Option<format::Component>}, properties: Vec<PlayerProperty>,
Remove{uuid: UUID}, gamemode: VarInt,
ping: VarInt,
display: Option<format::Component>,
},
UpdateGamemode {
uuid: UUID,
gamemode: VarInt,
},
UpdateLatency {
uuid: UUID,
ping: VarInt,
},
UpdateDisplayName {
uuid: UUID,
display: Option<format::Component>,
},
Remove {
uuid: UUID,
},
} }
#[derive(Debug)] #[derive(Debug)]