/*
 * [TestSunCRC16.java]
 *
 * Summary: 16-bit unofficial Sun CRC, cyclic redundancy checks.
 *
 * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2009-01-01 initial version
 */
package com.mindprod.example;

import com.mindprod.common18.EIO;
import sun.misc.CRC16;

import java.io.UnsupportedEncodingException;

import static java.lang.System.*;

/**
 * 16-bit unofficial Sun CRC, cyclic redundancy checks.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2009-01-01 initial version
 * @since 2009-01-01
 */
public final class TestSunCRC16
    {
    ;

    /**
     * Calc CRC-16 with unofficial Sun method. You will get a warning message of the form
     * [warning: sun.misc.CRC16 is Sun proprietary API and may be removed in a future release]
     *
     * @param ba byte array to compute CRC on
     *
     * @return 16-bit CRC, signed
     */
    @SuppressWarnings( "deprecation" )
    private static short sunCRC16( byte[] ba )
        {
        // create a new CRC-calculating object
        final CRC16 crc = new CRC16();
        // loop, calculating CRC for each byte of the string
        // There is no CRC16.update(byte[]) method.
        for ( byte b : ba )
            {
            crc.update( b );
            }
        // note use crc.value, not crc.getValue()
        return ( short ) crc.value;
        }

    /**
     * Test harness
     *
     * @param args not used
     *
     * @throws java.io.UnsupportedEncodingException in case UTF-8 support missing.
     */
    public static void main( String[] args ) throws UnsupportedEncodingException
        {
        final String s = "The quick brown fox jumped over the lazy dog's back; sample url: http://mindprod.com/jgloss/digest.html";
        final byte[] theTextToDigestAsBytes = s.getBytes( EIO.UTF8 );
        out.println( sunCRC16( theTextToDigestAsBytes ) );
        long start = System.nanoTime();
        for ( int i = 0; i < 100_000100_000; i++ )
            {
            sunCRC16( theTextToDigestAsBytes );
            }
        long stop = System.nanoTime();
        out.println( ( stop - start ) / 1_000_0001_000_000L + " seconds to compute 100,000 sunCRC16 hashes" );
        // On my machine it takes: 184 seconds to compute 100,000 sunCRC16 hashes
        }
    }