マイペースなプログラミング日記

DTMやプログラミングにお熱なd-kamiがマイペースに書くブログ

バイナリエディタを目指して その1

なんとなくバイナリエディタを作ってみたくなったので、作成中。まずはデータを格納するクラスを作成。set(byte data, int index)でindex番目をdataに書き換えてget(int index)でindex番目を返すみたいなクラスを作った。データを格納する配列型のcontentsは指定されたサイズより大きめの容量を持たせて、足りなくなったらreallocateでサイズ変更するようにした。以下ソース

public class BinaryDocument{
    private int size;
    private int capacity;
    private byte[] contents;

    public BinaryDocument(){
        this(0);
    }

    public BinaryDocument(int size){
        this.size = size;
        this.capacity = (size * 13 / 10) + 10;
        this.contents = new byte[capacity];
    }

    public void set(byte data, int index){
        if(index >= capacity)
            reallocate(index);

        if(index > size)
            size = index;

        contents[index] = data;
    }

    public byte get(int index){
        if(index >= size)
            return (byte)0;

        return contents[index];
    }

    public byte[] gets(int index, int length){
         byte[] data = new byte[length];

         for(int i = 0; i < length; i++){
              data[i] = get(index + i);
         }

         return data;
    }

    private void reallocate(int newSize){
         capacity = (newSize * 13 / 10) + 10;
         byte[] newContents = new byte[capacity];

         for(int i = 0; i < size; i++){
             newContents[i] = contents[i];
         }

         contents = newContents;
         size = newSize;
    }
}