-------------------------------------------------------------------------------
--
-- <STRONG>Copyright (c) 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 unit 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>
--
-- <DL><DT><STRONG>
-- Author:</STRONG><DD>
--   Thomas Wolf  (TW)
--   <ADDRESS><A HREF="mailto:twolf@acm.org">twolf@acm.org</A></ADDRESS></DL>
--
-- <DL><DT><STRONG>
-- Purpose:</STRONG><DD>
--   Provides dynamic hash tables. Internal collision resolution, automatic
--   and explicit resizing. Collision chain index computation can be customized
--   though <CODE>Collision_Policies</CODE>. Resizing can be controlled through
--   load factors and <CODE>Growth_Policies</CODE>.
--   <BR><BR>
--   This hash table does not allow associating additional data with the
--   items stored. However, only a portion of type @Item@ might be the actual
--   key, while additional components might hold associated data. In this
--   case, both @Hash@ and <CODE>"="</CODE> must work only on the key part
--   of @Item@.
--   <BR><BR>
--   Note that this hash table does not allow in-place modification of the
--   items stored since this might result in violations of the internal
--   consistency of the hash table.
--   <BR><BR>
--   A slightly more powerful (but also slightly more complex to instantiate)
--   hash table package taking separate @Key@ and @Item@ types and allowing
--   in-place modifications of the items (but not the keys) is available in
--   package <A HREF="gal-adt-hash_tables.html">GAL.ADT.Hash_Tables</A>.
--   </DL>
--
-- <DL><DT><STRONG>
-- Tasking semantics:</STRONG><DD>
--   N/A. Not abortion-safe.</DL>
--
-- <DL><DT><STRONG>
-- Storage semantics:</STRONG><DD>
--   Dynamic storage allocation in a user-supplied storage pool.</DL>
--
-- <!--
-- Revision 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.
-- -->
-------------------------------------------------------------------------------

pragma License (Modified_GPL);

with GAL.Storage.Memory;

with GAL.ADT.Hash_Tables;
with GAL.Support.Hashing;

generic
   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 Item)
          return GAL.Support.Hashing.Hash_Type is <>;

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

   with function Choose_Size
        (Suggested : in GAL.Support.Hashing.Hash_Type)
        return GAL.Support.Hashing.Size_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.Containers.Hash_Tables is

   pragma Elaborate_Body;

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

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

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

   Container_Error  : exception renames GAL.Containers.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;

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

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

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

   procedure Insert
     (Table   : in out Hash_Table;
      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;
      Element : access Item);

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

   procedure Replace
     (Table   : in out Hash_Table;
      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;
      Element : access Item);

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

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

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

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

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

   function Contains
     (Table   : in     Hash_Table;
      Element : access Item)
     return Boolean;

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

   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);
   --  Resizes the table to at least 'New_Size' slots.
   --
   --  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.
   --
   --  Raises Range_Error if the new size of the table would be larger than
   --  the number of elements in Hash_Type. (Note that the new size of the
   --  table may be *larger* than 'New_Size'!)

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

   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 exponential hashing, which seems to be least
   --  Susceptible to clustering (primary or secondary) and better than
   --  double hashing.
   --
   --  (Note however that better is relative anyway. Depending on the
   --  circumstances, linear probing may in fact be the most appropriate
   --  choice, as it exhibits a good access locality and thus may be a win on
   --  modern processor architctures with multi-level caching.)

   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;

   ----------------------------------------------------------------------------
   --  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);

   procedure Remove_Growth_Policy
     (Table : in out Hash_Table);

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

   function  Has_Growth_Policy
     (Table : in Hash_Table)
     return Boolean;

   function Get_Growth_Policy
     (Table : in Hash_Table)
     return GAL.Support.Hashing.Growth_Policy'Class;

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

   type Visitor is abstract tagged private;

   procedure Execute
     (V     : in out Visitor;
      Value : in     Item;
      Quit  : in out Boolean)
     is abstract;
   --  'Quit' is False upon entry; traversal continues until either all items
   --  in the hash table have been processed or 'Quit' is set to True.

   procedure Traverse
     (Table     : in     Hash_Table;
      V         : in out Visitor'Class);
   --  Calls 'Execute (V)' for all items currently in the hash table, until
   --  either all items have been processed or 'Execute' sets 'Quit' to True.

   generic
      with procedure Execute
           (Value : in     Item;
            Quit  : in out Boolean);
   procedure Traverse_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.

private
   package Impl is
      new GAL.ADT.Hash_Tables (Item, GAL.Support.Null_Type, Memory,
                               Initial_Size, Hash, "=", Choose_Size);

   type Visitor is abstract
     new Impl.Visitor with null record;

   procedure Action
     (V     : in out Visitor;
      Key   : in     Item;
      Value : in out GAL.Support.Null_Type;
      Quit  : in out Boolean);
   --  Dispatching call-through to 'Execute'.

   type Hash_Table is
      record
         Rep : Impl.Hash_Table;
      end record;

   Null_Hash_Table : constant Hash_Table := (Rep => Impl.Null_Hash_Table);

end GAL.Containers.Hash_Tables;







