File: memfile.c

package info (click to toggle)
growl-for-linux 0.8.5-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,464 kB
  • sloc: sh: 4,121; ansic: 3,748; makefile: 74
file content (52 lines) | stat: -rw-r--r-- 1,053 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#include "compatibility.h"
#include "memfile.h"

MEMFILE*
memfopen() {
  return (MEMFILE*) calloc(1, sizeof(MEMFILE));
}

void
memfclose(MEMFILE* mf) {
  free(memfdata(mf));
  free(mf);
}

char*
memfresize(MEMFILE* mf, const size_t newsize) {
  if (!mf) return NULL;

  // Grow
  if (mf->size < newsize) {
    char* const tmp = (char*) realloc(mf->data, newsize);
    if (!tmp) return NULL;
    mf->data = tmp;
  }
  char* const insert_point = mf->data + mf->size;
  mf->size = newsize;
  return insert_point;
}

size_t
memfwrite(const char* ptr, size_t size, size_t nmemb, void* stream) {
  MEMFILE* const mf = (MEMFILE*) stream;
  const size_t block = size * nmemb;
  if (!mf) return block; // through

  const size_t orig_size = memfsize(mf);
  if (!memfresize(mf, orig_size + block)) return block;

  memcpy(memfdata(mf) + orig_size, ptr, block);
  return block;
}

char*
memfstrdup(const MEMFILE* mf) {
  if (!memfsize(mf)) return NULL;
  return strndup(memfcdata(mf), memfsize(mf));
}