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 int firstLen = keyPrefixToInt(first);
41 int lastLen = keyPrefixToInt(last);
42 min = Math.min(firstLen, lastLen);
43 max = Math.max(firstLen, lastLen);
44 System.out.println(min);
45 System.out.println(max);
46 this.keyLenRNG = keyLenRNG;
47 }
48
49 private int keyPrefixToInt(byte [] key) {
50 byte[] b = key;
51 int o = 0;
52 return (b[o] & 0xff) << 24 | (b[o + 1] & 0xff) << 16
53 | (b[o + 2] & 0xff) << 8 | (b[o + 3] & 0xff);
54 }
55
56 public void next(BytesWritable key) {
57 key.setSize(Math.max(MIN_KEY_LEN, keyLenRNG.nextInt()));
58 random.nextBytes(key.get());
59 int rnd = 0;
60 if (max != min) {
61 rnd = random.nextInt(max - min);
62 }
63 int n = rnd + min;
64 byte[] b = key.get();
65 b[0] = (byte) (n >> 24);
66 b[1] = (byte) (n >> 16);
67 b[2] = (byte) (n >> 8);
68 b[3] = (byte) n;
69 }
70 }