StreamCharReader.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package me.hammerle.snuviscript.tokenizer;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. public class StreamCharReader {
  5. private final InputStream in;
  6. private int buffer = -1;
  7. public StreamCharReader(InputStream in) {
  8. this.in = in;
  9. }
  10. public int peekChar() {
  11. if(buffer == -1) {
  12. buffer = readChar();
  13. return buffer;
  14. }
  15. return buffer;
  16. }
  17. public int readChar() {
  18. if(buffer != -1) {
  19. int r = buffer;
  20. buffer = -1;
  21. return r;
  22. }
  23. try {
  24. if(in.available() <= 0) {
  25. return -1;
  26. }
  27. int data = in.read();
  28. if((data & 0x80) != 0) // special char
  29. {
  30. if((data & 0x40) != 0) // this should always be true
  31. {
  32. if((data & 0x20) != 0) // 3 byte unicode
  33. {
  34. int a = in.read();
  35. int b = in.read();
  36. data = ((data & 0xF) << 12) | ((a & 0x3F) << 6) | (b & 0x3F);
  37. } else // 2 byte unicode
  38. {
  39. data = ((data & 0x1F) << 6) | (in.read() & 0x3F);
  40. }
  41. } else {
  42. // should not happen as unicode starts with 11
  43. }
  44. }
  45. return data;
  46. } catch(IOException ex) {
  47. return -1;
  48. }
  49. }
  50. }