aboutsummaryrefslogtreecommitdiff
path: root/strbuf.h
blob: 9bf603a9cc1b7d2831ad2191e159aeaeebf07d30 (plain)
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
92
93
94
95
96
#ifndef STRBUF_H
#define STRBUF_H

#include <unistd.h>
#include <cstdlib>
// #include <cstring>
#include <string>

#include <iostream>

/*
 * A high level string type which holds it's own length, how much
 * memmory it has allocated for itself, and a seek pointer into the
 * string.
 *
 * Also comes with a number of functions which allow for safe(er)
 * access to the memmory.
 */
struct strbuf {
	/* TODO add support for negative ptr */
	int ptr      = 0;
	size_t alloc = 0;
	size_t len   = 0;

	char* mem;

	strbuf () : strbuf (1) { };

	strbuf (const strbuf& other);

	strbuf (size_t alloc)
		: alloc(alloc)
		, mem(static_cast<char*>(malloc(alloc))) { };

	~strbuf();

	/*
	 * Like realloc, but for strbuf
	 */
	void realloc (size_t len);

	bool operator==(strbuf& other);

	bool operator==(const char* other);

	strbuf& operator=(strbuf* other);

	strbuf& operator+=(char c);

	void cap() { this->mem += '\0'; }

	/*
	 * Returns a pointer to character at index. Allows mutation of the
	 * value pointed to by the return address.
	 */
	char& operator[](int idx) 
		{ return this->mem[idx]; }

	/* Same as `charat`, But returns the current character.  */
	char& strbuf_cur()
		{ return this->mem[this->ptr]; }

	/* Returns the character after the last, so where null hopefully is.  */
	char& back()
		{ return this->mem[this->len]; }

	/* Resets the seek for strbuf to 0.  */
	void reset()
		{ this->ptr = 0; }

	/* Sets the length and seek ptr to 0, but doesn't touch the memmory.  */
	void soft_reset() {
		this->ptr = 0; this->len = 0;
	};


	char* c_str();

	std::string to_string() {
		return std::string (this->c_str());
	}
};

std::ostream& operator << (std::ostream& out, strbuf& str);

/*
 * Reallocs dest to be the same size as src, and copies the contents
 * of src into dest.
 */
// int strbuf_realloc_copy(strbuf* dest, strbuf* src);

/*
 * Copies contents from src to dest, also allocating dest in the
 * process. dest should not be initialized before self call.
 */
#endif /* STRBUF_H */