github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/common/copy.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package common 20 21 import ( 22 "bytes" 23 "encoding/gob" 24 "encoding/json" 25 26 "github.com/francoispqt/gojay" 27 "github.com/jinzhu/copier" 28 ) 29 30 // CopyEngine ... 31 type CopyEngine string 32 33 const ( 34 // JsonEngine ... 35 JsonEngine = CopyEngine("json") 36 // GobEngine ... 37 GobEngine = CopyEngine("gob") 38 // GojayEngine ... 39 GojayEngine = CopyEngine("gojay") 40 ) 41 42 func gobCopy(to, from interface{}) (err error) { 43 buff := new(bytes.Buffer) 44 if err = gob.NewEncoder(buff).Encode(from); err != nil { 45 return 46 } 47 err = gob.NewDecoder(buff).Decode(to) 48 return 49 } 50 51 func jsonCopy(to, from interface{}) (err error) { 52 var b []byte 53 if b, err = json.Marshal(from); err != nil { 54 return 55 } 56 err = json.Unmarshal(b, to) 57 return 58 } 59 60 func gojayCopy(to, from interface{}) (err error) { 61 var b []byte 62 if b, err = gojay.Marshal(from); err != nil { 63 return 64 } 65 err = gojay.Unmarshal(b, to) 66 return 67 } 68 69 // Copy ... 70 func Copy(to, from interface{}, params ...CopyEngine) (err error) { 71 72 if len(params) == 0 { 73 err = copier.Copy(to, from) 74 return 75 } 76 77 switch params[0] { 78 case JsonEngine: 79 err = jsonCopy(to, from) 80 case GobEngine: 81 err = gobCopy(to, from) 82 default: 83 err = gojayCopy(to, from) 84 85 } 86 87 return 88 }