-------------------------------------------------------------------------------
--
--  <STRONG>Copyright &copy; 2001, 2002 by Thomas Wolf.</STRONG>
--  <BLOCKQUOTE>
--    This piece of software is free software; you can redistribute it and/or
--    modify it under the terms of the  GNU General Public License as published
--    by the Free Software  Foundation; either version 2, or (at your option)
--    any later version. This software is distributed in the hope that it will
--    be useful, but <EM>without any warranty</EM>; without even the implied
--    warranty of <EM>merchantability or fitness for a particular purpose.</EM>
--    See the GNU General Public License for  more details. You should have
--    received a copy of the GNU General Public License with this distribution,
--    see file "<A HREF="GPL.txt">GPL.txt</A>". If not, write to the Free
--    Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
--    USA.
--  </BLOCKQUOTE>
--  <BLOCKQUOTE>
--    As a special exception from the GPL, if other files instantiate generics
--    from this unit, or you link this unit with other files to produce an
--    executable, this unit does not by itself cause the resulting executable
--    to be covered by the GPL. This exception does not however invalidate any
--    other reasons why the executable file might be covered by the GPL.
--  </BLOCKQUOTE>
--
--  <AUTHOR>
--    Thomas Wolf  (TW) <E_MAIL>
--  </AUTHOR>
--
--  <PURPOSE>
--    Provides dynamic hash tables. Internal collision resolution, automatic
--    and explicit resizing. Collision chain index computation can be
--    customized though @Collision_Policies@.
--  </PURPOSE>
--
--  <NOT_TASK_SAFE>
--
--  <USER_DEF_STORAGE>
--
--  <HISTORY>
--    20-DEC-2001   TW  Initial version.
--    28-DEC-2001   TW  Added growth policies.
--    24-APR-2002   TW  Added the 'Choose_Size' generic formal function.
--  </HISTORY>
-------------------------------------------------------------------------------

pragma License (Modified_GPL);

with Ada.Finalization;
with Ada.Streams;

with GAL.Storage.Memory;
with GAL.Support.Hashing;

generic
   type Key_Type (<>) is private;
   type Item (<>)     is private;

   with package Memory is new GAL.Storage.Memory (<>);

   Initial_Size : in GAL.Support.Hashing.Size_Type := 23;

   with function Hash
          (Element : in Key_Type)
          return GAL.Support.Hashing.Hash_Type is <>;

   with function "="  (Left, Right : in Key_Type) return Boolean is <>;

   with function Choose_Size
          (Suggested : in GAL.Support.Hashing.Hash_Type)
          return GAL.Support.Hashing.Hash_Type
          is GAL.Support.Hashing.Next_Prime;
   --  This function is called whenever the size of the hash table is to be
   --  defined. 'Suggested' is the suggested size of the new table; the
   --  function should then return a size that is >= Suggested. If it
   --  returns a smaller value anyway, the exception 'Container_Error' is
   --  raised.

