Skip to content

Commit dd97ede

Browse files
committed
Quoted strings to String() or Key() are auto-sized by template
No strlen call needs to be made when templates can auto-deduce the string length. No strlen = faster! Unfortunately this needs a touch of SFINAE to allow multiple overrides to coexist cleanly.
1 parent 7116c35 commit dd97ede

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

include/rapidjson/writer.h

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#define RAPIDJSON_WRITER_H_
1717

1818
#include "stream.h"
19+
#include "internal/meta.h"
1920
#include "internal/stack.h"
2021
#include "internal/strfunc.h"
2122
#include "internal/dtoa.h"
@@ -198,7 +199,8 @@ class Writer {
198199
return EndValue(WriteString(str, length));
199200
}
200201

201-
bool String(const Ch* str, SizeType length, bool copy = false) {
202+
template <typename T>
203+
bool String(const T* str, SizeType length, bool copy = false, RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) {
202204
RAPIDJSON_ASSERT(str != 0);
203205
(void)copy;
204206
Prefix(kStringType);
@@ -217,7 +219,8 @@ class Writer {
217219
return WriteStartObject();
218220
}
219221

220-
bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
222+
template <typename T>
223+
bool Key(const T* str, SizeType length, bool copy = false, RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return String(str, length, copy); }
221224

222225
bool EndObject(SizeType memberCount = 0) {
223226
(void)memberCount;
@@ -247,8 +250,16 @@ class Writer {
247250
//@{
248251

249252
//! Simpler but slower overload.
250-
bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
251-
bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
253+
template <typename T>
254+
bool String(const T* const& str, RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return String(str, internal::StrLen(str)); }
255+
template <typename T>
256+
bool Key(const T* const& str, RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return Key(str, internal::StrLen(str)); }
257+
258+
//! The compiler can give us the length of quoted strings for free.
259+
template <typename T, size_t N>
260+
bool String(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return String(str, N-1); }
261+
template <typename T, size_t N>
262+
bool Key(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return Key(str, N-1); }
252263

253264
//@}
254265

0 commit comments

Comments
 (0)