1// Copyright 2024 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package gobtools 16 17import ( 18 "bytes" 19 "encoding/gob" 20) 21 22type CustomGob[T any] interface { 23 ToGob() *T 24 FromGob(data *T) 25} 26 27func CustomGobEncode[T any](cg CustomGob[T]) ([]byte, error) { 28 w := new(bytes.Buffer) 29 encoder := gob.NewEncoder(w) 30 err := encoder.Encode(cg.ToGob()) 31 if err != nil { 32 return nil, err 33 } 34 35 return w.Bytes(), nil 36} 37 38func CustomGobDecode[T any](data []byte, cg CustomGob[T]) error { 39 r := bytes.NewBuffer(data) 40 var value T 41 decoder := gob.NewDecoder(r) 42 err := decoder.Decode(&value) 43 if err != nil { 44 return err 45 } 46 cg.FromGob(&value) 47 48 return nil 49} 50