error.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. use std::error;
  2. use std::fmt;
  3. use std::io;
  4. use std::num;
  5. use std::str;
  6. /// A common error type for the `autocfg` crate.
  7. #[derive(Debug)]
  8. pub struct Error {
  9. kind: ErrorKind,
  10. }
  11. impl error::Error for Error {
  12. fn description(&self) -> &str {
  13. "AutoCfg error"
  14. }
  15. fn cause(&self) -> Option<&error::Error> {
  16. match self.kind {
  17. ErrorKind::Io(ref e) => Some(e),
  18. ErrorKind::Num(ref e) => Some(e),
  19. ErrorKind::Utf8(ref e) => Some(e),
  20. ErrorKind::Other(_) => None,
  21. }
  22. }
  23. }
  24. impl fmt::Display for Error {
  25. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  26. match self.kind {
  27. ErrorKind::Io(ref e) => e.fmt(f),
  28. ErrorKind::Num(ref e) => e.fmt(f),
  29. ErrorKind::Utf8(ref e) => e.fmt(f),
  30. ErrorKind::Other(s) => s.fmt(f),
  31. }
  32. }
  33. }
  34. #[derive(Debug)]
  35. enum ErrorKind {
  36. Io(io::Error),
  37. Num(num::ParseIntError),
  38. Utf8(str::Utf8Error),
  39. Other(&'static str),
  40. }
  41. pub fn from_io(e: io::Error) -> Error {
  42. Error {
  43. kind: ErrorKind::Io(e),
  44. }
  45. }
  46. pub fn from_num(e: num::ParseIntError) -> Error {
  47. Error {
  48. kind: ErrorKind::Num(e),
  49. }
  50. }
  51. pub fn from_utf8(e: str::Utf8Error) -> Error {
  52. Error {
  53. kind: ErrorKind::Utf8(e),
  54. }
  55. }
  56. pub fn from_str(s: &'static str) -> Error {
  57. Error {
  58. kind: ErrorKind::Other(s),
  59. }
  60. }