// B-tree map of numbers to numbers -*- c++ -*-

#ifndef BTREE_H_
# define BTREE_H_
# ifdef __GNUC__
#  pragma interface
# endif // __GNUC__

# include "file.h"

/** @file BTree.h
 * B-tree map of numbers to numbers
 */

/* Copyright © 2000-2002 Marko Mäkelä (msmakela@tcs.hut.fi).

   This file is part of MARIA, a reachability analyzer and model checker
   for high-level Petri nets.

   MARIA 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.

   MARIA is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   The GNU General Public License is often shipped with GNU software, and
   is generally kept in a file called COPYING or LICENSE.  If you do not
   have a copy of the license, write to the Free Software Foundation,
   59 Temple Place, Suite 330, Boston, MA 02111 USA. */

/** Size of the b-tree nodes (must be at least 8 and divisible by 4) */
# define BTREE_SIZE 512

/** B-tree map of numbers to numbers */
class BTree
{
public:
  /** Type of the numbers to be stored */
  typedef unsigned item_t;
  /** Constructor
   * @param file	Disk file containing the B-tree
   */
  explicit BTree (file_t file);
private:
  /** Copy constructor */
  BTree (const class BTree& old);
  /** Assignment operator */
  class BTree& operator= (const class BTree& old);
public:
  /** Destructor */
  ~BTree ();

  /** Search a tree
   * @param key		the key to be sought
   * @return		the values (item 0: amount of the values)
   */
  item_t* search (item_t key) const;
  /** Insert an item to the tree
   * @param key		the key
   * @param value	the value
   */
  void insert (item_t key, item_t value);

# ifdef USE_MMAP
  /** Close the file without truncating it */
  void cleanup () {
#  ifdef NO_MMAP
    if (myFile.addr) free (myFile.addr);
    myFile.addr = 0;
#  else // NO_MMAP
    if (myFile.addr) munmap (myFile.addr, myFile.alloc);
    close (myFile.fd);
    myFile.addr = 0, myFile.fd = -1;
#  endif // NO_MMAP
  }
# endif // USE_MMAP

  /** Truncate the file */
  void clear ();

private:
  /** The disk file containing the B-tree */
  file_t myFile;
# ifndef USE_MMAP
  /** Number of pages in the B-tree */
  unsigned myNumPages;
  /** Copy of the root node of the B-tree */
  item_t myRoot[BTREE_SIZE];
# endif // USE_MMAP
};

#endif // BTREE_H_
