/packages/fxa-email-service/src/types/mod.rs

https://github.com/mozilla/fxa · Rust · 82 lines · 66 code · 10 blank · 6 comment · 8 complexity · 28c8fcfa8ea5dc2cda0a939db5d0356a MD5 · raw file

  1. // This Source Code Form is subject to the terms of the Mozilla Public
  2. // License, v. 2.0. If a copy of the MPL was not distributed with this
  3. // file, you can obtain one at https://mozilla.org/MPL/2.0/.
  4. //! Parent scope
  5. //! for modules that implement
  6. //! miscellaneous generally-used types.
  7. macro_rules! enum_boilerplate {
  8. ($name:ident ($description:expr, $default:ident, $error:ident) {
  9. $($variant:ident => $serialization:expr,)+
  10. }) => {
  11. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
  12. pub enum $name {
  13. $($variant,
  14. )+
  15. }
  16. impl AsRef<str> for $name {
  17. fn as_ref(&self) -> &str {
  18. match *self {
  19. $($name::$variant => $serialization,
  20. )+
  21. }
  22. }
  23. }
  24. impl std::default::Default for $name {
  25. fn default() -> Self {
  26. $name::$default
  27. }
  28. }
  29. impl std::fmt::Display for $name {
  30. fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
  31. write!(formatter, "{}", self.as_ref())
  32. }
  33. }
  34. impl<'d> serde::de::Deserialize<'d> for $name {
  35. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  36. where
  37. D: serde::de::Deserializer<'d>,
  38. {
  39. let value: String = serde::de::Deserialize::deserialize(deserializer)?;
  40. std::convert::TryFrom::try_from(value.as_str())
  41. .map_err(|_| D::Error::invalid_value(serde::de::Unexpected::Str(&value), &$description))
  42. }
  43. }
  44. impl serde::ser::Serialize for $name {
  45. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  46. where
  47. S: serde::ser::Serializer,
  48. {
  49. serializer.serialize_str(self.as_ref())
  50. }
  51. }
  52. impl<'v> std::convert::TryFrom<&'v str> for $name {
  53. type Error = AppError;
  54. fn try_from(value: &str) -> Result<Self, Self::Error> {
  55. match value {
  56. $($serialization => Ok($name::$variant),
  57. )+
  58. _ => Err(AppErrorKind::$error(value.to_owned()))?,
  59. }
  60. }
  61. }
  62. }
  63. }
  64. pub mod duration;
  65. pub mod email_address;
  66. pub mod env;
  67. pub mod error;
  68. pub mod headers;
  69. pub mod logging;
  70. pub mod provider;
  71. pub mod regex;
  72. pub mod validate;