Quellcode durchsuchen

Add group_by to enumerable, index_of to vector, and write_to to BinaryData

Billy Barrow vor 1 Jahr
Ursprung
Commit
ce8e110d2a

+ 9 - 2
src/lib/Collections/BinaryData.vala

@@ -92,9 +92,9 @@ namespace Invercargill {
         }
         
         private uint8[] get_string_data(string str, bool remove_null_termination) {
-            var data = (uint8[])str;
+            var data = str.data;
             if(remove_null_termination) {
-                data = data[0:-1];
+                data = data[0:data.length-1];
             }
             return data;
         }
@@ -309,6 +309,13 @@ namespace Invercargill {
             return element_type.is_a(typeof(uint8));
         }
 
+        public size_t write_to(void* array, size_t max_size) {
+            var data = to_array();
+            var size = max_size > data.length ? data.length : max_size;
+            Memory.copy(array, data, size);
+            return size;
+        }
+
     }
 
 }

+ 11 - 0
src/lib/Collections/Vector.vala

@@ -182,6 +182,17 @@ namespace Invercargill {
             return array[index];
         }
 
+        public int index_of(PredicateDelegate<T> predicate) {
+            var i = -1;
+            foreach (var item in this) {
+                i++;
+                if(predicate(item)) {
+                    return i;
+                }
+            }
+            return -1;
+        }
+
         private class VectorTracker<T> : Tracker<T> {
 
             private T? next_item = null;

+ 5 - 0
src/lib/Enumerable.vala

@@ -222,6 +222,11 @@ namespace Invercargill {
             return new UniqueQuery<T>(this, (owned)comparison);
         }
 
+        public virtual Enumerable<Grouping<TKey, T>> group_by<TKey>(TransformDelegate<T, TKey> key_selector, EqualityDelegate<TKey> key_equality) {
+            var keys = select<TKey>(i => key_selector(i)).unique((a, b) => key_equality(a, b));
+            return keys.select<Grouping<TKey, T>>(g => new Grouping<TKey, T>(g, this.where(i => key_equality(g, key_selector(i)))));
+        }
+
         public virtual Enumerable<T> with(T item) {
             var seq = new Series<T>();
             seq.add(item);

+ 15 - 0
src/lib/Grouping.vala

@@ -0,0 +1,15 @@
+
+namespace Invercargill {
+
+    public class Grouping<TKey, TItems> {
+
+        public TKey key {get; set;}
+        public Enumerable<TItems> items {get; set;}
+
+        public Grouping(TKey key, Enumerable<TItems> items) {
+            this.key = key;
+            this.items = items;
+        }
+    }
+
+}

+ 1 - 0
src/lib/meson.build

@@ -16,6 +16,7 @@ sources += files('SelectionContext.vala')
 sources += files('Convert.vala')
 sources += files('Safety.vala')
 sources += files('Promotion.vala')
+sources += files('Grouping.vala')
 
 sources += files('Queries/Query.vala')
 sources += files('Queries/Transform.vala')