001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. 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, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.rng.core.source64; 018 019import org.apache.commons.rng.core.util.NumberFactory; 020 021/** 022 * Implement Bob Jenkins's small fast (JSF) 64-bit generator. 023 * 024 * <p>The state size is 256-bits.</p> 025 * 026 * @see <a href="https://burtleburtle.net/bob/rand/smallprng.html">A small noncryptographic PRNG</a> 027 * @since 1.3 028 */ 029public class JenkinsSmallFast64 extends LongProvider { 030 /** State a. */ 031 private long a; 032 /** State b. */ 033 private long b; 034 /** State c. */ 035 private long c; 036 /** Statd d. */ 037 private long d; 038 039 /** 040 * Creates an instance with the given seed. 041 * 042 * @param seed Initial seed. 043 */ 044 public JenkinsSmallFast64(Long seed) { 045 setSeedInternal(seed); 046 } 047 048 /** 049 * Seeds the RNG. 050 * 051 * @param seed Seed. 052 */ 053 private void setSeedInternal(long seed) { 054 a = 0xf1ea5eedL; 055 b = seed; 056 c = seed; 057 d = seed; 058 for (int i = 0; i < 20; i++) { 059 next(); 060 } 061 } 062 063 /** {@inheritDoc} */ 064 @Override 065 public final long next() { 066 final long e = a - Long.rotateLeft(b, 7); 067 a = b ^ Long.rotateLeft(c, 13); 068 b = c + Long.rotateLeft(d, 37); 069 c = d + e; 070 d = e + a; 071 return d; 072 } 073 074 /** {@inheritDoc} */ 075 @Override 076 protected byte[] getStateInternal() { 077 return composeStateInternal(NumberFactory.makeByteArray(new long[] {a, b, c, d}), 078 super.getStateInternal()); 079 } 080 081 /** {@inheritDoc} */ 082 @Override 083 protected void setStateInternal(byte[] s) { 084 final byte[][] parts = splitStateInternal(s, 4 * 8); 085 086 final long[] tmp = NumberFactory.makeLongArray(parts[0]); 087 a = tmp[0]; 088 b = tmp[1]; 089 c = tmp[2]; 090 d = tmp[3]; 091 092 super.setStateInternal(parts[1]); 093 } 094}