/*
 * Example 9: RWDiskPageHeap. 
 *
 * $Id: example9.cpp,v 2.2 1993/08/07 17:03:51 keffer Exp $
 *
 ****************************************************************************
 *
 * Rogue Wave Software, Inc.
 * P.O. Box 2328
 * Corvallis, OR 97339
 * Voice: (503) 754-2311	FAX: (503) 757-7350
 *
 * Copyright (C) 1989 - 1993.
 * This software is subject to copyright protection under the laws of
 * the United States and other countries.
 *
 ***************************************************************************
 *
 * $Log: example9.cpp,v $
 * Revision 2.2  1993/08/07  17:03:51  keffer
 * Now checks to see whether swap file can be opened.
 *
 * Revision 2.1  1993/06/16  01:02:34  keffer
 * Added RCS keywords.
 *
 *
 */

#include <rw/diskpage.h>
#include <rw/rstream.h>

struct Node {
  int	key;
  RWHandle	next;
};

RWHandle head = 0;

const int N = 100;	// Exercise 100 Nodes

main() {

  // Construct a disk-based page heap with page size equal
  // to the size of Node and with 10 buffers:
  RWDiskPageHeap heap(0, 10, sizeof(Node));

  if (!heap.isValid())
  {
    cerr << "Unable to open temporary swap file.\n";
    cerr << "Do you have write privileges?\n" << flush;
    return 0;
  }

  // Build the linked list:
  for (int i=0; i<N; i++){
    RWHandle h = heap.allocate();
    Node* newNode = (Node*)heap.lock(h);
    newNode->key  = i;
    newNode->next = head;
    head = h;
    heap.dirty(h);
    heap.unlock(h);
  }

  // Now walk the list:
  unsigned count = 0;
  RWHandle nodeHandle = head;
  while(nodeHandle){
    Node* node = (Node*)heap.lock(nodeHandle);
    RWHandle nextHandle = node->next;
    heap.unlock(nodeHandle);
    heap.deallocate(nodeHandle);
    nodeHandle = nextHandle;
    count++;
  }

  cout << "List with " << count << " nodes walked.\n";

  // The following line should not be necessary, but a bug in Sun C++
  // requires it:
  cout.flush();

  return 0;
}

