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.
3
4
4
5
runnableExamples:
5
6
let numBytes = 100
@@ -13,10 +14,8 @@ runnableExamples:
13
14
80 .. 100
14
15
]
15
16
16
- func allocationNum(numBytes: Natural, numPartitions: Natural ): seq [Slice[Natural]] =
17
+ func allocationNum(numBytes: Natural, numPartitions: Positive ): seq [Slice[Natural]] =
17
18
# # Divide `numBytes` bytes into `numPartitions` non-overlapping partitions.
18
- if numPartitions <= 0 :
19
- raise newException(ValueError, " numPartitions must be > 0" )
20
19
if numPartitions > numBytes:
21
20
raise newException(ValueError, " numPartitions must be <= numBytes" )
22
21
var
@@ -33,20 +32,26 @@ when isMainModule:
33
32
import std/ unittest
34
33
35
34
suite " Test `allocationNum`" :
36
- test " Test `allocationNum`" :
35
+ test " Test `allocationNum` on a divisor of bytes (same partition sizes) " :
37
36
let allocations: seq [Slice[Natural]] = allocationNum(100 , 5 )
38
37
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 )
44
43
]
45
44
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
+ ]
48
54
49
55
test " `allocationNum` on more partitions than bytes" :
50
56
doAssertRaises(ValueError): discard allocationNum(0 , 5 )
51
-
52
- echo allocationNum(0 , 5 )
57
+ doAssertRaises(ValueError): discard allocationNum(1 , 5 )
0 commit comments