DataReelDataReelC++ Transition Guide

Examples › Database Examples

database_defrag

C++17 or laterDataReel 6.4.3Portable C++ (tested on Linux)

Legacy: examples_database/defrag/testprog.cpp · Modern: examples_modern/database/defrag/modern.cpp

Modern equivalent of the defrag test: allocate objects of growing size, delete them, undelete every other one, and allocate again with the best fit and the first fit methods, showing how deleted blocks are reused. The addresses go in a std::vector (not a fixed array), the method is a loop over a std::array of {method, name} pairs with a C++17 structured binding, the statistics come back as a struct, and std::filesystem removes the file between the runs.

Legacy calls in this program

LegacyModern C++StandardNotes
gxString / UStringstd::string, std::string_viewC++98 / C++17string_view looks at text without copying it.
new / deleteautomatic objects, containers, std::unique_ptr / std::make_uniqueC++11 / C++14Ownership is in the type, and release() shows a hand-over.
clock(), SysTime, GetSystemTime()std::chrono::steady_clock (elapsed), system_clock (calendar)C++11clock() is CPU time, not elapsed time.
gxDatabasekeep gxDatabase: a stack object, errors as exceptions, static_assert(std::is_trivially_copyable_v<Record>)C++17The standard library has no database file; the file format is DataReel's.

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_database/defrag/testprog.cpp 229 lines
#include "gxdlcode.h"

#if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library
#include <iostream>
using namespace std; // Use unqualified names for Standard C++ library
#else // Use the old iostream library by default
#include <iostream.h>
#endif // __USE_ANSI_CPP__

#include <time.h>
#include "gxdbase.h"
#include "gxdstats.h"
#include "ustring.h"

void PausePrg()
{
  cout << "\n";
  cout << "Press enter to continue..." << "\n";
  cin.get();
}

clock_t Start()
// Mark the starting time for the routine.
{
  return clock();
}

clock_t Stop()
// Mark the stop time for the routine. 
{
  return clock();
}

double ElapsedTime(clock_t begin, clock_t end)
// Calculate the elapsed time in milliseconds. 
{
  return (double)(end - begin) / CLOCKS_PER_SEC;
}

void DefragStats(gxDatabase *f)
{
  UString intbuf;
  FAU_t td, d, r, n, t;
  t = f->TotalBlocks();
  n = f->NormalBlocks();
  td = f->DeletedBlocks(&d, &r);
  
  cout << "\n";
  
  intbuf << clear << t;
  cout << "Number of blocks allocated: " << intbuf.c_str() << "\n";
  intbuf << clear << n;
  cout << "Total blocks in use: " << intbuf.c_str() << "\n";
  intbuf << clear << d;
  cout << "Total deleted/removed:  " << intbuf.c_str() << "/";
  intbuf << clear << r;
  cout << intbuf.c_str() << " (";
  intbuf << clear << td;
  cout << intbuf.c_str() << ")" << "\n";
}

