001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.io.hfile;
019
020import java.util.Random;
021import org.apache.hadoop.hbase.util.RandomDistribution.DiscreteRNG;
022import org.apache.hadoop.io.BytesWritable;
023
024/*
025* <p>
026* Copied from
027* <a href="https://issues.apache.org/jira/browse/HADOOP-3315">hadoop-3315 tfile</a>.
028* Remove after tfile is committed and use the tfile version of this class
029* instead.</p>
030*/
031class KeySampler {
032  Random random;
033  int min, max;
034  DiscreteRNG keyLenRNG;
035  private static final int MIN_KEY_LEN = 4;
036
037  public KeySampler(Random random, byte[] first, byte[] last, DiscreteRNG keyLenRNG) {
038    this.random = random;
039    int firstLen = keyPrefixToInt(first);
040    int lastLen = keyPrefixToInt(last);
041    min = Math.min(firstLen, lastLen);
042    max = Math.max(firstLen, lastLen);
043    System.out.println(min);
044    System.out.println(max);
045    this.keyLenRNG = keyLenRNG;
046  }
047
048  private int keyPrefixToInt(byte[] key) {
049    byte[] b = key;
050    int o = 0;
051    return (b[o] & 0xff) << 24 | (b[o + 1] & 0xff) << 16 | (b[o + 2] & 0xff) << 8
052      | (b[o + 3] & 0xff);
053  }
054
055  public void next(BytesWritable key) {
056    key.setSize(Math.max(MIN_KEY_LEN, keyLenRNG.nextInt()));
057    random.nextBytes(key.get());
058    int rnd = 0;
059    if (max != min) {
060      rnd = random.nextInt(max - min);
061    }
062    int n = rnd + min;
063    byte[] b = key.get();
064    b[0] = (byte) (n >> 24);
065    b[1] = (byte) (n >> 16);
066    b[2] = (byte) (n >> 8);
067    b[3] = (byte) n;
068  }
069}