Friday, January 18, 2013

Generic array slice

Not sure if anyone created(in delphi) something similar yet, which should indicate that it's usage is very limited, but here it goes...

Ever played with huge arrays and you always have to copy chunks into smaller arrays which then you want to feed to some algorithm(or pass a bunch of indexes)? if yes, then you should know by now that a "slice of TYPE" functionality kinda', shoulda' be available by now in Delphi's compiler... anyhu' with the introduction of generics, we got the options to shoot ourselves in the foot or come up with good ideas, depending on your POV.

So, what is an array slice? Well, wiki says that it grabs a slice of an array and puts it into another array, cool, but that's a bit expensive because I have to copy a block of memory into another, we can surely do better than that, right? well, with generics we can:

procedure TestSlice;
  LIntList: TArray<Integer>;
  LSlice: TArraySlice<Integer>;
  Index: Integer;
   /// fill LIntList
   SetLength(LIntList, 10);
   for Index := Low(LIntList) to High(LIntList) do
     LIntList[Index] := Index;
   /// "grab" a slice of LIntList
   LSlice.SliceArray(LIntList, 0, 5);
   for Index := LSlice.Low to LSlice.High do

So, what are we doing in the code above? well, we're creating an array of 10 elements and we set the value of each element to be it's index in the array(I am lazy), next, we grab the first 5 elements from array as a slice and then we walk over the slice and print the elements, the output should be:

Pretty cool, huh? in case you're wondering, TArraySlice is a generic record, therefore initialization and finalization is done by compiler and it holds very little information(reference to "mother|main array", it's offset, count and original array size).

Here's the whole code of TArraySlice, very simple and yet powerful and incomplete (:

Not feeling like writing too much about it, after all it's a very simple thing so I'll let you have fun with it and if you find something useful to add and would like to share, feel free to comment.

Blogroll(General programming and Delphi feeds)