payment.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. use crate::{id::Error, RevisionId};
  2. use serde::{de, Serialize, Serializer};
  3. use std::{fmt, ops::Deref, str::FromStr};
  4. #[derive(Clone, Debug, Eq, Ord, Hash, PartialOrd, PartialEq)]
  5. /// PaymentID
  6. ///
  7. /// This is the payment ID. The payment ID has two public members, which is
  8. /// basically the transaction which created this payment and the position in the
  9. /// transaction.
  10. pub struct PaymentId {
  11. /// Transaction which created this payment
  12. pub transaction: RevisionId,
  13. /// This payment position inside the transaction
  14. pub position: u16,
  15. }
  16. impl FromStr for PaymentId {
  17. type Err = Error;
  18. fn from_str(s: &str) -> Result<Self, Self::Err> {
  19. let parts: Vec<&str> = s.split(':').collect();
  20. if parts.len() != 2 {
  21. return Err(Error::InvalidLength(
  22. "payment_id".to_owned(),
  23. 2,
  24. parts.len(),
  25. ));
  26. }
  27. let transaction = parts[0].try_into()?;
  28. let position = parts[1].parse()?;
  29. Ok(PaymentId {
  30. transaction,
  31. position,
  32. })
  33. }
  34. }
  35. impl PaymentId {
  36. /// Returns the bytes representation of the PaymentId
  37. pub fn bytes(&self) -> [u8; 34] {
  38. let mut bytes = [0u8; 34];
  39. bytes[0..32].copy_from_slice(self.transaction.deref());
  40. bytes[32..34].copy_from_slice(&self.position.to_be_bytes());
  41. bytes
  42. }
  43. }
  44. impl Serialize for PaymentId {
  45. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  46. where
  47. S: Serializer,
  48. {
  49. let serialized = self.to_string();
  50. serializer.serialize_str(&serialized)
  51. }
  52. }
  53. impl ToString for PaymentId {
  54. fn to_string(&self) -> String {
  55. format!("{}:{}", self.transaction, self.position)
  56. }
  57. }
  58. struct PaymentIdVisitor;
  59. impl<'de> de::Visitor<'de> for PaymentIdVisitor {
  60. type Value = PaymentId;
  61. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  62. formatter.write_str("a string in the format 'transaction_id:position'")
  63. }
  64. fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
  65. where
  66. E: de::Error,
  67. {
  68. value
  69. .parse()
  70. .map_err(|e: Error| E::custom(format!("Invalid payment ID: {}", e)))
  71. }
  72. }
  73. impl<'de> de::Deserialize<'de> for PaymentId {
  74. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  75. where
  76. D: de::Deserializer<'de>,
  77. {
  78. deserializer.deserialize_str(PaymentIdVisitor)
  79. }
  80. }