error.rs 992 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. use std::error;
  2. use std::fmt;
  3. #[derive(Debug)]
  4. pub struct Error<'a> {
  5. pub input: &'a str,
  6. pub position: usize,
  7. pub source: Box<dyn error::Error + Send>,
  8. }
  9. impl<'a> PartialEq for Error<'a> {
  10. fn eq(&self, other: &Self) -> bool {
  11. self.input == other.input && self.position == other.position
  12. }
  13. }
  14. impl<'a> error::Error for Error<'a> {
  15. fn source(&self) -> Option<&(dyn error::Error + 'static)> {
  16. Some(&*self.source)
  17. }
  18. }
  19. impl<'a> Error<'a> {
  20. pub fn position(&self) -> usize {
  21. self.position
  22. }
  23. }
  24. impl<'a> fmt::Display for Error<'a> {
  25. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  26. let space = 10;
  27. let end = std::cmp::min(self.input.len(), self.position + space);
  28. write!(
  29. f,
  30. "...'{}' | error: {} at >| '{}'...",
  31. &self.input[self.position.saturating_sub(space)..self.position],
  32. self.source,
  33. &self.input[self.position..end],
  34. )
  35. }
  36. }