Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hubbleprotocol/struct-arithmetic-macros
https://github.com/hubbleprotocol/struct-arithmetic-macros
Last synced: 14 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/hubbleprotocol/struct-arithmetic-macros
- Owner: hubbleprotocol
- Created: 2021-10-10T20:40:08.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2022-02-24T10:47:51.000Z (almost 3 years ago)
- Last Synced: 2024-12-21T22:50:33.213Z (about 1 month ago)
- Language: Rust
- Size: 28.3 KB
- Stars: 0
- Watchers: 4
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Struct arithmetic derive
```rs
#[derive(StructArithmetic)]
struct TokenMap {
pub sol: u64,
pub eth: u64,
pub btc: u64,
}
```turns into
```rs
struct TokenMap {
pub sol: u64,
pub eth: u64,
pub btc: u64,
}
impl TokenMap {
pub fn new(sol: u64, eth: u64, btc: u64) -> TokenMap {
TokenMap {
sol,
eth,
btc,
}
}
pub fn add(&self, other: TokenMap) -> TokenMap {
TokenMap::new(
sol: self.sol.checked_add(other.sol).unwrap(),
eth: self.eth.checked_add(other.eth).unwrap(),
btc: self.btc.checked_add(other.btc).unwrap(),
)
}
pub fn add_assign(&mut self, other: TokenMap) {
self.sol = self.sol.checked_sub(other.sol).unwrap();
self.eth = self.eth.checked_sub(other.eth).unwrap();
self.btc = self.btc.checked_sub(other.btc).unwrap();
}
...
}
```## You can also add a `_reserved` field (only with type [u8; N]!) which does not interfere with the arithmetics.
```rs
#[derive(StructArithmetic)]
struct TokenMap {
pub sol: u64,
pub eth: u64,
pub btc: u64,
pub _reserved: [u8; 100],
}
```turns into
```rs
struct TokenMap {
pub sol: u64,
pub eth: u64,
pub btc: u64,
pub _reserved: [u8; 100],
}
impl TokenMap {
pub fn new(sol: u64, eth: u64, btc: u64) -> TokenMap {
TokenMap {
sol,
eth,
btc,
_reserved: [0; 100],
}
}
pub fn add(&self, other: TokenMap) -> TokenMap {
TokenMap::new(
sol: self.sol.checked_add(other.sol).unwrap(),
eth: self.eth.checked_add(other.eth).unwrap(),
btc: self.btc.checked_add(other.btc).unwrap(),
)
}
pub fn add_assign(&mut self, other: TokenMap) {
self.sol = self.sol.checked_sub(other.sol).unwrap();
self.eth = self.eth.checked_sub(other.eth).unwrap();
self.btc = self.btc.checked_sub(other.btc).unwrap();
}
...
```