diff dmd/Array.d @ 74:7e0d548de9e6

Switch Arrays of Dsymbols to the new templated Vector type
author Eldar Insafutdinov <e.insafutdinov@gmail.com>
date Sun, 29 Aug 2010 09:43:40 +0100
parents 2e2a5c3f943a
children ad4792a1cfd6
line wrap: on
line diff
--- a/dmd/Array.d	Sat Aug 28 19:42:41 2010 +0400
+++ b/dmd/Array.d	Sun Aug 29 09:43:40 2010 +0100
@@ -180,3 +180,133 @@
 		return copyTo(new Array());
 	}
 }
+
+class Vector(T)
+{
+public:
+    @property final uint dim()
+    {
+        return _dim;
+    }
+    
+    @property T *data()
+    {
+        return _data;
+    }
+    
+    @property final uint allocdim()
+    {
+        return _allocdim;
+    }
+    
+    T opIndex(uint index)
+    {
+        return _data[index];
+    }
+    
+    void opIndexAssign(T value, uint index)
+    {
+        _data[index] = value;
+    }
+    
+    final T pop()
+    {        
+        T v = _data[--_dim];
+        _data[dim] = T.init;
+        return v;
+    }
+    
+    final void push(T elem)
+    {
+        reserve(1);
+        _data[_dim++] = elem;
+    }
+    
+    final void reserve(uint nentries)
+	{
+        //printf("Array::reserve: size = %d, offset = %d, nbytes = %d\n", size, offset, nbytes);
+        if (allocdim - dim < nentries) {
+            _allocdim = dim + nentries;
+            _data = cast(T*)GC.realloc(_data, allocdim * T.sizeof);
+        }
+	}
+    
+    final void shift(T ptr)
+    {
+        reserve(1);
+        memmove(_data + 1, _data, _dim * T.sizeof);
+        _data[0] = ptr;
+        _dim++;
+    }
+
+    final Vector!T copy()
+	{
+		return copyTo(new Vector!T());
+	}
+
+	final Vector!T copyTo(Vector!T a)
+	{
+		a.setDim(dim);
+		memcpy(a._data, _data, dim * T.sizeof);
+        // TODO call postblits
+		return a;
+	}
+    
+    final void setDim(uint newdim)
+	{
+		if (dim < newdim) {
+			reserve(newdim - dim);
+		}
+
+		_dim = newdim;
+	}
+    
+    int opApply(scope int delegate(ref T) dg)
+    {
+        int result = 0;
+
+	    for (int i = 0; i < _dim; i++)
+	    {
+    	    result = dg(_data[i]);
+	        if (result)
+		        break;
+	    }
+	    return result;
+    }
+
+    int opApply(scope int delegate(ref int key, ref T value) dg)
+    {
+        int result = 0;
+        for (int i = 0; i < _dim; i++)
+        {
+            result = dg(i, _data[i]);
+            if(result)
+                break;
+        }
+        return result;
+    }
+    
+    final void append(Vector!T a)
+	{
+		insert(dim, a);
+	}
+    
+    final void insert(uint index, Vector!T a)
+	{
+		if (a !is null) {
+			uint d = a.dim;
+			reserve(d);
+
+			if (dim != index) {
+				memmove(_data + index + d, _data + index, (dim - index) * T.sizeof);
+			}
+
+			memcpy(_data + index, a._data, d * T.sizeof);
+			_dim += d;
+		}
+	}
+private:
+    T* _data = null;
+    uint _dim = 0;
+    uint _allocdim = 0;
+}
\ No newline at end of file