stream.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var assert = require("assert.js").ok;
  2. var Class = require("rtl.js").Class;
  3. exports.Stream = Class.extend({
  4. init: function Stream(s){
  5. this.__s = s;
  6. this.__pos = 0;
  7. },
  8. str: function(n){return this.__s.substr(this.__pos, n);},
  9. char: function(){
  10. if (this.eof())
  11. return undefined;
  12. return this.__s.charAt(this.__pos++);
  13. },
  14. read: function(f){
  15. while (!this.eof() && f(this.peekChar()))
  16. this.next(1);
  17. return !this.eof();
  18. },
  19. peekChar: function(){
  20. if (this.eof())
  21. return undefined;
  22. return this.__s.charAt(this.__pos);
  23. },
  24. peekStr: function(size){
  25. var max = this.__s.length - this.__pos;
  26. if (size > max)
  27. size = max;
  28. return this.__s.substr(this.__pos, size);
  29. },
  30. next: function(n){
  31. assert(this.__pos + n <= this.__s.length);
  32. this.__pos += n;
  33. },
  34. pos: function(){return this.__pos;},
  35. setPos: function(pos){
  36. assert(pos <= this.__s.length);
  37. return this.__pos = pos;
  38. },
  39. eof: function(){return this.__pos == this.__s.length;},
  40. describePosition: function(){
  41. var line = this.__s.substr(0, this.__pos).split("\n").length;
  42. return "line " + line;
  43. }
  44. });