-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathKeyBatch.cs
More file actions
85 lines (66 loc) · 2.08 KB
/
KeyBatch.cs
File metadata and controls
85 lines (66 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace LightningDB.Benchmarks;
public enum KeyOrdering
{
Sequential,
Random
}
/// <summary>
/// A collection of key arrays with configurable size
/// </summary>
public class KeyBatch
{
private KeyBatch(byte[][] buffers)
{
Buffers = buffers;
}
public byte[][] Buffers { get; }
public int Count => Buffers.Length;
public ref byte[] this[int index] => ref Buffers[index];
public static KeyBatch Generate(int keyCount, KeyOrdering keyOrdering)
=> Generate(keyCount, keyOrdering, keySize: 4);
public static KeyBatch Generate(int keyCount, KeyOrdering keyOrdering, int keySize)
{
var buffers = new byte[keyCount][];
switch (keyOrdering) {
case KeyOrdering.Sequential:
PopulateSequential(buffers, keySize);
break;
case KeyOrdering.Random:
PopulateRandom(buffers, keySize);
break;
default:
throw new ArgumentException("That isn't a valid KeyOrdering", nameof(keyOrdering));
}
return new KeyBatch(buffers);
}
private static void PopulateSequential(byte[][] buffers, int keySize)
{
for (var i = 0; i < buffers.Length; i++) {
buffers[i] = CopyToArray(i, keySize);
}
}
private static void PopulateRandom(byte[][] buffers, int keySize)
{
var random = new Random(0);
var seen = new HashSet<int>(buffers.Length);
var i = 0;
while (i < buffers.Length) {
var keyValue = random.Next(0, buffers.Length);
if (!seen.Add(keyValue))
continue;//skip duplicates
buffers[i++] = CopyToArray(keyValue, keySize);
}
}
private static byte[] CopyToArray(int keyValue, int keySize)
{
var key = new byte[keySize];
if (keySize >= 8)
MemoryMarshal.Write(key, (long)keyValue);
else
MemoryMarshal.Write(key, in keyValue);
return key;
}
}