-#ifdef __BIG_ENDIAN__
- memcpy((char*)dest + (destsize - srcsize), src, srcsize);
-#else
- memcpy(dest, src, srcsize);
-#endif
+ /* First calculate the message size using a non-writing substream. */
+ pb_ostream_t substream = {0,0,0,0};
+ size_t size;
+ bool status;
+
+ if (!pb_encode(&substream, fields, src_struct))
+ return false;
+
+ size = substream.bytes_written;
+
+ if (!pb_encode_varint(stream, (uint64_t)size))
+ return false;
+
+ if (stream->callback == NULL)
+ return pb_write(stream, NULL, size); /* Just sizing */
+
+ if (stream->bytes_written + size > stream->max_size)
+ return false;
+
+ /* Use a substream to verify that a callback doesn't write more than
+ * what it did the first time. */
+ substream.callback = stream->callback;
+ substream.state = stream->state;
+ substream.max_size = size;
+ substream.bytes_written = 0;
+
+ status = pb_encode(&substream, fields, src_struct);
+
+ stream->bytes_written += substream.bytes_written;
+ stream->state = substream.state;
+
+ if (substream.bytes_written != size)
+ return false;
+
+ return status;