File: memfile.cpp

package info (click to toggle)
tippecanoe 2.53.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 148,236 kB
  • sloc: cpp: 44,069; ansic: 2,057; makefile: 454; perl: 129; python: 62; sh: 4
file content (91 lines) | stat: -rw-r--r-- 1,966 bytes parent folder | download | duplicates (2)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#include "memfile.hpp"

#define INCREMENT 131072
#define INITIAL 256

struct memfile *memfile_open(int fd) {
	if (ftruncate(fd, INITIAL) != 0) {
		return NULL;
	}

	struct memfile *mf = new memfile;
	if (mf == NULL) {
		return NULL;
	}

	mf->fd = fd;
	mf->tree = 0;
	mf->off = 0;

	return mf;
}

int memfile_close(struct memfile *file) {
	// If it isn't full yet, flush out the string to the file now.
	// If it is full, close out the buffered file writer.

	if (file->fp == NULL) {
		if (write(file->fd, file->map.c_str(), file->map.size()) != (ssize_t) file->map.size()) {
			return -1;
		}

		if (file->fd >= 0) {
			if (close(file->fd) != 0) {
				return -1;
			}
		}
	} else {
		if (fclose(file->fp) != 0) {
			return -1;
		}
	}

	delete file;
	return 0;
}

int memfile_write(struct memfile *file, void *s, long long len, bool &in_memory) {
	// If it is full, append to the file.
	// If it is not full yet, append to the string in memory.

	in_memory = false;
	if (file->fp != NULL) {
		if (fwrite(s, sizeof(char), len, file->fp) != (size_t) len) {
			return 0;
		}
		file->off += len;
	} else {
		file->map.append(std::string((char *) s, len));
		file->off += len;
		in_memory = true;
	}

	return len;
}

void memfile_full(struct memfile *file) {
	// The file is full. Write out a copy of whatever has accumulated in memory
	// to the file, and switch to appending to the file. Existing references
	// into the memory still work.

	if (file->fp != NULL) {
		fprintf(stderr, "memfile marked full twice\n");
		exit(EXIT_IMPOSSIBLE);
	}

	file->fp = fdopen(file->fd, "wb");
	if (file->fp == NULL) {
		fprintf(stderr, "fdopen memfile: %s\n", strerror(errno));
		exit(EXIT_OPEN);
	}

	if (fwrite(file->map.c_str(), sizeof(char), file->map.size(), file->fp) != file->map.size()) {
		fprintf(stderr, "memfile write: %s\n", strerror(errno));
		exit(EXIT_WRITE);
	}
}