cosmos-sdk/types/mapcoins.go
Dev Ojha b73c17cb9c
perf: Add a map coins struct to speedup bank genesis (#15764)
Co-authored-by: Aleksandr Bezobchuk <alexanderbez@users.noreply.github.com>
Co-authored-by: Marko <marbar3778@yahoo.com>
2023-04-24 09:51:37 +00:00

43 lines
921 B
Go

package types
// map coins is a map representation of sdk.Coins
// intended solely for use in bulk additions.
// All serialization and iteration should be done after conversion to sdk.Coins.
type MapCoins map[string]Int
func NewMapCoins(coins Coins) MapCoins {
m := make(MapCoins, len(coins))
m.Add(coins...)
return m
}
func (m MapCoins) Add(coins ...Coin) {
for _, coin := range coins {
existAmt, exists := m[coin.Denom]
// TODO: Once int supports in-place arithmetic, switch this to be in-place.
if exists {
m[coin.Denom] = existAmt.Add(coin.Amount)
} else {
m[coin.Denom] = coin.Amount
}
}
}
func (m MapCoins) ToCoins() Coins {
if len(m) == 0 {
return Coins{}
}
coins := make(Coins, 0, len(m))
for denom, amount := range m {
if amount.IsZero() {
continue
}
coins = append(coins, NewCoin(denom, amount))
}
if len(coins) == 0 {
return Coins{}
}
coins.Sort()
return coins
}