/*
  crossword -- a crossword game
  Copyright (C) 2000 Falk Hueffner

  This program 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 of the License, or (at your option)
  any later version.
  
  This program 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.
  
  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  Place, Suite 330, Boston, MA 02111-1307 USA

  $Id: Trie.cc,v 1.5 2000/11/29 01:29:38 falk Exp $
*/

#include <assert.h>
#include <stdlib.h>		// for abort()
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

#include "Trie.hh"

Trie::Trie(const std::string& file) {
    assert(sizeof(int) == sizeof(TrieNode));
    assert(sizeof(TrieNode) == 4);
    int fd = open(file.c_str(), O_RDONLY);
    if (fd == -1) {
	perror("Can't open trie file");
	abort();
    }
    int length;
    if (read(fd, &length, sizeof(int)) != sizeof(int)) {
	perror("Can't read trie length");
	abort();
    }
    mapLength = sizeof(int) + length * sizeof(TrieNode);
    nodes = (TrieNode*) mmap(NULL, mapLength, PROT_READ, MAP_SHARED, fd, 0);
    if (nodes == (TrieNode*) -1) {
	perror("Can't mmap trie file");
	abort();
    }
    ++nodes;	// skip length header
    // FIXME Warn if mismatch of letters with bag
}

Trie::~Trie() {
    --nodes;	// reintroduce length header
    if (munmap((void*) nodes, mapLength) == -1) {
	perror("Can't mmunap trie file");
	abort();
    }
}

