protoutil.go 767 B

1234567891011121314151617181920212223242526272829303132
  1. // Copyright (C) 2025 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package protoutil
  7. import (
  8. "errors"
  9. "google.golang.org/protobuf/proto"
  10. )
  11. var errBufferTooSmall = errors.New("buffer too small")
  12. func MarshalTo(buf []byte, pb proto.Message) (int, error) {
  13. if sz := proto.Size(pb); len(buf) < sz {
  14. return 0, errBufferTooSmall
  15. } else if sz == 0 {
  16. return 0, nil
  17. }
  18. opts := proto.MarshalOptions{}
  19. bs, err := opts.MarshalAppend(buf[:0], pb)
  20. if err != nil {
  21. return 0, err
  22. }
  23. if &buf[0] != &bs[0] {
  24. panic("can't happen: slice was reallocated")
  25. }
  26. return len(bs), nil
  27. }