msgpack-arduino icon indicating copy to clipboard operation
msgpack-arduino copied to clipboard

String length and allocation

Open Sod-Almighty opened this issue 7 years ago • 5 comments

When calling the readString functions, I have to magically know how big the string buffer needs to be. There appears to be no way to check this ahead of time.

I propose a variant of readString, thusly:

char* readNewString(Stream& stream, bool safely = true) {
 DataType dataFormat;
 getNextDataType(stream, dataFormat, safely);
 size_t outputSize;
 char* value = nullptr;
 switch(dataFormat) {
  case DataType::String5: {
   MSGPACK_SAFETY_FORMAT_CHECK(DataType::String8);
   stream.read();
   MSGPACK_SAFELY_RUN(readRaw(stream, outputSize, safely));
   value = new char[outputSize + 1];
   MSGPACK_SAFELY_RUN(readRaw(stream, value, outputSize, safely));
   value[outputSize] = '\0';
   return value;
  }
  /* ... */
 }
}

Sod-Almighty avatar Dec 01 '18 22:12 Sod-Almighty

Yes it's a good idea! Could you possibly make a pull request?

Naming-wise, it might be nice to be readStringNew since it is a variant of readString... (so that it shows up in auto-complete along-side the others).

elliotwoods avatar Dec 04 '18 04:12 elliotwoods

Issued pull request #7

Incidentally, is there a simple way to add a function that skips whatever the next value is?

Sod-Almighty avatar Dec 06 '18 19:12 Sod-Almighty

we don't have a generic skip value function. So if the next value was a map of maps, then we'd want to skip the map of maps - so the skip code would need to recursively skip all sub-elements, correct?

elliotwoods avatar Dec 10 '18 02:12 elliotwoods

Correct. Would you like me to have a go?

Sod-Almighty avatar Dec 10 '18 15:12 Sod-Almighty

sure! why not. that'd be great

elliotwoods avatar Dec 11 '18 06:12 elliotwoods