RetroArch
serialization.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <stdint.h>
4 
5 #ifndef __MINGW32__
6 #pragma warning(push)
7 
8 #pragma warning(disable : 4061) // enum is not explicitly handled by a case label
9 #pragma warning(disable : 4365) // signed/unsigned mismatch
10 #pragma warning(disable : 4464) // relative include path contains
11 #pragma warning(disable : 4668) // is not defined as a preprocessor macro
12 #pragma warning(disable : 6313) // Incorrect operator
13 #endif // __MINGW32__
14 
15 #include "rapidjson/document.h"
16 #include "rapidjson/stringbuffer.h"
17 #include "rapidjson/writer.h"
18 
19 #ifndef __MINGW32__
20 #pragma warning(pop)
21 #endif // __MINGW32__
22 
23 // if only there was a standard library function for this
24 template <size_t Len>
25 inline size_t StringCopy(char (&dest)[Len], const char* src)
26 {
27  if (!src || !Len) {
28  return 0;
29  }
30  size_t copied;
31  char* out = dest;
32  for (copied = 1; *src && copied < Len; ++copied) {
33  *out++ = *src++;
34  }
35  *out = 0;
36  return copied - 1;
37 }
38 
39 size_t JsonWriteHandshakeObj(char* dest, size_t maxLen, int version, const char* applicationId);
40 
41 // Commands
42 struct DiscordRichPresence;
43 size_t JsonWriteRichPresenceObj(char* dest,
44  size_t maxLen,
45  int nonce,
46  int pid,
47  const DiscordRichPresence* presence);
48 size_t JsonWriteSubscribeCommand(char* dest, size_t maxLen, int nonce, const char* evtName);
49 
50 size_t JsonWriteUnsubscribeCommand(char* dest, size_t maxLen, int nonce, const char* evtName);
51 
52 size_t JsonWriteJoinReply(char* dest, size_t maxLen, const char* userId, int reply, int nonce);
53 
54 // I want to use as few allocations as I can get away with, and to do that with RapidJson, you need
55 // to supply some of your own allocators for stuff rather than use the defaults
56 
58 public:
59  char* buffer_;
60  char* end_;
62  {
63  assert(0); // needed for some default case in rapidjson, should not use
64  }
65  LinearAllocator(char* buffer, size_t size)
66  : buffer_(buffer)
67  , end_(buffer + size)
68  {
69  }
70  static const bool kNeedFree = false;
71  void* Malloc(size_t size)
72  {
73  char* res = buffer_;
74  buffer_ += size;
75  if (buffer_ > end_) {
76  buffer_ = res;
77  return nullptr;
78  }
79  return res;
80  }
81  void* Realloc(void* originalPtr, size_t originalSize, size_t newSize)
82  {
83  if (newSize == 0) {
84  return nullptr;
85  }
86  // allocate how much you need in the first place
87  assert(!originalPtr && !originalSize);
88  // unused parameter warning
89  (void)(originalPtr);
90  (void)(originalSize);
91  return Malloc(newSize);
92  }
93  static void Free(void* ptr)
94  {
95  /* shrug */
96  (void)ptr;
97  }
98 };
99 
100 template <size_t Size>
102 public:
106  {
107  }
108  static const bool kNeedFree = false;
109 };
110 
111 // wonder why this isn't a thing already, maybe I missed it
113 public:
114  using Ch = char;
115  char* buffer_;
116  char* end_;
117  char* current_;
118 
119  DirectStringBuffer(char* buffer, size_t maxLen)
120  : buffer_(buffer)
121  , end_(buffer + maxLen)
122  , current_(buffer)
123  {
124  }
125 
126  void Put(char c)
127  {
128  if (current_ < end_) {
129  *current_++ = c;
130  }
131  }
132  void Flush() {}
133  size_t GetSize() const { return (size_t)(current_ - buffer_); }
134 };
135 
136 using MallocAllocator = rapidjson::CrtAllocator;
137 using PoolAllocator = rapidjson::MemoryPoolAllocator<MallocAllocator>;
138 using UTF8 = rapidjson::UTF8<char>;
139 // Writer appears to need about 16 bytes per nested object level (with 64bit size_t)
141 constexpr size_t WriterNestingLevels = 2048 / (2 * sizeof(size_t));
142 using JsonWriterBase =
143  rapidjson::Writer<DirectStringBuffer, UTF8, UTF8, StackAllocator, rapidjson::kWriteNoFlags>;
144 class JsonWriter : public JsonWriterBase {
145 public:
148 
149  JsonWriter(char* dest, size_t maxLen)
151  , stringBuffer_(dest, maxLen)
152  , stackAlloc_()
153  {
154  }
155 
156  size_t Size() const { return stringBuffer_.GetSize(); }
157 };
158 
159 using JsonDocumentBase = rapidjson::GenericDocument<UTF8, PoolAllocator, StackAllocator>;
161 public:
162  static const int kDefaultChunkCapacity = 32 * 1024;
163  // json parser will use this buffer first, then allocate more if needed; I seriously doubt we
164  // send any messages that would use all of this, though.
165  char parseBuffer_[32 * 1024];
172  sizeof(stackAllocator_.fixedBuffer_),
175  , stackAllocator_()
176  {
177  }
178 };
179 
180 using JsonValue = rapidjson::GenericValue<UTF8, PoolAllocator>;
181 
182 inline JsonValue* GetObjMember(JsonValue* obj, const char* name)
183 {
184  if (obj) {
185  auto member = obj->FindMember(name);
186  if (member != obj->MemberEnd() && member->value.IsObject()) {
187  return &member->value;
188  }
189  }
190  return nullptr;
191 }
192 
193 inline int GetIntMember(JsonValue* obj, const char* name, int notFoundDefault = 0)
194 {
195  if (obj) {
196  auto member = obj->FindMember(name);
197  if (member != obj->MemberEnd() && member->value.IsInt()) {
198  return member->value.GetInt();
199  }
200  }
201  return notFoundDefault;
202 }
203 
204 inline const char* GetStrMember(JsonValue* obj,
205  const char* name,
206  const char* notFoundDefault = nullptr)
207 {
208  if (obj) {
209  auto member = obj->FindMember(name);
210  if (member != obj->MemberEnd() && member->value.IsString()) {
211  return member->value.GetString();
212  }
213  }
214  return notFoundDefault;
215 }
static const int kDefaultChunkCapacity
Definition: serialization.h:162
GLuint const GLchar * name
Definition: glext.h:6671
Definition: serialization.h:112
rapidjson::GenericDocument< UTF8, PoolAllocator, StackAllocator > JsonDocumentBase
Definition: serialization.h:159
const GLvoid * ptr
Definition: nx_glsym.h:242
Unknown compiler Device disconnected from port File already exists Saving to backup buffer Got connection Port Mapping Successful No arguments supplied and no menu displaying help Waiting for client You have joined as player u Player *s has left the game *s has joined with input devices *s The netplay peer is running an old version of RetroArch Cannot connect A netplay peer is running a different core Cannot connect This core does not support inter architecture netplay between these systems Enter netplay server Incorrect password A netplay client has disconnected You do not have permission to play The input devices requested are not available Netplay peer s paused Give hardware rendered cores their own private context Avoids having to assume hardware state changes inbetween frames Adjusts menu screen appearance settings Improves performance at the cost of latency and more video stuttering Use only if you cannot obtain full speed otherwise Autodetect Capabilities Connecting to port Password Username Accounts List Endpoint Achievements Resume Achievements Hardcore Mode Scan Content Import content Ask Block Frames Audio Driver Audio Enable Turbo Deadzone Audio Maximum Timing Skew Audio Output Dynamic Audio Rate Control Audio Audio Volume WASAPI Exclusive Mode WASAPI Shared Buffer Length Load Override Files Automatically Load Shader Presets Automatically Confirm Quit Scroll Up Toggle Keyboard Basic menu controls Info Scroll Up Toggle Keyboard Don t overwrite SaveRAM on loading savestate Buildbot Assets URL Allow Camera Cheat Start Search For New Cheat Code Cheat File Load Cheat Load Cheat Save Cheat File As Description Leaderboards Locked Locked Test Unofficial Achievements Unlocked Verbose Mode Close Content Load Configuration Save Configuration on Exit Database History List Size Quick Menu Downloads Core Counters Core Information Categories Core name Permissions System manufacturer Controls Install or Restore a Core Core installation succesful Core Automatically extract downloaded archive Core Updater CPU CPU Cursor Custom Ratio Database Selection Start directory< Default > Directory not found Disk Cycle Tray Status Disk Index Don t care Download a Core DPI Override Enable Driver Check for Missing Firmware Before Loading Dynamic Backgrounds Menu entry hover color False Favorites Include Memory Details Sync to Exact Content Frame Throttle Load Content Specific Core Options Automatically Save Game options file Audio Video Troubleshooting Basic Menu Controls Loading Content What Is A Core History Image Information All Users Control Menu Left analog Left analog Left Analog Y Left analog Right Analog X Right analog Right Analog Y Right analog Gun Trigger Gun Aux A Gun Aux C Gun Select Gun D pad Down Gun D pad Right Analog Stick Deadzone Bind All Bind Timeout Hide Unbound Core Input Descriptors Device Index Mouse Index Duty Cycle Keyboard Gamepad Mapping Enable B Down D pad L3 L Left D pad R3 R Right D pad Start button X Y Mouse Mouse Mouse Wheel Down Wheel Right Max Users Cheat index Cheat toggle Disk next Enable hotkeys Fast forward toggle FPS toggle Grab mouse toggle Desktop menu toggle Menu toggle Audio mute toggle On screen keyboard toggle Pause toggle Reset game Cheat Details Save state Next shader Slow motion hold Savestate slot Volume Display Overlay Show Inputs On Overlay Poll Type Behavior Late Prefer Front Touch Remap Binds Enable Input Touch Enable Turbo Period Latency Input Autoconfig Services Dutch Esperanto German Japanese Polish Russian Vietnamese Greek Core Core Logging Level Load Archive Load Content Allow Location Logging Main Menu Menu Color Theme Blue Grey Green Red Footer Opacity Menu Driver Settings Horizontal Animation Background Missing Mouse Support Music Navigation Wrap Around Netplay Netplay Check Frames Input Latency Frames Range Disconnect from netplay host Connect to netplay host Stop netplay host Scan local network Username Publicly Announce Netplay Disallow Non Slave Mode Clients Analog Input Sharing Average Share Vote No preference Netplay Stateless Mode Netplay Spectator Enable Netplay NAT Traversal Network Command Port Network Gamepad Network None No achievements to display No cores available No core options available No history available No items No networks found No playlists No settings found OFF Online Onscreen Display Adjust Bezels and Onscreen controls Adjust the Onscreen Notifications Optional Autoload Preferred Overlay Overlay Opacity Overlay Scale Use PAL60 Mode Pause when menu activated Performance Counters Playlist Touch Support Present MIDI Analog supported CERO Rating CRC32 Developer Edge Magazine Rating ELSPA Rating ESRB Rating Franchise MD5 Origin Publisher Releasedate Year Serial Start Content Reboot Recording Output Custom Record Config Record Driver Enable Recording Save Recordings in Output Dir Load Remap File Save Content Directory Remap File Delete Core Remap File Delete Game Content Directory Remap File Restart Resume RetroKeyboard RetroPad w Analog Rewind Enable Auto Apply Cheats During Game Load Rewind Buffer Size(MB)" ) MSG_HASH( MENU_ENUM_LABEL_VALUE_REWIND_BUFFER_SIZE_STEP
static void Free(void *ptr)
Definition: serialization.h:93
DirectStringBuffer(char *buffer, size_t maxLen)
Definition: serialization.h:119
void Flush()
Definition: serialization.h:132
GLuint res
Definition: glext.h:10520
object
Definition: rapidjson.h:607
GLsizeiptr size
Definition: glext.h:6559
JsonWriter(char *dest, size_t maxLen)
Definition: serialization.h:149
main RapidJSON namespace
struct passwd out
Definition: missing_libc_functions.c:51
typedef void(__stdcall *PFN_DESTRUCTION_CALLBACK)(void *pData)
size_t Size() const
Definition: serialization.h:156
char * end_
Definition: serialization.h:60
static const bool kNeedFree
Definition: serialization.h:70
void * Malloc(size_t size)
Definition: serialization.h:71
const GLubyte * c
Definition: glext.h:9812
char * buffer_
Definition: serialization.h:115
DirectStringBuffer stringBuffer_
Definition: serialization.h:146
char * buffer_
Definition: serialization.h:59
size_t GetSize() const
Definition: serialization.h:133
void Put(char c)
Definition: serialization.h:126
LinearAllocator(char *buffer, size_t size)
Definition: serialization.h:65
size_t StringCopy(char(&dest)[Len], const char *src)
Definition: serialization.h:25
version
Definition: setup.py:6
size_t JsonWriteJoinReply(char *dest, size_t maxLen, const char *userId, int reply, int nonce)
Definition: serialization.cpp:218
void * Realloc(void *originalPtr, size_t originalSize, size_t newSize)
Definition: serialization.h:81
MallocAllocator mallocAllocator_
Definition: serialization.h:166
LinearAllocator()
Definition: serialization.h:61
char * end_
Definition: serialization.h:116
GLenum src
Definition: glext.h:6980
char parseBuffer_[32 *1024]
Definition: serialization.h:165
static const bool kNeedFree
Definition: serialization.h:108
const char * GetStrMember(JsonValue *obj, const char *name, const char *notFoundDefault=nullptr)
Definition: serialization.h:204
size_t JsonWriteUnsubscribeCommand(char *dest, size_t maxLen, int nonce, const char *evtName)
Definition: serialization.cpp:199
Definition: serialization.h:160
rapidjson::Writer< DirectStringBuffer, UTF8, UTF8, StackAllocator, rapidjson::kWriteNoFlags > JsonWriterBase
Definition: serialization.h:143
size_t JsonWriteHandshakeObj(char *dest, size_t maxLen, int version, const char *applicationId)
Definition: serialization.cpp:165
size_t JsonWriteSubscribeCommand(char *dest, size_t maxLen, int nonce, const char *evtName)
Definition: serialization.cpp:180
FixedLinearAllocator()
Definition: serialization.h:104
Definition: discord_rpc.h:26
JsonValue * GetObjMember(JsonValue *obj, const char *name)
Definition: serialization.h:182
#define Len
Definition: deflate.h:79
char Ch
Definition: serialization.h:114
size_t JsonWriteRichPresenceObj(char *dest, size_t maxLen, int nonce, int pid, const DiscordRichPresence *presence)
Definition: serialization.cpp:83
int GetIntMember(JsonValue *obj, const char *name, int notFoundDefault=0)
Definition: serialization.h:193
StackAllocator stackAllocator_
Definition: serialization.h:168
Definition: serialization.h:101
constexpr size_t WriterNestingLevels
Definition: serialization.h:141
char fixedBuffer_[Size]
Definition: serialization.h:103
StackAllocator stackAlloc_
Definition: serialization.h:147
rapidjson::CrtAllocator MallocAllocator
Definition: serialization.h:136
UTF-8 encoding.
Definition: encodings.h:96
Definition: video4linux2.c:51
rapidjson::MemoryPoolAllocator< MallocAllocator > PoolAllocator
Definition: serialization.h:137
rapidjson::GenericValue< UTF8, PoolAllocator > JsonValue
Definition: serialization.h:180
Definition: serialization.h:144
PoolAllocator poolAllocator_
Definition: serialization.h:167
Definition: serialization.h:57
char * current_
Definition: serialization.h:117
JsonDocument()
Definition: serialization.h:169
GLsizei GLsizei GLuint * obj
Definition: glext.h:6682