StreamCharReader.java 1.6 KB

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