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
use rmpv::decode;
use std::{error, fmt, io};

#[derive(Debug)]
pub struct CakeError(pub String);

#[derive(Debug)]
pub enum DecodeError {
  Truncated,
  Invalid,
  UnknownIo(io::Error),
}

impl DecodeError {
  fn description(&self) -> &str {
    match *self {
      DecodeError::Truncated => "could not read enough bytes to decode a complete message",
      DecodeError::UnknownIo(_) => "Unknown IO error while decoding a message",
      DecodeError::Invalid => "the byte sequence is not a valid msgpack-rpc message",
    }
  }
}

impl fmt::Display for DecodeError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
    self.description().fmt(f)
  }
}

impl error::Error for DecodeError {
  fn description(&self) -> &str {
    self.description()
  }

  fn cause(&self) -> Option<&dyn error::Error> {
    match *self {
      DecodeError::UnknownIo(ref e) => Some(e),
      _ => None,
    }
  }
}

impl From<io::Error> for DecodeError {
  fn from(err: io::Error) -> DecodeError {
    match err.kind() {
      io::ErrorKind::UnexpectedEof => DecodeError::Truncated,
      io::ErrorKind::Other => {
        if let Some(cause) = err.get_ref().unwrap().source() {
          if cause.to_string() == "type mismatch" {
            return DecodeError::Invalid;
          }
        }
        DecodeError::UnknownIo(err)
      }
      _ => DecodeError::UnknownIo(err),
    }
  }
}

impl From<decode::Error> for DecodeError {
  fn from(err: decode::Error) -> DecodeError {
    match err {
      decode::Error::InvalidMarkerRead(io_err) | decode::Error::InvalidDataRead(io_err) => {
        From::from(io_err)
      }
    }
  }
}