How do you set, clear and toggle a single bit in Sway?

Hey guys
In progress of refactoring and optimisation my sway lend contarct I decided to storage info about user’s collaterals like compound do

I wrote a working prototype code on rust and test it

fn toggle(mut num: u16, index: u16) -> u16 {
    num ^= 1 << index;
    num
}
fn set_bit(mut assets_in: u16, asset_offset: u16) -> u16 {
    assets_in |= 1 << asset_offset;
    assets_in
}
fn clear_bit(mut assets_in: u16, asset_offset: u16) -> u16 {
    assets_in &= !(1 << asset_offset);
    assets_in
}

fn is_in_asset(assets_in: u16, asset_offset: u8) -> bool {
    assets_in & (1 << asset_offset) != 0
}

But when I’m trying to use in sway I have errors like

error
   --> /Users/alexey/projects/fuel/sway-lend/contracts/market/src/main.sw:167:24
    |
165 | 
166 |             // set bit for asset
167 |             assets_in ^= 1 << asset_offset;
    |                        ^ Expected an expression.
168 |             storage.supplied_collateral_assets.get(account, assets_in);
169 |         } else if initial_user_balance != 0 && final_user_balance == 0 {
    |

Or

error
   --> /Users/alexey/projects/fuel/sway-lend/contracts/market/src/main.sw:167:24
    |
165 | 
166 |             // set bit for asset
167 |             assets_in |= 1 << asset_offset;
    |                        ^ Expected an expression.
168 |             storage.supplied_collateral_assets.get(account, assets_in);
169 |         } else if initial_user_balance != 0 && final_user_balance == 0 {

and

error
   --> /Users/alexey/projects/fuel/sway-lend/contracts/market/src/main.sw:171:24
    |
169 | 
170 |             // clear bit for asset
171 |             assets_in &= !(1 << asset_offset);
    |                        ^ Expected an expression.
172 |             storage.supplied_collateral_assets.get(account, assets_in);
173 |         }
    |
____

Please tell me how to use these operators in sway
And please help me write the functions set_bit and clear_bit .

2 Likes

For the time being you can replace something like

assets_in ^= 1 << asset_offset;

with

assets_in = asset_in ^ (1 << asset_offset);

and so on. I will open an issue to implement ^= as we already support this shorthand for something like + and -.

3 Likes

@fuel I need to update this lib as it’s pretty old, but the set_bit function in this small library will set a given bit to whatever value you give it: GitHub - nfurfaro/sway-bits: A collection of bitwise operations for the Sway blockchain programming language

3 Likes