/* -*- Mode: C; c-file-style: "gnu" -*-
   crc32.c -- native methods for java/util/zip/CRC32
   Created: Chris Toshok <toshok@hungry.com>, 9-Nov-1997
 */
/*
  This file is part of Japhar, the GNU Virtual Machine for Java Bytecodes.
  Japhar is a project of The Hungry Programmers, GNU, and OryxSoft.

  Copyright (C) 1997, 1998, 1999 The Hungry Programmers

  This library 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 library 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
#include "config.h"
#include "jni.h"
#include "zlib.h"
#include "objects.h"

static jint
get_crc(JNIEnv *env,
	jobject obj)
{
  jfieldID crc_field;
  jclass crc_class = (*env)->GetObjectClass(env, obj);

  crc_field = (*env)->GetFieldID(env, crc_class, "crc", "I");

  return (*env)->GetIntField(env, obj, crc_field);
}

static void
set_crc(JNIEnv *env,
	jobject obj,
	jint crc)
{
  jfieldID crc_field;
  jclass crc_class = (*env)->GetObjectClass(env, obj);
  
  crc_field = (*env)->GetFieldID(env, crc_class, "crc", "I");
  
  (*env)->SetIntField(env, obj, crc_field, crc);
}

JNIEXPORT void JNICALL
Java_java_util_zip_CRC32_update(JNIEnv *env,
				jobject obj,
				jbyteArray b,
				jint off,
				jint len)
{
  jint crc = get_crc(env, obj);
  jbyte* bytes;

  bytes = (*env)->GetByteArrayElements(env, b, NULL);

  crc = crc32(crc,
	      bytes + off,
	      len);

  (*env)->ReleaseByteArrayElements(env, b, bytes, 0);

  set_crc(env, obj, crc);
}

JNIEXPORT void JNICALL
Java_java_util_zip_CRC32_update1(JNIEnv *env,
				 jobject obj,
				 jint b)
{
  jint crc = get_crc(env, obj);
  jbyte byte = (jbyte)b;

  crc = crc32(crc,
	      &byte, 1);

  set_crc(env, obj, crc);
}

/* JDK1.2 */
JNIEXPORT jint JNICALL
Java_java_util_zip_CRC32_updateBytes(JNIEnv *env,
				     jobject obj,
				     jint crc,
				     jbyteArray b,
				     jint off,
				     jint len)
{
  jbyte *bytes;

  bytes = (*env)->GetByteArrayElements(env, b, NULL);

  crc = crc32(crc, bytes + off, len);

  (*env)->ReleaseByteArrayElements(env, b, bytes, JNI_COMMIT);

  return crc;
}
