kmx.io/kv/kv_unquote.c

Branch

Thomas de Grivel 78c072be1 2022-01-03T17:17:35
wip unquote
/*
 * kv - key value text file format
 *
 * Copyright 2022 Thomas de Grivel
*/

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "kv.h"

int kv_unquote (s_buffer *b)
{
  
}

int kv_quote_delim (char **str, size_t *str_size, const char *delim)
{
  char  *s;
  size_t delim_len;
  size_t len;
  assert(str);
  assert(str_size);
  assert(delim);
  if (kv_check_delimiter(delim)) {
    fprintf(stderr, "bad delimiter: %s\n", delim);
    return 1;
  }
  if (kv_contains_delimiter(*str, *str_size, delim))
    return 1;
  delim_len = strlen(delim);
  len = *str_size + delim_len * 2 + 3;
  s = calloc(len + 1, 1);
  if (!s)
    return -1;
  s[0] = '<'; s[1] = '<';
  memcpy(s + 2, delim, delim_len);
  s[2 + delim_len] = '\n';
  memcpy(s + delim_len + 3, *str, *str_size);
  memcpy(s + *str_size + delim_len + 3, delim, delim_len);
  *str = s;
  *str_size = len;
  return 0;
}

int kv_quote_double_quotes (char **str, size_t *str_size)
{
  size_t i = 0;
  size_t o = 0;
  size_t res;
  char  *s;
  assert(str);
  assert(str_size);
  res = kv_count_quotable_chars(*str, *str_size);
  s = calloc(*str_size + res + 3, 1);
  if (!s)
    return -1;
  s[o++] = '"';
  while (i < *str_size) {
    int c = (*str)[i++];
    if (kv_is_quotable_char(c))
      s[o++] = '\\';
    switch (c) {
    case 0:    s[o++] = '0'; break;
    case '\n': s[o++] = 'n'; break;
    case '\r': s[o++] = 'r'; break;
    case '\t': s[o++] = 't'; break;
    case '\v': s[o++] = 'v'; break;
    default: s[o++] = c;
    }
  }
  s[o++] = '"';
  assert(o == *str_size + res + 2);
  s[o] = 0;
  *str = s;
  *str_size = o;
  return 0;
}

int kv_quote_triple_double_quotes (char **str, size_t *str_size)
{
  char *e;
  char *s;
  if (kv_contains_triple_double_quotes(*str, *str_size))
    return 1;
  s = calloc(*str_size + 8, 1);
  if (!s)
    return -1;
  s[0] = '"'; s[1] = '"'; s[2] = '"'; s[3] = '\n';
  memcpy(s + 4, *str, *str_size);
  e = s + 4 + *str_size;
  e[0] = '"'; e[1] = '"'; e[2] = '"'; e[3] = 0;
  *str = s;
  *str_size = *str_size + 7;
  return 0;
}
Download