package com.icystar.findnumber;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class Serializer {
public static void writeInt(FileOutputStream fos, int value) throws IOException {
fos.write( ByteBuffer.allocate((Integer.SIZE+7)/8).putInt(value).array() );
}
public static int readInt(FileInputStream fis) throws IOException {
byte[] b = new byte[(Integer.SIZE+7)/8];
Arrays.fill(b, (byte)0);
fis.read(b);
return ByteBuffer.wrap(b).getInt();
}
public static void writeFloat(FileOutputStream fos, float value) throws IOException {
fos.write( ByteBuffer.allocate((Float.SIZE+7)/8).putFloat(value).array() );
}
public static float readFloat(FileInputStream fis) throws IOException {
byte[] b = new byte[(Float.SIZE+7)/8];
Arrays.fill(b, (byte)0);
fis.read(b);
return ByteBuffer.wrap(b).getFloat();
}
public static void writeString(FileOutputStream fos, String value) throws IOException {
byte[] b = value.getBytes();
writeInt(fos, b.length);
fos.write(b);
}
public static String readString(FileInputStream fis) throws IOException {
byte[] b = new byte[readInt(fis)];
fis.read(b);
return new String(b);
}
public static <T extends Object> T[] resizeArray(Class<T> typeClass, T[] array, int size) {
@SuppressWarnings("unchecked")
T[] resized = (T[])Array.newInstance(typeClass, Math.max(0, size));
if (array != null)
for(int i = 0; i < array.length && i < resized.length; i++)
resized[i] = array[i];
return resized;
}
public static <T extends Object> T[] resizeArrayIfNeed(Class<T> typeClass, T[] array, int size) {
if (array != null && array.length == Math.max(0, size)) return array;
return resizeArray(typeClass, array, Math.max(0, size));
}
public static <T extends Object> T[] enlargeArray(Class<T> typeClass, T[] array, int size) {
return resizeArray(typeClass, array, Math.max(size, array == null ? 0 : array.length));
}
public static <T extends Object> T[] reduceArray(Class<T> typeClass, T[] array, int size) {
return resizeArray(typeClass, array, Math.min(size, array == null ? 0 : array.length));
}
public static <T extends Object> T[] enlargeArrayIfNeed(Class<T> typeClass, T[] array, int size) {
return resizeArrayIfNeed(typeClass, array, Math.max(size, array == null ? 0 : array.length));
}
public static <T extends Object> T[] reduceArrayIfNeed(Class<T> typeClass, T[] array, int size) {
return resizeArrayIfNeed(typeClass, array, Math.min(size, array == null ? 0 : array.length));
}
}