diff --git a/src/main/java/io/github/lonamiwebs/overgram/parser/TLReader.java b/src/main/java/io/github/lonamiwebs/overgram/parser/TLReader.java index 09c9b9f..5dc076d 100644 --- a/src/main/java/io/github/lonamiwebs/overgram/parser/TLReader.java +++ b/src/main/java/io/github/lonamiwebs/overgram/parser/TLReader.java @@ -1,5 +1,7 @@ package io.github.lonamiwebs.overgram.parser; +import io.github.lonamiwebs.overgram.utils.CharacterIterator; + import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -8,7 +10,6 @@ import java.util.List; public class TLReader { - private static final int BUFFER_SIZE = 4096; public static List readTlObjects(final File file) { final List lines = readFileWithDelimiter(new File("telegram_api.tl"), ';'); @@ -22,18 +23,14 @@ public class TLReader { private static List readFileWithDelimiter(final File file, final char delimiter) { final List result = new ArrayList<>(); - try (final FileReader reader = new FileReader(file)) { - int read; - final char[] buffer = new char[BUFFER_SIZE]; + try (final CharacterIterator iter = new CharacterIterator(new FileReader(file))) { final StringBuilder builder = new StringBuilder(); - while ((read = reader.read(buffer)) > 0) { - for (int i = 0; i < read; ++i) { - if (buffer[i] == delimiter) { - result.add(builder.toString()); - builder.setLength(0); - } else { - builder.append(buffer[i]); - } + for (char c : iter) { + if (c == delimiter) { + result.add(builder.toString()); + builder.setLength(0); + } else { + builder.append(c); } } } catch (IOException ignored) { diff --git a/src/main/java/io/github/lonamiwebs/overgram/utils/CharacterIterator.java b/src/main/java/io/github/lonamiwebs/overgram/utils/CharacterIterator.java new file mode 100644 index 0000000..d1cc81f --- /dev/null +++ b/src/main/java/io/github/lonamiwebs/overgram/utils/CharacterIterator.java @@ -0,0 +1,61 @@ +package io.github.lonamiwebs.overgram.utils; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Iterator; + +public class CharacterIterator implements Iterator, Iterable, AutoCloseable { + + private static final int BUFFER_SIZE = 4096; + + private final InputStreamReader reader; + private final char[] buffer; + private int index; + private int length; + + public CharacterIterator(final InputStreamReader reader) { + this.reader = reader; + buffer = new char[BUFFER_SIZE]; + index = 0; + readNext(); + } + + @Override + public Iterator iterator() { + return this; + } + + @Override + public boolean hasNext() { + if (index == BUFFER_SIZE) { + readNext(); + index = 0; + } + return length != -1; + } + + @Override + public Character next() { + if (index == BUFFER_SIZE) { + readNext(); + index = 0; + } + return buffer[index++]; + } + + @Override + public void close() { + try { + reader.close(); + } catch (Exception ignored) { + } + } + + private void readNext() { + try { + length = reader.read(buffer); + } catch (IOException ignored) { + length = -1; + } + } +}