Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. mod msg {
  2. pub const ERR_ARG_NOT_CONVERTIBLE_TO_UTF_8: &str =
  3. "Error: Supplied command-line argument not convertible to UTF-8";
  4. }
  5.  
  6. /// THEN: The verbose way
  7. mod error_verbose {
  8. use crate::msg;
  9. use std::{
  10. ffi::OsString,
  11. fmt::{Display, Formatter, Result as FmtResult},
  12. };
  13.  
  14. #[derive(Debug, PartialEq)]
  15. pub enum Error {
  16. ArgNotConvertibleToUtf8(OsString),
  17. }
  18.  
  19. impl Display for Error {
  20. fn fmt(&self, f: &mut Formatter) -> FmtResult {
  21. write!(
  22. f,
  23. "{}",
  24. match self {
  25. Error::ArgNotConvertibleToUtf8(os_string) => {
  26. format!("{}: {:?}", msg::ERR_ARG_NOT_CONVERTIBLE_TO_UTF_8, os_string)
  27. }
  28. }
  29. )
  30. }
  31. }
  32.  
  33. impl From<OsString> for Error {
  34. fn from(err: OsString) -> Self {
  35. Error::ArgNotConvertibleToUtf8(err)
  36. }
  37. }
  38. }
  39.  
  40. /// NOW: The succinct way
  41. mod error {
  42. use crate::msg;
  43. use derive_more::*;
  44.  
  45. #[derive(Debug, Display, From, PartialEq)]
  46. pub enum Error {
  47. #[display(fmt = "{}: {:?}", "msg::ERR_ARG_NOT_CONVERTIBLE_TO_UTF_8", "_0")]
  48. // Optional; use literal or `const` args; `_0` means `self.0`
  49. ArgNotConvertibleToUtf8(std::ffi::OsString, Context),
  50. }
  51.  
  52. impl std::error::Error for Error {}
  53.  
  54. pub enum Context {
  55. Transfer(/* Sender, Recipient, Amount, Date, etc. etc. etc. */),
  56. Mint,
  57. Smelt,
  58. SomeOtherContext,
  59. }
  60. }
  61.  
  62. use std::result::Result as StdResult;
  63. /// Take your pick: `Error` definitions are identical
  64. type Result<T> = StdResult<T, error::Error>;
  65. //type Result<T> = StdResult<T, error_verbose::Error>;
  66.  
  67. fn main() -> Result<()> {
  68. /// Will yield `Error::ArgNotConvertibleToUtf8(OsString)`
  69. /// whenever `OsString` cannot be converted to valid UTF-8 (as per below)
  70. let _some_arg = std::ffi::OsString::from_vec(vec![b'\xc3', b'\x28'])
  71. .into_string()
  72. .map_err(|e| (e, Context::Transfer()))?;
  73.  
  74. /* ... do some processing ... */
  75.  
  76. Ok(())
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement