protoutil.go 721 B

123456789101112131415161718192021222324252627282930
  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. "fmt"
  9. "google.golang.org/protobuf/proto"
  10. )
  11. func MarshalTo(buf []byte, pb proto.Message) (int, error) {
  12. if sz := proto.Size(pb); len(buf) < sz {
  13. return 0, fmt.Errorf("buffer too small")
  14. } else if sz == 0 {
  15. return 0, nil
  16. }
  17. opts := proto.MarshalOptions{}
  18. bs, err := opts.MarshalAppend(buf[:0], pb)
  19. if err != nil {
  20. return 0, err
  21. }
  22. if &buf[0] != &bs[0] {
  23. panic("can't happen: slice was reallocated")
  24. }
  25. return len(bs), nil
  26. }