1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with this
4    * work for additional information regarding copyright ownership. The ASF
5    * licenses this file to you under the Apache License, Version 2.0 (the
6    * "License"); you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14   * License for the specific language governing permissions and limitations under
15   * the License.
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  * <p>
26  * Copied from
27  * <a href="https://issues.apache.org/jira/browse/HADOOP-3315">hadoop-3315 tfile</a>.
28  * Remove after tfile is committed and use the tfile version of this class
29  * instead.</p>
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  }