Lib.hx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package python;
  2. import python.lib.Types;
  3. class HaxeIterable<T>
  4. {
  5. var x :NativeIterable<T>;
  6. public inline function new (x:NativeIterable<T>) {
  7. this.x = x;
  8. }
  9. public inline function iterator ():HaxeIterator<T> return new HaxeIterator(x.__iter__());
  10. }
  11. class HaxeIterator<T>
  12. {
  13. var it :NativeIterator<T>;
  14. var x:Null<T> = null;
  15. var has = false;
  16. var checked = false;
  17. public function new (it:NativeIterator<T>) {
  18. this.it = it;
  19. }
  20. public inline function next ():T
  21. {
  22. checked = false;
  23. return x;
  24. }
  25. public function hasNext ():Bool
  26. {
  27. if (checked) {
  28. return has;
  29. } else {
  30. try {
  31. x = it.__next__();
  32. has = true;
  33. } catch (s:StopIteration) {
  34. has = false;
  35. x = null;
  36. }
  37. checked = true;
  38. return has;
  39. }
  40. }
  41. }
  42. @:preCode("import sys as _hx_sys")
  43. class Lib
  44. {
  45. public static function print(v:Dynamic):Void {
  46. var str = Std.string(v);
  47. untyped __python__('_hx_sys.stdout.buffer.write(("%s"%str).encode(\'utf-8\'))');
  48. untyped __python__('_hx_sys.stdout.flush()');
  49. }
  50. public static function println(v:Dynamic):Void {
  51. var str = Std.string(v);
  52. untyped __python__('_hx_sys.stdout.buffer.write(("%s\\n"%str).encode(\'utf-8\'))');
  53. untyped __python__('_hx_sys.stdout.flush()');
  54. }
  55. public static function toPythonIterable <T>(it:Iterable<T>):python.lib.Types.NativeIterable<T>
  56. {
  57. return {
  58. __iter__ : function () {
  59. var it1 = it.iterator();
  60. var self:PyIterator<T> = null;
  61. self = new PyIterator({
  62. __next__ : function ():T {
  63. if (it1.hasNext()) {
  64. return it1.next();
  65. } else {
  66. throw new python.lib.Types.StopIteration();
  67. }
  68. },
  69. __iter__ : function () return self
  70. });
  71. return self;
  72. }
  73. }
  74. }
  75. public static inline function toHaxeIterable <T>(it:NativeIterable<T>):HaxeIterable<T>
  76. {
  77. return new HaxeIterable(it);
  78. }
  79. public static inline function toHaxeIterator <T>(it:NativeIterator<T>):HaxeIterator<T>
  80. {
  81. return new HaxeIterator(it);
  82. }
  83. }