001    package edu.harvard.deas.hyperenc;
002    
003    import java.util.Random;
004    
005    /** Source of random bits. */
006    
007    public class TestRandomSource implements RandomSource {
008      private static final long serialVersionUID = 1L;
009    
010      Random rand;
011    
012      // SecureRandom srand;
013    
014      public TestRandomSource() {
015      }
016    
017      public void getPage(byte[] block, byte[] page) throws PageException {
018        // srand = new SecureRandom(block);
019        // srand.nextBytes(page);
020        rand = new Random(bytesToLong(block));
021        rand.nextBytes(page);
022      }
023    
024      /**
025       * Concatenate the first 8 bytes of <code>b</code> into a long. This
026       * function computes the long integer equal to the sum, for <i>k</i> from 0
027       * to <i>N</i>, of 2<sup>N-k</sup>*<code>b[k]</code>, where <i>N</i>
028       * is min(b.length, 8)-1.
029       * 
030       * @param b
031       *        A byte array.
032       * @return The long integer as described above.
033       */
034      private long bytesToLong(byte[] b) {
035        // longs are 64 bits, bytes are 8.
036        long result = 0;
037        for (int i = 0; i < Math.min(b.length, 8); i++) {
038          result <<= 8;
039          result += b[i];
040        }
041        return result;
042      }
043    }