void TestReclaimMethod(gxDatabaseReclaimMethod reclaim_method,
		       char rev_letter)
{
  const int NumObjects = 100; // Number of objects to allocate
  const char *fname = "defrag.gxd";
  
  gxDatabase *f = new gxDatabase;

  cout << "\n";
  cout << "Testing the best-fit/first-fit allocation methods." << "\n";
  
  if(reclaim_method == gxDBASE_RECLAIM_BESTFIT) {
  cout << "\n";
  cout << "Using the best-fit method to reclaim deleted/removed blocks."
       << "\n";
  }
  else { 
  cout << "\n";
  cout << "Using the first-fit method to reclaim deleted/removed blocks."
       << "\n";
  }

  if(!gxDatabase::Exists(fname)) {
    cout << "Creating new file..." << "\n";
    f->Create(fname, (FAU_t)0, rev_letter);
    if(CheckError(f) != 0) {
      delete f;
      return;
    }
  }
  else {
    cout << "Opening existing file..." << "\n";
    f->Open(fname);
    if(CheckError(f) != 0) {
      delete f;
      return;
    }
  }

  PausePrg();
  DatabaseStats(f);
  PausePrg();

  FAU_t addr;

  FAU_t addr_list[NumObjects];
  char data = 'X';
  int i,j;

  cout << "Adding " << NumObjects << " objects to the file." << "\n";
  cout << "Objects range from " << sizeof(data) << " to " << NumObjects
       << " bytes in length"
       << "\n";
  cout << "Writing..." << "\n";
  
  clock_t Begin = Start();
  for(i = 0; i < NumObjects; i++) {
    addr = f->Alloc(sizeof(data)+i, reclaim_method);
    addr_list[i] = addr; // Store the address of each node allocated
    for(j = 0; j <= i; j++) {
      f->Write(&data, sizeof(data), addr+j, 0, 0);
    }
  }
  clock_t End = Stop();

  cout.precision(3);
  cout << "Comleted in " << ElapsedTime(Begin, End) << " seconds" << "\n";
  DefragStats(f);
  PausePrg();
  
  cout << "Deleting all the blocks allocated that were just allocated."
       << "\n";
  cout << "Working..." << "\n";
  
  Begin = Start();
  for(i = 0; i < NumObjects; i++) f->Delete(addr_list[i]);;
  End = Stop();
  
  cout.precision(3);
  cout << "Comleted in " << ElapsedTime(Begin, End) << " seconds" << "\n";
  DefragStats(f);
  PausePrg();
  
  cout << "Fragmenting the file." << "\n";
  cout << "Undeleting every other block that was just deleted."
       << "\n";
  cout << "Working..." << "\n";
  
  Begin = Start();
  for(i = 0; i < NumObjects; i++) {
    f->UnDelete(addr_list[i]);
    i++; // Skip to the next block
  }
  End = Stop();
  
  cout.precision(3);
  cout << "Comleted in " << ElapsedTime(Begin, End) << " seconds" << "\n";
  DefragStats(f);
  PausePrg();
  
  cout << "Adding " << NumObjects << " objects to the file." << "\n";
  cout << "All objects are " << sizeof(data) << " bytes in length."
       << "\n";
  cout << "Writing..." << "\n";

  Begin = Start();
  for(i = 0; i < NumObjects; i++) {
    f->Alloc(sizeof(data), reclaim_method);
    f->Write(&data, sizeof(data), gxCurrAddress, 0, 0);
  }
  End = Stop();
  
  cout.precision(3);
  cout << "Comleted in " << ElapsedTime(Begin, End) << " seconds" << "\n";
  DefragStats(f);
  PausePrg();
  
  int offset = 1;
  cout << "Adding " << NumObjects << " objects to the file." << "\n";
  cout << "Objects range from " << (sizeof(data) + offset) << " to "
       << (NumObjects + offset) << " bytes in length"
       << "\n";
  cout << "Writing..." << "\n";

  Begin = Start();
  for(i = 0; i < NumObjects; i++) {
    addr = f->Alloc((sizeof(data)+i)+offset, reclaim_method);
    for(j = 0; j <= i; j++)
      f->Write(&data, sizeof(data), (addr+j)+offset, 0, 0);
  }
  End = Stop();  

  cout.precision(3);
  cout << "Comleted in " << ElapsedTime(Begin, End) << " seconds" << "\n";
  DefragStats(f);

  cout << "\n";
  cout << "Exiting..." << "\n";
  f->Close();
  if(CheckError(f) != 0) return;
  delete f;
}

