view helpgen/topic.c @ 9:60b08b68c750

Switch to static inline as an expedient build fix. Should probably set this up with working C99 inline but for the moment I don't have the energy.
author David A. Holland
date Mon, 30 May 2022 23:56:45 -0400
parents 13d2b8934445
children
line wrap: on
line source

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "utils.h"
#include "topic.h"

#define MAXTITLES 16
#define MAXREFS   64

struct topic {
  char *titles[MAXTITLES];
  int numtitles;
  char *refs[MAXREFS];
  int numrefs;
  char *body;
};

struct topic *topic_create(void) {
  struct topic *t = domalloc(sizeof(struct topic));
  t->numtitles = 0;
  t->numrefs = 0;
  t->body = NULL;
  return t;
}

void topic_destroy(struct topic *t) {
  int i;
  for (i=0; i<t->numtitles; i++) {
    free(t->titles[i]);
  }
  for (i=0; i<t->numrefs; i++) {
    free(t->refs[i]);
  }
  if (t->body) {
    free(t->body);
  }
  free(t);
}

void topic_addtitle(struct topic *t, const char *s) {
  if (t->numtitles >= MAXTITLES) {
    fprintf(stderr, "Too many titles (increase MAXTITLES) at %s\n", s);
    exit(1);
  }
  t->titles[t->numtitles++] = dostrdup(s);
}

void topic_addref(struct topic *t, const char *s) {
  if (t->numrefs >= MAXREFS) {
    fprintf(stderr, "Too many refs (increase MAXREFS) at %s\n", s);
    exit(1);
  }
  t->refs[t->numrefs++] = dostrdup(s);
}

void topic_setbody(struct topic *t, const char *buf, size_t len) {
  size_t i, j, reallen = 0;

  for (i=0; i<len; i++) {
    if (buf[i] != '\r') {
      reallen++;
    }
  }
  
  char *text = domalloc(reallen+1);
  for (i=j=0; i<len; i++) {
    if (buf[i] != '\r') {
      text[j++] = buf[i];
    }
  }
  assert(j==reallen);
  text[reallen] = 0;

  t->body = text;
}

const char *topic_getbody(struct topic *t) { return t->body; }
int topic_getnumtitles(struct topic *t) { return t->numtitles; }
const char *topic_gettitle(struct topic *t, int ix) { return t->titles[ix]; }
int topic_getnumrefs(struct topic *t) { return t->numrefs; }
const char *topic_getref(struct topic *t, int ix) { return t->refs[ix]; }