-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstr.h
89 lines (71 loc) · 1.53 KB
/
str.h
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
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "intrinsics.h"
#include "strlcpy.h"
#include "ggformat.h"
template< size_t N >
class str {
public:
STATIC_ASSERT( N > 0 );
str() {
clear();
}
template< typename... Rest >
str( const char * fmt, const Rest & ... rest ) {
sprintf( fmt, rest... );
}
void clear() {
buf[ 0 ] = '\0';
length = 0;
}
template< typename T >
void operator+=( const T & x ) {
appendf( "{}", x );
}
template< typename... Rest >
void sprintf( const char * fmt, const Rest & ... rest ) {
size_t copied = ggformat( buf, N, fmt, rest... );
length = min( copied, N - 1 );
}
template< typename... Rest >
void appendf( const char * fmt, const Rest & ... rest ) {
size_t copied = ggformat( buf + length, N - length, fmt, rest... );
length += min( copied, N - length - 1 );
}
void truncate( size_t n ) {
if( n >= length ) {
return;
}
buf[ n ] = '\0';
length = n;
}
char & operator[]( size_t i ) {
ASSERT( i < N );
return buf[ i ];
}
const char & operator[]( size_t i ) const {
ASSERT( i < N );
return buf[ i ];
}
const char * c_str() const {
return buf;
}
size_t len() const {
return length;
}
bool operator==( const char * rhs ) const {
return strcmp( buf, rhs ) == 0;
}
bool operator!=( const char * rhs ) const {
return !( *this == rhs );
}
private:
char buf[ N ];
size_t length;
};
template< size_t N >
void format( FormatBuffer * fb, const str< N > & buf, const FormatOpts & opts ) {
format( fb, buf.c_str(), opts );
}