/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.cksum;

import java.nio.ByteBuffer;
import java.util.zip.CRC32;

/**
 * Implementation of the CRC-32 checksum following the <code>Checksum</code> interface.
 *
 * @author Alex Leigh
 */
public class CRC32Checksum implements Checksum {
    private CRC32 crc = new CRC32();

    @Override
    public int getSize() {
        return 4;
    }

    @Override
    public void update(byte[] data) {
        crc.update(data);
    }

    public void writeChecksumValue(ByteBuffer data) {
        // It's admittedly strange that CRC32 returns a long.
        data.putInt((int) crc.getValue());
    }

    @Override
    public ByteBuffer getChecksumValue() {
        ByteBuffer val = ByteBuffer.allocate(getSize());
        writeChecksumValue(val);
        val.rewind();
        return val;
    }

    @Override
    public void reset() {
        crc.reset();
    }
}
