Lib.hx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. class Lib
  43. {
  44. /*
  45. public static inline function assert(value:Dynamic)
  46. {
  47. untyped __assert__(value);
  48. }
  49. public static function random(max:Int)
  50. {
  51. var r = new dart.math.Random(); //TODO(av) benchmark / test caching Random instance as static
  52. return r.nextInt(max);
  53. }
  54. */
  55. public static function print(v:Dynamic)
  56. {
  57. python.lib.Sys.stdout.write(Std.string(v));
  58. python.lib.Sys.stdout.flush();
  59. }
  60. public static function println(v:Array<Dynamic>)
  61. {
  62. for (e in v) {
  63. untyped __python__("print")(Std.string(e));
  64. }
  65. }
  66. public static function toPythonIterable <T>(it:Iterable<T>):python.lib.Types.NativeIterable<T>
  67. {
  68. return {
  69. __iter__ : function () {
  70. var it1 = it.iterator();
  71. var self:PyIterator<T> = null;
  72. self = new PyIterator({
  73. __next__ : function ():T {
  74. if (it1.hasNext()) {
  75. return it1.next();
  76. } else {
  77. throw new python.lib.Types.StopIteration();
  78. }
  79. },
  80. __iter__ : function () return self
  81. });
  82. return self;
  83. }
  84. }
  85. }
  86. public static inline function toHaxeIterable <T>(it:NativeIterable<T>):HaxeIterable<T>
  87. {
  88. return new HaxeIterable(it);
  89. }
  90. public static inline function toHaxeIterator <T>(it:NativeIterator<T>):HaxeIterator<T>
  91. {
  92. return new HaxeIterator(it);
  93. }
  94. }