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 */
017
018package org.apache.commons.rng.core.source64;
019
020import org.apache.commons.rng.core.util.NumberFactory;
021
022/**
023 * A fast RNG, with 64 bits of state, that can be used to initialize the
024 * state of other generators.
025 *
026 * @see <a href="http://xorshift.di.unimi.it/splitmix64.c">
027 * Original source code</a>
028 *
029 * @since 1.0
030 */
031public class SplitMix64 extends LongProvider {
032    /** State. */
033    private long state;
034
035    /**
036     * Creates a new instance.
037     *
038     * @param seed Initial seed.
039     * @since 1.3
040     */
041    public SplitMix64(long seed) {
042        state = seed;
043    }
044
045    /**
046     * Creates a new instance.
047     *
048     * @param seed Initial seed.
049     */
050    public SplitMix64(Long seed) {
051        // Support for Long to allow instantiation through the
052        // rng.simple.RandomSource factory methods.
053        setSeedInternal(seed);
054    }
055
056    /**
057     * Seeds the RNG.
058     *
059     * @param seed Seed.
060     */
061    private void setSeedInternal(Long seed) {
062        state = seed.longValue();
063    }
064
065    /** {@inheritDoc} */
066    @Override
067    public long next() {
068        long z = state += 0x9e3779b97f4a7c15L;
069        z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
070        z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
071        return z ^ (z >>> 31);
072    }
073
074    /** {@inheritDoc} */
075    @Override
076    protected byte[] getStateInternal() {
077        return composeStateInternal(NumberFactory.makeByteArray(state),
078                                    super.getStateInternal());
079    }
080
081    /** {@inheritDoc} */
082    @Override
083    protected void setStateInternal(byte[] s) {
084        final byte[][] c = splitStateInternal(s, 8);
085
086        state = NumberFactory.makeLong(c[0]);
087        super.setStateInternal(c[1]);
088    }
089}