ARB
sized_cstr.h
Go to the documentation of this file.
1 // =========================================================== //
2 // //
3 // File : sized_cstr.h //
4 // Purpose : helper class to reduce calls to strlen() //
5 // //
6 // Coded by Ralf Westram (coder@reallysoft.de) in May 2018 //
7 // http://www.arb-home.de/ //
8 // //
9 // =========================================================== //
10 
11 #ifndef SIZED_CSTR_H
12 #define SIZED_CSTR_H
13 
14 #ifndef ARB_ASSERT_H
15 #include "arb_assert.h"
16 #endif
17 #ifndef _GLIBCXX_LIMITS
18 #include <limits>
19 #endif
20 #ifndef _GLIBCXX_CSTDLIB
21 #include <cstdlib>
22 #endif
23 
24 #define UNKNOWN_LENGTH std::numeric_limits<size_t>::max()
25 
26 class SizedCstr {
27  const char *cstr;
28  mutable size_t len;
29 
30 public:
31  SizedCstr() : cstr(NULp), len(UNKNOWN_LENGTH) {}
32  explicit SizedCstr(const char *str) : cstr(str), len(UNKNOWN_LENGTH) {}
33  SizedCstr(const char *str, size_t length) : cstr(str), len(length) {
34  arb_assert(strlen(str) >= length); // allow to truncate buffer by specifying a smaller length
35  }
36 
37  bool isNull() const { return cstr == NULp; }
38  bool isSet() const { return !isNull(); }
39 
40  operator const char*() const { arb_assert(isSet()); return cstr; }
41 
42  size_t get_length() const {
43  arb_assert(isSet());
44  if (len == UNKNOWN_LENGTH) len = strlen(cstr);
45  return len;
46  }
47 };
48 
49 #undef UNKNOWN_LENGTH
50 
51 #else
52 #error sized_cstr.h included twice
53 #endif // SIZED_CSTR_H
#define arb_assert(cond)
Definition: arb_assert.h:245
#define UNKNOWN_LENGTH
Definition: sized_cstr.h:24
size_t get_length() const
Definition: sized_cstr.h:42
bool isSet() const
Definition: sized_cstr.h:38
SizedCstr(const char *str, size_t length)
Definition: sized_cstr.h:33
SizedCstr(const char *str)
Definition: sized_cstr.h:32
#define NULp
Definition: cxxforward.h:116
size_t length
bool isNull() const
Definition: sized_cstr.h:37