1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.hadoop.hbase.io.hfile;
18
19 import java.util.Random;
20
21 import org.apache.hadoop.io.BytesWritable;
22 import org.apache.hadoop.hbase.io.hfile.RandomDistribution.DiscreteRNG;
23
24
25
26
27
28
29
30
31 class KeySampler {
32 Random random;
33 int min, max;
34 DiscreteRNG keyLenRNG;
35 private static final int MIN_KEY_LEN = 4;
36
37 public KeySampler(Random random, byte [] first, byte [] last,
38 DiscreteRNG keyLenRNG) {
39 this.random = random;
40 min = keyPrefixToInt(first);
41 max = keyPrefixToInt(last);
42 this.keyLenRNG = keyLenRNG;
43 }
44
45 private int keyPrefixToInt(byte [] key) {
46 byte[] b = key;
47 int o = 0;
48 return (b[o] & 0xff) << 24 | (b[o + 1] & 0xff) << 16
49 | (b[o + 2] & 0xff) << 8 | (b[o + 3] & 0xff);
50 }
51
52 public void next(BytesWritable key) {
53 key.setSize(Math.max(MIN_KEY_LEN, keyLenRNG.nextInt()));
54 random.nextBytes(key.get());
55 int n = random.nextInt(max - min) + min;
56 byte[] b = key.get();
57 b[0] = (byte) (n >> 24);
58 b[1] = (byte) (n >> 16);
59 b[2] = (byte) (n >> 8);
60 b[3] = (byte) n;
61 }
62 }