--  Verada predefined library: the bodies of the arenas.
package body Verada.Containers.Arenas is
   procedure Insert (A : in out Arena; Item : Element_Type; H : out Handle) is
      Free : Positive := 1;
      Found : Boolean := False;
   begin
      --  the first slot that is free and has a generation left
      for I in 1 .. Capacity loop
         pragma Loop_Invariant (not Found);
         pragma Loop_Invariant (for all J in 1 .. I - 1 => A.Slots (J).Used or else A.Slots (J).Generation = Last_Generation);
         if not A.Slots (I).Used and then A.Slots (I).Generation < Last_Generation then
            Free := I;
            Found := True;
            exit;
         end if;
      end loop;
      pragma Assert (Found);
      A.Slots (Free).Used := True;
      A.Slots (Free).Value := Item;
      H := A.Slots (Free).Generation * Long_Long_Integer (Capacity) + Long_Long_Integer (Free);
   end Insert;

   procedure Replace_Element (A : in out Arena; H : Handle; Item : Element_Type) is
   begin
      A.Slots (Slot_Of (H)).Value := Item;
   end Replace_Element;

   procedure Remove (A : in out Arena; H : Handle) is
      S : constant Positive := Slot_Of (H);
   begin
      A.Slots (S).Used := False;
      if A.Slots (S).Generation < Last_Generation then
         A.Slots (S).Generation := A.Slots (S).Generation + 1;
      end if;
   end Remove;
end Verada.Containers.Arenas;
