1 // This file is part of Visual D
2 //
3 // Visual D integrates the D programming language into Visual Studio
4 // Copyright (c) 2010-2011 by Rainer Schuetze, All Rights Reserved
5 //
6 // Distributed under the Boost Software License, Version 1.0.
7 // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
8 
9 module stdext.array;
10 
11 T* contains(T)(T[] arr, bool delegate(ref T t) dg)
12 {
13     foreach(ref T t; arr)
14         if (dg(t))
15             return &t;
16     return null;
17 }
18 
19 T* contains(T)(T[] arr, T val)
20 {
21     foreach(ref T t; arr)
22         if (t == val)
23             return &t;
24     return null;
25 }
26 
27 int arrIndex(T)(in T[] arr, T val)
28 {
29     for(int i = 0; i < arr.length; i++)
30         if (arr[i] == val)
31             return i;
32     return -1;
33 }
34 
35 int arrIndexPtr(T)(in T[] arr, T val)
36 {
37     for(int i = 0; i < arr.length; i++)
38         if (arr[i] is val)
39             return i;
40     return -1;
41 }
42 
43 void addunique(T)(ref T[] arr, T val)
44 {
45     if (!contains(arr, val))
46         arr ~= val;
47 }
48 
49 void addunique(T)(ref T[] arr, T[] vals)
50 {
51     foreach(val; vals)
52         if (!contains(arr, val))
53             arr ~= val;
54 }
55 
56 void remove(T)(ref T[] arr, T val)
57 {
58     int idx = arrIndex(arr, val);
59     if(idx >= 0)
60         arr = arr[0..idx] ~ arr[idx+1..$];
61 }
62 
63 void adduniqueLRU(T)(ref T[] arr, T val, size_t maxEntries)
64 {
65     for(size_t i = 0; i < arr.length; i++)
66         if(val == arr[i])
67         {
68             // move to front
69             if(i > 0)
70                 arr = [val] ~ arr[0..i] ~ arr[i+1 .. $];
71             return;
72         }
73 
74     if(arr.length >= maxEntries)
75         arr.length = maxEntries - 1;
76     arr = [val] ~ arr;
77 }
78 
79 ///////////////////////////////////////////////////////////////////////
80 
81 struct Set(T)
82 {
83     bool[T] _payload;
84 
85     alias _payload this;
86 
87     T first()
88     {
89         foreach(n, b; _payload)
90             return n;
91         return null;
92     }
93 }
94 
95 bool contains(T)(ref bool[T] arr, T val)
96 {
97     return (val in arr);
98 }
99 
100 void addunique(T)(ref bool[T] arr, T val)
101 {
102     arr[val] = true;
103 }
104 
105 void addunique(T)(ref bool[T] arr, T[] vals)
106 {
107     foreach(val; vals)
108         arr[val] = true;
109 }
110 
111 void addunique(T)(ref bool[T] arr, bool[T] vals)
112 {
113     foreach(val, b; vals)
114         arr[val] = true;
115 }
116 
117 // needed in dmd 2.058beta
118 //version(none):
119 void addunique(T)(ref Set!T arr, T val)
120 {
121     arr[val] = true;
122 }
123 
124 void addunique(T)(ref Set!T arr, bool[T] vals)
125 {
126     foreach(val, b; vals)
127         arr[val] = true;
128 }
129 
130 void remove(T)(ref bool[T] arr, T val)
131 {
132     arr.remove(val);
133 }