common.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // SPDX-License-Identifier: AGPL-3.0-or-later
  2. //! Common types that are used in multiple modules.
  3. use std::{
  4. fmt::Display,
  5. net::{IpAddr, SocketAddr},
  6. sync::Arc,
  7. };
  8. use btlib::BlockPath;
  9. use btserde::field_helpers::smart_ptr;
  10. use serde::{Deserialize, Serialize};
  11. use crate::Result;
  12. /// Trait for messages which can be transmitted using the call method.
  13. pub trait CallMsg<'de>: Serialize + Deserialize<'de> + Send + Sync {
  14. type Reply<'r>: Serialize + Deserialize<'r> + Send;
  15. }
  16. /// Trait for messages which can be transmitted using the send method.
  17. /// Types which implement this trait should specify `()` as their reply type.
  18. pub trait SendMsg<'de>: CallMsg<'de> {}
  19. /// An address which identifies a block on the network. An instance of this struct can be
  20. /// used to get a socket address for the block this address refers to.
  21. #[derive(PartialEq, Eq, Hash, Clone, Debug, Serialize, Deserialize)]
  22. pub struct BlockAddr {
  23. #[serde(rename = "ipaddr")]
  24. ip_addr: IpAddr,
  25. #[serde(with = "smart_ptr")]
  26. path: Arc<BlockPath>,
  27. }
  28. impl BlockAddr {
  29. pub fn new(ip_addr: IpAddr, path: Arc<BlockPath>) -> Self {
  30. Self { ip_addr, path }
  31. }
  32. pub fn ip_addr(&self) -> IpAddr {
  33. self.ip_addr
  34. }
  35. pub fn path(&self) -> &Arc<BlockPath> {
  36. &self.path
  37. }
  38. fn port(&self) -> Result<u16> {
  39. self.path.port()
  40. }
  41. /// Returns the socket address of the block this instance refers to.
  42. pub fn socket_addr(&self) -> Result<SocketAddr> {
  43. Ok(SocketAddr::new(self.ip_addr, self.port()?))
  44. }
  45. }
  46. impl Display for BlockAddr {
  47. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  48. write!(f, "{}@{}", self.path, self.ip_addr)
  49. }
  50. }