aboutsummaryrefslogtreecommitdiff
path: root/src/bitio/integers.nim
diff options
context:
space:
mode:
Diffstat (limited to 'src/bitio/integers.nim')
-rw-r--r--src/bitio/integers.nim40
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
17const wordBitLength* = 8
18
19proc `/^`*[T: Natural](x, y: T): T =
20 (x + y - 1) div y
21
22proc truncateToUint8*(x: SomeUnsignedInt): uint8 =
23 (x and uint8.high).uint8
24
25proc bitLength*[T: SomeUnsignedInt](x: T): int =
26 var buf = x
27 while buf > 0.T:
28 buf = buf shr 1
29 result += 1
30
31proc 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
35iterator 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)