/*
    JpcgenSHA.java -- implementation of the JrpcgenSHA interface that 
    calls out to the Java standard library instead of to bundled code

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Library General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    @author William Benton <willb@redhat.com>
 */

package org.acplt.oncrpc.apps.jrpcgen;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JrpcgenSHA {
	public JrpcgenSHA() {
		reset();
	}

	public void update(byte b) {
		this.digest.update(b);
	}

	public void update(short s) {
		for (int pos = 0 ; pos < 2 ; pos ++) {
			update((byte)((s >> (pos * 8)) & 0xff));
		}
	}

	public void update(int i) {
		for (int pos = 0 ; pos < 4 ; pos ++) {
			update((byte)((i >> (pos * 8)) & 0xff));
		}
	}

	public void update(String s) {
		for (char ch: s.toCharArray()) {
			update((short)ch);
		}
	}

	public long getHash() {
		byte[] h = this.digest.digest();
		long result = 0;
		for(int i = 0; i < 8; i++) {
			result += ((long)h[i] & 0xffl) << (i*8);
		}
		return result;
	}

	@Override
	public String toString() {
		return String.valueOf(getHash());
	}
	
	private void reset() {
		try {
			this.digest = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("This JVM doesn't supply SHA-1; something is seriously wrong");
		}
	}

	private MessageDigest digest;

}

// End of JrpcgenSHA.java

