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 = c = d = seed;
056        for (int i = 0; i < 20; i++) {
057            next();
058        }
059    }
060
061    /** {@inheritDoc} */
062    @Override
063    public final long next() {
064        final long e = a - Long.rotateLeft(b, 7);
065        a = b ^ Long.rotateLeft(c, 13);
066        b = c + Long.rotateLeft(d, 37);
067        c = d + e;
068        d = e + a;
069        return d;
070    }
071
072    /** {@inheritDoc} */
073    @Override
074    protected byte[] getStateInternal() {
075        return composeStateInternal(NumberFactory.makeByteArray(new long[] {a, b, c, d}),
076                                    super.getStateInternal());
077    }
078
079    /** {@inheritDoc} */
080    @Override
081    protected void setStateInternal(byte[] s) {
082        final byte[][] parts = splitStateInternal(s, 4 * 8);
083
084        final long[] tmp = NumberFactory.makeLongArray(parts[0]);
085        a = tmp[0];
086        b = tmp[1];
087        c = tmp[2];
088        d = tmp[3];
089
090        super.setStateInternal(parts[1]);
091    }
092}