builder.rs 896 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use std::{fmt::Debug, marker::PhantomData};
  2. pub trait Build<C> {
  3. fn build(code: C, msg: String) -> Self;
  4. }
  5. #[allow(dead_code)]
  6. pub struct Builder<C, O> {
  7. pub code: C,
  8. pub msg: Option<String>,
  9. phantom: PhantomData<O>,
  10. }
  11. impl<C, O> Builder<C, O>
  12. where
  13. C: Debug,
  14. O: Build<C> + Build<C>,
  15. {
  16. pub fn new(code: C) -> Self {
  17. Builder {
  18. code,
  19. msg: None,
  20. phantom: PhantomData,
  21. }
  22. }
  23. pub fn msg<M>(mut self, msg: M) -> Self
  24. where
  25. M: Into<String>,
  26. {
  27. self.msg = Some(msg.into());
  28. self
  29. }
  30. pub fn error<Err>(mut self, err: Err) -> Self
  31. where
  32. Err: std::fmt::Debug,
  33. {
  34. self.msg = Some(format!("{:?}", err));
  35. self
  36. }
  37. pub fn build(mut self) -> O {
  38. let msg = self.msg.take().unwrap_or("".to_owned());
  39. O::build(self.code, msg)
  40. }
  41. }