From 3d5a87a5879aa724e47546d1bdbb7f6c9466cf94 Mon Sep 17 00:00:00 2001
From: pacien
Date: Fri, 30 Nov 2018 21:02:29 +0100
Subject: move integers utils
---
src/bitio/bitreader.nim | 2 +-
src/bitio/bitwriter.nim | 2 +-
src/bitio/integers.nim | 40 ++++++++++++++++++++++++++++++++++++++++
3 files changed, 42 insertions(+), 2 deletions(-)
create mode 100644 src/bitio/integers.nim
(limited to 'src/bitio')
diff --git a/src/bitio/bitreader.nim b/src/bitio/bitreader.nim
index e4ad225..baa8bf8 100644
--- a/src/bitio/bitreader.nim
+++ b/src/bitio/bitreader.nim
@@ -15,7 +15,7 @@
# along with this program. If not, see .
import streams
-import ../integers
+import integers
type BitReader* = ref object
stream: Stream
diff --git a/src/bitio/bitwriter.nim b/src/bitio/bitwriter.nim
index f1b44ca..4fe499a 100644
--- a/src/bitio/bitwriter.nim
+++ b/src/bitio/bitwriter.nim
@@ -15,7 +15,7 @@
# along with this program. If not, see .
import streams
-import ../integers
+import integers
type BitWriter* = ref object
stream: Stream
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 @@
+# gzip-like LZSS compressor
+# Copyright (C) 2018 Pacien TRAN-GIRARD
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+
+const wordBitLength* = 8
+
+proc `/^`*[T: Natural](x, y: T): T =
+ (x + y - 1) div y
+
+proc truncateToUint8*(x: SomeUnsignedInt): uint8 =
+ (x and uint8.high).uint8
+
+proc bitLength*[T: SomeUnsignedInt](x: T): int =
+ var buf = x
+ while buf > 0.T:
+ buf = buf shr 1
+ result += 1
+
+proc leastSignificantBits*[T: SomeUnsignedInt](x: T, bits: int): T =
+ let maskOffset = sizeof(T) * wordBitLength - bits
+ if maskOffset >= 0: (x shl maskOffset) shr maskOffset else: x
+
+iterator chunks*(totalBitLength: int, chunkType: typedesc[SomeInteger]): tuple[index: int, chunkBitLength: int] =
+ let chunkBitLength = sizeof(chunkType) * wordBitLength
+ let wordCount = totalBitLength div chunkBitLength
+ for i in 0..<(wordCount): yield (i, chunkBitLength)
+ let remainder = totalBitLength mod chunkBitLength
+ if remainder > 0: yield (wordCount, remainder)
--
cgit v1.2.3