view open.cpp @ 399:a65b31660804 api-inversion

Invert audioDB::dump / audiodb_dump(). No real API/ABI breakages, modulo the disappearance of audiodb_dump_withdir() (which really should have been audiodb_dump() itself from the start). There were of course ABI breakages in the previous commits. The dodgy thing in this patch is the horribleness of audiodb_dump() itself; there must be a better way of writing it, or at least abstracting some of the body into individual functional pieces. The declaration block at the top tells its own story. We also need to alter the way that audioDB::status handles the adb; rather than having a local variable, use the C++ audioDB object instance field and only open the database if necessary -- then everything has a consistent view.
author mas01cr
date Thu, 27 Nov 2008 15:19:49 +0000
parents 78fed0d4c108
children 58b88ab69424
line wrap: on
line source
#include "audioDB.h"
extern "C" {
#include "audioDB_API.h"
}

bool audiodb_check_header(adb_header_t *header) {
  /* FIXME: use syslog() or write to stderr or something to give the
     poor user some diagnostics. */
  if(header->magic == O2_OLD_MAGIC) {
    return false;
  }
  if(header->magic != O2_MAGIC) {
    return false;
  }
  if(header->version != O2_FORMAT_VERSION) {
    return false;
  }
  if(header->headerSize != O2_HEADERSIZE) {
    return false;
  }
  return true;
}

adb_t *audiodb_open(const char *path, int flags) {
  adb_t *adb = 0;
  int fd = -1;

  flags &= (O_RDONLY|O_RDWR);
  fd = open(path, flags);
  if(fd == -1) {
    goto error;
  }
  if(acquire_lock(fd, flags == O_RDWR)) {
    goto error;
  }

  adb = (adb_t *) malloc(sizeof(adb_t));
  if(!adb) {
    goto error;
  }
  adb->fd = fd;
  adb->flags = flags;
  adb->path = (char *) malloc(1+strlen(path));
  if(!(adb->path)) {
    goto error;
  }
  strcpy(adb->path, path);

  adb->header = (adb_header_t *) malloc(sizeof(adb_header_t));
  if(!(adb->header)) {
    goto error;
  }
  if(read(fd, (char *) adb->header, O2_HEADERSIZE) != O2_HEADERSIZE) {
    goto error;
  }
  if(!audiodb_check_header(adb->header)) {
    goto error;
  }

  return adb;

 error:
  if(adb) {
    if(adb->header) {
      free(adb->header);
    }
    if(adb->path) {
      free(adb->path);
    }
    free(adb);
  }
  if(fd != -1) {
    close(fd);
  }
  return NULL;
}