int main(int argv, char **argc)
{
  char rev_letter = gxDatabaseRevisionLetter; // Set the default rev letter
  if(argv == 2) { // Set a specified revision letter
    rev_letter = *argc[1];
    if(rev_letter == '0') rev_letter = '\0';
    // Valid rev letters are:
    // Rev 0
    // Rev 'A' or 'a'
    // Rev 'B' or 'b'
    // Rev 'C' or 'c'
    // Rev 'D' or 'd'
    // Rev 'E' or 'e'
    // NOTE: The gxDatabase class will set invalid revision letters
    // to the version set by the gxDatabaseRevisionLetter constant.  
  }

  TestReclaimMethod(gxDBASE_RECLAIM_BESTFIT, rev_letter);
  TestReclaimMethod(gxDBASE_RECLAIM_FIRSTFIT, rev_letter);
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/database/defrag/modern.cpp 74 lines
#include <array>
#include <filesystem>
#include <iostream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "gxdbase.h"

struct Stats { FAU_t total, deleted, removed, eof; };

Stats stats(gxDatabase &f)
{
  FAU_t d = 0, r = 0;
  f.DeletedBlocks(&d, &r);
  return {f.TotalBlocks(), d, r, FAU_t(f.GetEOF())};
}

void print(std::string_view what, const Stats &s)
{
  std::cout << "  " << what << ": blocks " << s.total << ", deleted "
            << s.deleted << ", removed " << s.removed << ", file size "
            << s.eof << "\n";
}

int main()
{
  const std::array<std::pair<gxDatabaseReclaimMethod, std::string_view>, 2>
    methods = {{{gxDBASE_RECLAIM_BESTFIT, "best fit"},
                {gxDBASE_RECLAIM_FIRSTFIT, "first fit"}}};
  const std::filesystem::path fname = "modern_defrag.gxd";
  const int NumObjects = 100;
  bool ok = true;

  for(const auto &[method, name] : methods) {
    std::filesystem::remove(fname);
    gxDatabase f;
    if(f.Create(fname.string().c_str()) != gxDBASE_NO_ERROR) return 1;
    std::cout << "Reclaim method: " << name << "\n";

    std::vector<FAU_t> addrs;
    for(int i = 0; i < NumObjects; i++) {
      std::string data(std::size_t(i) + 1, 'X');   // Objects of 1..100 bytes
      FAU_t a = f.Alloc(__ULWORD__(data.size()), method);
      f.Write(data.data(), __ULWORD__(data.size()), a);
      addrs.push_back(a);
    }
    print("allocated", stats(f));

    for(FAU_t a : addrs) f.Delete(a);
    print("deleted all", stats(f));

    for(std::size_t i = 0; i < addrs.size(); i += 2) f.UnDelete(addrs[i]);
    print("undeleted every other one", stats(f));

    FAU_t eof = FAU_t(f.GetEOF());
    for(int i = 0; i < NumObjects / 2; i++) {
      std::string data(std::size_t(i % 50) + 1, 'Y');
      FAU_t a = f.Alloc(__ULWORD__(data.size()), method);
      f.Write(data.data(), __ULWORD__(data.size()), a);
    }
    Stats s = stats(f);
    print("allocated 50 more", s);
    std::cout << "  file grew by " << s.eof - eof << " bytes\n";
    ok = ok && f.GetDatabaseError() == gxDBASE_NO_ERROR;
  }
  std::filesystem::remove(fname);
  return ok ? 0 : 1;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target database_defrag
./build-modern/database_defrag

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

Reclaim method: best fit
  allocated: blocks 100, deleted 0, removed 0, file size 8346
  deleted all: blocks 100, deleted 100, removed 0, file size 8346
  undeleted every other one: blocks 100, deleted 50, removed 0, file size 8346
  allocated 50 more: blocks 134, deleted 0, removed 34, file size 8346
  file grew by 0 bytes
Reclaim method: first fit
  allocated: blocks 100, deleted 0, removed 0, file size 8346
  deleted all: blocks 100, deleted 100, removed 0, file size 8346
  undeleted every other one: blocks 100, deleted 50, removed 0, file size 8346
  allocated 50 more: blocks 133, deleted 23, removed 10, file size 8926
  file grew by 580 bytes