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