Преглед на файлове

Add "once" caching utility function

Billy Barrow преди 10 месеца
родител
ревизия
43130f70dc
променени са 3 файла, в които са добавени 36 реда и са изтрити 1 реда
  1. 22 0
      src/lib/Cache.vala
  2. 1 0
      src/lib/meson.build
  3. 13 1
      src/tests/Integration/Cache.vala

+ 22 - 0
src/lib/Cache.vala

@@ -0,0 +1,22 @@
+namespace Invercargill {
+
+    public delegate T CachedGet<T>();
+
+    private static Dictionary<int, NativeElement> cache;
+
+    public T once<T>(owned CachedGet<T> constructor) {
+        if(cache == null) {
+            cache = new Dictionary<int, NativeElement>();
+        }
+
+        int location = (int)constructor;
+        print(@"Location=$location\n");
+        NativeElement<T> element;
+        if(!cache.try_get(location, out element)) {
+            element = new NativeElement<T>(constructor());
+            cache.set(location, element);
+        }
+
+        return element.assert_as<T>();
+    }
+}

+ 1 - 0
src/lib/meson.build

@@ -24,6 +24,7 @@ sources += files('Converter.vala')
 sources += files('PropertyMapper.vala')
 sources += files('KeyValuePair.vala')
 sources += files('Attempt.vala')
+sources += files('Cache.vala')
 
 sources += files('Queries/Query.vala')
 sources += files('Queries/Transform.vala')

+ 13 - 1
src/tests/Integration/Cache.vala

@@ -21,4 +21,16 @@ void cache_tests() {
         assert_cmpint(64, CompareOperator.EQ, runs);
     });
 
-}
+    Test.add_func("/invercargill/cache/once", () => {
+        
+        var runs = 0;
+        CachedGet<int> func = () => once<int>(() => ++runs);
+
+        var enumerable = range(0, 64).select<int>(i => func()).to_vector();
+        
+        assert_cmpint(1, CompareOperator.EQ, runs);
+        assert_true(enumerable.all(i => i == 1));
+
+    });
+
+}