diff options
author | pacien | 2018-11-30 21:02:29 +0100 |
---|---|---|
committer | pacien | 2018-11-30 21:02:29 +0100 |
commit | 3d5a87a5879aa724e47546d1bdbb7f6c9466cf94 (patch) | |
tree | a0abba7ab32e88e8daf6b7b547cfd446754cacfe /src/bitio/integers.nim | |
parent | 5bbe75659aef55542268cbf35c66342cb22ce865 (diff) | |
download | gziplike-3d5a87a5879aa724e47546d1bdbb7f6c9466cf94.tar.gz |
move integers utils
Diffstat (limited to 'src/bitio/integers.nim')
-rw-r--r-- | src/bitio/integers.nim | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/bitio/integers.nim b/src/bitio/integers.nim new file mode 100644 index 0000000..c93c9b8 --- /dev/null +++ b/src/bitio/integers.nim | |||
@@ -0,0 +1,40 @@ | |||
1 | # gzip-like LZSS compressor | ||
2 | # Copyright (C) 2018 Pacien TRAN-GIRARD | ||
3 | # | ||
4 | # This program is free software: you can redistribute it and/or modify | ||
5 | # it under the terms of the GNU Affero General Public License as | ||
6 | # published by the Free Software Foundation, either version 3 of the | ||
7 | # License, or (at your option) any later version. | ||
8 | # | ||
9 | # This program is distributed in the hope that it will be useful, | ||
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
12 | # GNU Affero General Public License for more details. | ||
13 | # | ||
14 | # You should have received a copy of the GNU Affero General Public License | ||
15 | # along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
16 | |||
17 | const wordBitLength* = 8 | ||
18 | |||
19 | proc `/^`*[T: Natural](x, y: T): T = | ||
20 | (x + y - 1) div y | ||
21 | |||
22 | proc truncateToUint8*(x: SomeUnsignedInt): uint8 = | ||
23 | (x and uint8.high).uint8 | ||
24 | |||
25 | proc bitLength*[T: SomeUnsignedInt](x: T): int = | ||
26 | var buf = x | ||
27 | while buf > 0.T: | ||
28 | buf = buf shr 1 | ||
29 | result += 1 | ||
30 | |||
31 | proc leastSignificantBits*[T: SomeUnsignedInt](x: T, bits: int): T = | ||
32 | let maskOffset = sizeof(T) * wordBitLength - bits | ||
33 | if maskOffset >= 0: (x shl maskOffset) shr maskOffset else: x | ||
34 | |||
35 | iterator chunks*(totalBitLength: int, chunkType: typedesc[SomeInteger]): tuple[index: int, chunkBitLength: int] = | ||
36 | let chunkBitLength = sizeof(chunkType) * wordBitLength | ||
37 | let wordCount = totalBitLength div chunkBitLength | ||
38 | for i in 0..<(wordCount): yield (i, chunkBitLength) | ||
39 | let remainder = totalBitLength mod chunkBitLength | ||
40 | if remainder > 0: yield (wordCount, remainder) | ||