1- # # In a multi-threaded download, this algorithmm could be used to provide
2- # # each worker thread with a block of non-overlapping bytes to download.
1+ # Non-overlapping Partitioning
2+ # # In a multi-threaded program, this algorithmm could be used to provide
3+ # # each worker thread with a block of non-overlapping bytes to work on.
34
45runnableExamples:
56 let numBytes = 100
@@ -13,10 +14,8 @@ runnableExamples:
1314 80 .. 100
1415 ]
1516
16- func allocationNum (numBytes: Natural , numPartitions: Natural ): seq [Slice [Natural ]] =
17+ func allocationNum (numBytes: Natural , numPartitions: Positive ): seq [Slice [Natural ]] =
1718 # # Divide `numBytes` bytes into `numPartitions` non-overlapping partitions.
18- if numPartitions <= 0 :
19- raise newException (ValueError , " numPartitions must be > 0" )
2019 if numPartitions > numBytes:
2120 raise newException (ValueError , " numPartitions must be <= numBytes" )
2221 var
@@ -33,20 +32,26 @@ when isMainModule:
3332 import std/ unittest
3433
3534 suite " Test `allocationNum`" :
36- test " Test `allocationNum`" :
35+ test " Test `allocationNum` on a divisor of bytes (same partition sizes) " :
3736 let allocations: seq [Slice [Natural ]] = allocationNum (100 , 5 )
3837 check allocations == @ [
39- Natural (0 ) .. 19 ,
40- Natural (20 ) .. 39 ,
41- Natural (40 ) .. 59 ,
42- Natural (60 ) .. 79 ,
43- Natural (80 ) .. 100
38+ Natural (0 ) .. Natural ( 19 ) ,
39+ Natural (20 ) .. Natural ( 39 ) ,
40+ Natural (40 ) .. Natural ( 59 ) ,
41+ Natural (60 ) .. Natural ( 79 ) ,
42+ Natural (80 ) .. Natural ( 100 )
4443 ]
4544
46- test " `allocationNum` on 0 partitions" :
47- doAssertRaises (ValueError ): discard allocationNum (5 , 0 )
45+ test " `allocationNum` on a non-divisor of bytes" :
46+ let allocations: seq [Slice [Natural ]] = allocationNum (104 , 5 )
47+ check allocations == @ [
48+ Natural (0 ) .. Natural (19 ),
49+ Natural (20 ) .. Natural (39 ),
50+ Natural (40 ) .. Natural (59 ),
51+ Natural (60 ) .. Natural (79 ),
52+ Natural (80 ) .. Natural (104 )
53+ ]
4854
4955 test " `allocationNum` on more partitions than bytes" :
5056 doAssertRaises (ValueError ): discard allocationNum (0 , 5 )
51-
52- echo allocationNum (0 , 5 )
57+ doAssertRaises (ValueError ): discard allocationNum (1 , 5 )
0 commit comments