field_of.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. use binrw::{binrw, BinRead, BinWrite};
  2. use diff::Diff;
  3. use std::{
  4. fmt::{Debug, Display},
  5. mem::size_of,
  6. ops::{Deref, DerefMut},
  7. };
  8. /// Wrapper to prefix arbitrary types with size of type as u32
  9. #[binrw]
  10. #[derive(Clone, Copy, Default, PartialEq)]
  11. pub struct FieldOf<T>
  12. where
  13. T: for<'a> BinRead<Args<'a> = ()>,
  14. T: for<'a> BinWrite<Args<'a> = ()>,
  15. {
  16. // Temporary variable that must match size of value
  17. #[br(temp, assert(size == size_of::<T>().try_into().unwrap()))]
  18. #[bw(try_calc(u32::try_from(size_of::<T>())))]
  19. size: u32,
  20. pub value: T,
  21. }
  22. // Custom Diff implementation to only diff internal value
  23. impl<T> Diff for FieldOf<T>
  24. where
  25. T: for<'a> BinRead<Args<'a> = ()>,
  26. T: for<'a> BinWrite<Args<'a> = ()>,
  27. T: Diff + Default,
  28. {
  29. type Repr = <T as Diff>::Repr;
  30. fn diff(&self, other: &Self) -> Self::Repr {
  31. self.value.diff(&other.value)
  32. }
  33. fn apply(&mut self, diff: &Self::Repr) {
  34. self.value.apply(diff)
  35. }
  36. fn identity() -> Self {
  37. Self {
  38. value: T::default(),
  39. }
  40. }
  41. }
  42. impl<T> Deref for FieldOf<T>
  43. where
  44. T: for<'a> BinRead<Args<'a> = ()>,
  45. T: for<'a> BinWrite<Args<'a> = ()>,
  46. {
  47. type Target = T;
  48. fn deref(&self) -> &Self::Target {
  49. &self.value
  50. }
  51. }
  52. impl<T> DerefMut for FieldOf<T>
  53. where
  54. T: for<'a> BinRead<Args<'a> = ()>,
  55. T: for<'a> BinWrite<Args<'a> = ()>,
  56. {
  57. fn deref_mut(&mut self) -> &mut Self::Target {
  58. &mut self.value
  59. }
  60. }
  61. impl<T> Debug for FieldOf<T>
  62. where
  63. T: for<'a> BinRead<Args<'a> = ()>,
  64. T: for<'a> BinWrite<Args<'a> = ()>,
  65. T: Debug,
  66. {
  67. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  68. write!(f, "{:?}", self.value)
  69. }
  70. }
  71. impl<T> Display for FieldOf<T>
  72. where
  73. T: for<'a> BinRead<Args<'a> = ()>,
  74. T: for<'a> BinWrite<Args<'a> = ()>,
  75. T: Display,
  76. {
  77. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  78. write!(f, "{}", self.value)
  79. }
  80. }
  81. impl<T> From<T> for FieldOf<T>
  82. where
  83. T: for<'a> BinRead<Args<'a> = ()>,
  84. T: for<'a> BinWrite<Args<'a> = ()>,
  85. {
  86. fn from(value: T) -> Self {
  87. Self { value }
  88. }
  89. }