IntMap.hx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (C)2005-2012 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package haxe.ds;
  23. @:coreApi class IntMap<T> {
  24. private var h : Dynamic;
  25. public function new() : Void {
  26. h = untyped __new__(_global["Object"]);
  27. }
  28. public function set( key : Int, value : T ) : Void {
  29. h[key] = value;
  30. }
  31. public function get( key : Int ) : Null<T> {
  32. return h[key];
  33. }
  34. public function exists( key : Int ) : Bool {
  35. return untyped h["hasOwnProperty"](key);
  36. }
  37. public function remove( key : Int ) : Bool {
  38. if( untyped !h["hasOwnProperty"](key) ) return false;
  39. untyped __delete__(h,key);
  40. return true;
  41. }
  42. public function keys() : Iterator<Int> {
  43. var l : Array<Int> = untyped __keys__(h);
  44. for( x in 0...l.length )
  45. l[x] = Std.int(l[x]);
  46. return l.iterator();
  47. }
  48. public function iterator() : Iterator<T> {
  49. return untyped {
  50. ref : h,
  51. it : keys(),
  52. hasNext : function() { return __this__.it[__unprotect__("hasNext")](); },
  53. next : function() { var i = __this__.it[__unprotect__("next")](); return __this__.ref[i]; }
  54. };
  55. }
  56. public function toString() : String {
  57. var s = new StringBuf();
  58. s.add("{");
  59. var it = keys();
  60. for( i in it ) {
  61. s.add(i);
  62. s.add(" => ");
  63. s.add(Std.string(get(i)));
  64. if( it.hasNext() )
  65. s.add(", ");
  66. }
  67. s.add("}");
  68. return s.toString();
  69. }
  70. }