Advertisement
Guest User

Untitled

a guest
May 19th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ld.nape;
  2.  
  3. $(import);
  4.  
  5. class Allocator {
  6.    
  7.     $(define local private var pool<T>:T;);
  8.    
  9.     //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  10.    
  11.     public function new() {}
  12.    
  13.     //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  14.    
  15.     $(define global public inline function alloc<T>() {
  16.         if(pool<T>==null) return new T();
  17.         else {
  18.             var ret = pool<T>;
  19.             pool<T> = ret.next;
  20.             return ret;
  21.         }
  22.     });
  23.    
  24.     //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  25.    
  26.     $(define global public inline function free<T>(obj:T) {
  27.         obj.next = pool<T>;
  28.         pool<T> = obj;
  29.     });
  30.    
  31.     //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  32.    
  33.     $(define global public inline function reserve<T>(num:UInt) {
  34.         while(num-->0) free<T>(new T());
  35.     });
  36. }
  37.  
  38. /* example
  39.  
  40. import ld.nape.Allocator;
  41.  
  42. class A {
  43.     public var next:A;
  44.     public function new() {}
  45. }
  46.  
  47. class Main {
  48.     static function main() {
  49.         var alloc = new Allocator();
  50.        
  51.         alloc.free<A>(new A());
  52.         var obj = alloc.alloc<A>();
  53.         alloc.reserve<A>(100);
  54.        
  55.         //no conflict with macro when using alloc as a variable name
  56.         //as alloc macro must take an argument.
  57.     }
  58. }
  59.  
  60. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement