On Friday 07 August 2015 07:08:34 Lankswert, Patrick wrote: > Hyuna, > If you know your representation and the types, you should be able to > calculate the worse-case encoding size in most cases. Collections, on the > other hand, are more difficult and will require calculation of worse case > size at run time. FYI, the problem of not knowing the size before encoding > would be worse with JSON, right?
Not exactly. The cJSON API is allocating memory as it goes, so it does not run out of buffer to encode your data. So you're trading off one big allocation for a lot of smaller ones, followed by one or more big allocations at the end to create the encoded JSON. The Tinycbor library was designed to do exactly zero allocations. It does not call malloc anywhere. The trade-off is when you don't know the buffer size and must guess. > I am not as big a fan of Thiago?s > suggestion of try and reallocate on fail. In bad cases, it will have a > performance impact. In worse case, a flaw in the encoder could case cycles > that result in memory exhaustion. In most cases, it would be better to > calculate, try and if encoding fails, fail the operation. The compromise is > the Windows API practice of running the encoding twice, the first time > without a buffer to calculate the size. If the size is acceptable, allocate > the memory and encode for real. Pat Tinycbor doesn't have an API to return the required size, but it wouldn't be difficult to add. It would probably mean changing the return value from all the cbor_encode_* functions: return zero on ok and a non-zero value of the number of more bytes required to encode the piece of data. So you could run it once with an empty buffer, calculate the size; then allocate and run again. -- Thiago Macieira - thiago.macieira (AT) intel.com Software Architect - Intel Open Source Technology Center