package GAL.ADT.Hash_Tables is

   pragma Elaborate_Body;

   ----------------------------------------------------------------------------
   --  Exception renamings to facilitate usage of this package.

   Container_Empty  : exception renames GAL.ADT.Container_Empty;
   Container_Full   : exception renames GAL.ADT.Container_Full;
   Range_Error      : exception renames GAL.ADT.Range_Error;
   Not_Found        : exception renames GAL.ADT.Not_Found;
   Duplicate_Key    : exception renames GAL.ADT.Duplicate_Key;

   Hash_Table_Empty : exception renames Container_Empty;
   Hash_Table_Full  : exception renames Container_Full;

   Container_Error  : exception renames GAL.ADT.Container_Error;

   ----------------------------------------------------------------------------

   type Hash_Table is private;
   --  Hash tables are initially empty; no storage allocation occurs yet.
   --  Virgin hash tables do not resize themselves when full!
   --
   --  Some routines specify explicit (minimum) sizes for a hash table. Note
   --  that an implementation is free to choose a larger size if it so
   --  desires.

   Null_Hash_Table : constant Hash_Table;

   type Item_Ptr is access all Item;
   for Item_Ptr'Storage_Size use 0;

   ----------------------------------------------------------------------------

   procedure Swap
     (Left, Right : in out Hash_Table);
   --  Exchanges the two tables without making a temporary copy.

   ----------------------------------------------------------------------------

   procedure Insert
     (Table   : in out Hash_Table;
      Key     : in     Key_Type;
      Element : in     Item);
   --  Raises @Container_Full@ if the hash table is full and automatic resizing
   --  is off (the table's resize load factor is 0.0), and @Duplicate_Key@ if
   --  if an item with an equal key already is in the table.

   procedure Insert
     (Table   : in out Hash_Table;
      Key     : in     Key_Type;
      Element : access Item);

   ----------------------------------------------------------------------------

   procedure Replace
     (Table   : in out Hash_Table;
      Key     : in     Key_Type;
      Element : in     Item);
   --  If the key already exists in the hash table, replaces the associated
   --  item. Otherwise inserts the element and its key.

   procedure Replace
     (Table   : in out Hash_Table;
      Key     : in     Key_Type;
      Element : access Item);

   ----------------------------------------------------------------------------

   procedure Delete
     (Table : in out Hash_Table;
      Key   : in     Key_Type);
   --  Raises @Container_Empty@ if the table is empty, and @Not_Found@ if the
   --  key is not in the table.

   procedure Delete
     (Table   : in out Hash_Table;
      Key     : in     Key_Type;
      Element :    out Item);

   ----------------------------------------------------------------------------

   function Retrieve
     (Table : in Hash_Table;
      Key   : in Key_Type)
     return Item;
   --  Raises @Container_Empty@ if the table is empty, and @Not_Found@ if the
   --  key is not in the table.

   function Contains
     (Table : in Hash_Table;
      Key   : in Key_Type)
     return Boolean;
   --  Returns @False@ if the table is empty or the key is not in the table,
   --  @True@ if it is.

   ----------------------------------------------------------------------------

   function Nof_Elements
     (Table : in Hash_Table)
     return GAL.Support.Hashing.Hash_Type;

   function Is_Empty
     (Table : in Hash_Table)
     return Boolean;

   function Load
     (Table : in Hash_Table)
     return GAL.Support.Hashing.Load_Factor;

   function Size
     (Table : in Hash_Table)
     return GAL.Support.Hashing.Hash_Type;

   ----------------------------------------------------------------------------

   procedure Resize
     (Table    : in out Hash_Table;
      New_Size : in     GAL.Support.Hashing.Size_Type);
   --  Raises @Container_Error@ without modifying @Table@ if @New_Size@ is so
   --  small that the table couldn't hold all the elements it currently
   --  contains.
   --
   --  An alternative would be not to change the table at all, without raising
   --  an exception. However, I think an attempt to shrink a hash table
   --  through @Resize@ below the current number of elements in the table
   --  should be seen as an application error.

   ----------------------------------------------------------------------------

   procedure Reset
     (Table : in out Hash_Table);

   procedure Reset
     (Table    : in out Hash_Table;
      New_Size : in     GAL.Support.Hashing.Size_Type);

   procedure Reset
     (Table     : in out Hash_Table;
      New_Size  : in     GAL.Support.Hashing.Size_Type;
      Resize_At : in     GAL.Support.Hashing.Load_Factor);

   ----------------------------------------------------------------------------

   procedure Merge
     (Result : in out Hash_Table;
      Source : in     Hash_Table);
   --  Raises @Duplicate_Key@ without modifying @Result@ if @Source@ contains
   --  a key already in @Result@.

   procedure Merge
     (Result    : in out Hash_Table;
      Source    : in     Hash_Table;
      Overwrite : in     Boolean);
   --  Same as above, but different duplicate key handling: if @Overwrite@ is
   --  true, items already in @Result@ are overwritten by the items from
   --  @Source@; otherwise, the items in @Result@ remain unchanged.

   ----------------------------------------------------------------------------
   --  Collision chain management. Every hash table has a collision policy;
   --  the default is to do double hashing.

   procedure Set_Collision_Policy
     (Table  : in out Hash_Table;
      Policy : in     GAL.Support.Hashing.Collision_Policy'Class);
   --  If @Table@ is not empty, this causes re-hashing!

   procedure Remove_Collision_Policy
     (Table : in out Hash_Table);
   --  If @Table@ is not empty, and the current policy is not already the
   --  default one, this causes re-hashing!

   procedure Set_Default_Collision_Policy
     (Table : in out Hash_Table)
     renames Remove_Collision_Policy;

   function Get_Collision_Policy
     (Table : in Hash_Table)
     return GAL.Support.Hashing.Collision_Policy'Class;
   --  Raises @Constraint_Error@ if the @Table@ does not have a collision
   --  policy, which implies that it has been assigned the @Null_Hash_Table@,
   --  and no insertions have yet taken place.

   ----------------------------------------------------------------------------
   --  Growth management. See GAL.Containers.Vectors for more comments. By
   --  default, a hash table has no growth policy and therefore doesn't
   --  grow automatically but raises Container_Full in case (2) below.
   --
   --  The increase operation is called to get the new size:
   --
   --    1. In 'Insert', if the resize load factor > 0.0 and the table's load
   --       would be greater after inserting.
   --
   --    2. In 'Insert', if no empty slot can be found.

   ----------------------------------------------------------------------------

   procedure Set_Resize
     (Table     : in out Hash_Table;
      Resize_At : in     GAL.Support.Hashing.Load_Factor);
   --  If @Resize_At@ = 0.0, the table resizes only if it is full and a growth
   --  policy is set.

   procedure Set_Growth_Policy
     (Table  : in out Hash_Table;
      Policy : in     GAL.Support.Hashing.Growth_Policy'Class);
   --  Removes the current growth policy of @Table@ (if any), and installs a
   --  copy of @Policy@ as the table's new growth policy.

   procedure Remove_Growth_Policy
     (Table : in out Hash_Table);
   --  Removes the current growth policy of @Table@ (if any).

   procedure Set_Default_Growth_Policy
     (Table : in out Hash_Table)
     renames Remove_Growth_Policy;

   function  Has_Growth_Policy
     (Table : in Hash_Table)
     return Boolean;
   --  Returns @True@ if a growth policy is defined for @Table@.

   function Get_Growth_Policy
     (Table : in Hash_Table)
     return GAL.Support.Hashing.Growth_Policy'Class;
   --  Raises @Constraint_Error@ if no growth policy has been set on @Table@.

   ----------------------------------------------------------------------------
   --  Traversals:

   type Visitor is abstract tagged private;

   procedure Action
     (V     : in out Visitor;
      Key   : in     Key_Type;
      Value : in out Item;
      Quit  : in out Boolean);

   procedure Action
     (V     : in out Visitor;
      Key   : in     Key_Type;
      Value : access Item;
      Quit  : in out Boolean);

   procedure Traverse
     (Table     : in     Hash_Table;
      V         : in out Visitor'Class;
      Reference : in     Boolean := False);

   generic
      with procedure Execute
           (Key   : in     Key_Type;
            Value : in out Item;
            Quit  : in out Boolean);
   procedure Traverse_G
     (Table : in Hash_Table);

   generic
      with procedure Execute
           (Key   : in     Key_Type;
            Value : access Item;
            Quit  : in out Boolean);
   procedure Traverse_By_Reference_G
     (Table : in Hash_Table);

   ----------------------------------------------------------------------------
   --  Comparisons

   function "="
     (Left, Right : in Hash_Table)
     return Boolean;
   --  Returns true if the two hash tables contain the same number of elements
   --  with the same keys, False otherwise.

   generic
      with function "=" (Left, Right : in Item) return Boolean is <>;
   function Equals
     (Left, Right : in Hash_Table)
     return Boolean;
   --  Ditto, but also requires the values associated with the keys to be
   --  equal.

   ----------------------------------------------------------------------------
   --  Unsafe pointer operations. All these operations return Item_Ptrs, which
   --  point directly into the list. Of course, such pointers are unsafe
   --  because they are not invalidated when the element pointed to is deleted.
   --  Item_Ptrs can thus become dangling, and any dereference of an Item_Ptr
   --  after the element pointed to has vanished is a bounded error.
   --    Nevertheless, Item_Ptrs are sometimes a convenient and efficient way
   --  to get at and work with the stored elements, especially if the element
   --  type is a large record.

   package Unsafe is

      function Retrieve
        (Table : in Hash_Table;
         Key   : in Key_Type)
        return Item_Ptr;
      --  Returns @null@ if no such element exists in the hash table.

   end Unsafe;

private

   function "=" (Left, Right : in Item) return Boolean
      is abstract;
   --  Make sure we don't use (the default) equality of items; we only want
   --  to use equality on keys!

   type Collision_Policy_Ptr is
     access all GAL.Support.Hashing.Collision_Policy'Class;
   for Collision_Policy_Ptr'Storage_Pool use Memory.Pool;

   type Growth_Policy_Ptr is
     access all GAL.Support.Hashing.Growth_Policy'Class;
   for Growth_Policy_Ptr'Storage_Pool use Memory.Pool;

   type Key_Ptr is access Key_Type;
   for Key_Ptr'Storage_Pool use Memory.Pool;

   type Data_Ptr is access all Item;
   for Data_Ptr'Storage_Pool use Memory.Pool;

   type Hash_State is (Empty, Deleted, Used);

   type Hash_Entry is
      record
         Key   : Key_Ptr    := null;
         Value : Data_Ptr   := null;
         State : Hash_State := Empty;
      end record;

   type Mem is array (GAL.Support.Hashing.Hash_Type range <>) of Hash_Entry;
   type Ptr is access Mem;
   for Ptr'Storage_Pool use Memory.Pool;

   type Hash_Table is new Ada.Finalization.Controlled with
      record
         Count             : GAL.Support.Hashing.Hash_Type   := 0;
         Table             : Ptr                             := null;
         Collisions        : Collision_Policy_Ptr            := null;
         Growth            : Growth_Policy_Ptr               := null;
         Resize_At         : GAL.Support.Hashing.Load_Factor := 0.0;
         Initial_Size      : GAL.Support.Hashing.Size_Type   :=
           GAL.ADT.Hash_Tables.Initial_Size;
      end record;

   procedure Adjust     (Table : in out Hash_Table);
   procedure Finalize   (Table : in out Hash_Table);

   --  Stream support:

   procedure Write
     (Stream : access Ada.Streams.Root_Stream_Type'Class;
      Table  : in     Hash_Table);

   procedure Read
     (Stream : access Ada.Streams.Root_Stream_Type'Class;
      Table  :    out Hash_Table);

   for Hash_Table'Write use Write;
   for Hash_Table'Read  use Read;

   Null_Hash_Table : constant Hash_Table :=
     (Ada.Finalization.Controlled with
        Count             => 0,
        Table             => null,
        Collisions        => null,
        Growth            => null,
        Resize_At         => 0.0,
        Initial_Size      => 1);

   pragma Inline (Insert, Replace);

   type Visitor is abstract tagged null record;

end GAL.ADT.Hash_Tables;







