util.ha (1834B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 // The following code was initially ported from BearSSL. 5 // 6 // Copyright (c) 2017 Thomas Pornin <pornin@bolet.org> 7 // 8 // Permission is hereby granted, free of charge, to any person obtaining a copy 9 // of this software and associated documentation files (the "Software"), to deal 10 // in the Software without restriction, including without limitation the rights 11 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 // copies of the Software, and to permit persons to whom the Software is 13 // furnished to do so, subject to the following conditions: 14 // 15 // The above copyright notice and this permission notice shall be included in 16 // all copies or substantial portions of the Software. 17 // 18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 // SOFTWARE. 25 use bytes; 26 27 // Sets encoded bitlen of 'x' to 'ebitlen' and then zeroes its effective words. 28 export fn zero(x: []word, ebitlen: word) void = { 29 x[0] = ebitlen; 30 const ewordlen = ewordlen(x); 31 bytes::zero((x: *[*]u8)[size(word)..(1 + ewordlen) * size(word)]); 32 }; 33 34 // Checks whether the effective words of 'x' are zero. Returns 1 if so, or 0 35 // otherwise. 36 export fn iszero(x: []word) u32 = { 37 let z: u32 = 0; 38 39 for (let i = ewordlen(x); i > 0; i -= 1) { 40 z |= x[i]; 41 }; 42 return ~(z | -(z: i32): u32) >> 31; 43 }; 44 45 fn isodd(x: []word) bool = { 46 return x[1] & 1 == 1; 47 };