blob: 7918c14bc2c6a7e59d02e0773ca8b2ae4859150d [file] [log] [blame]
khenaidoobf6e7bb2018-08-14 22:27:29 -04001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040016package model
17
18import (
19 "bytes"
20 "crypto/md5"
21 "encoding/json"
22 "fmt"
23 "github.com/golang/protobuf/proto"
24 "reflect"
25)
26
27type DataRevision struct {
28 Data interface{}
29 Hash string
30}
31
32func NewDataRevision(data interface{}) *DataRevision {
33 cdr := &DataRevision{}
34 cdr.Data = data
35 cdr.Hash = cdr.hashData(data)
36
37 return cdr
38}
39
40func (cr *DataRevision) hashData(data interface{}) string {
41 var buffer bytes.Buffer
42
43 if IsProtoMessage(data) {
44 if pbdata, err := proto.Marshal(data.(proto.Message)); err != nil {
45 fmt.Errorf("problem to marshal protobuf data --> err: %s", err.Error())
46 } else {
47 buffer.Write(pbdata)
48 }
49
50 } else if reflect.ValueOf(data).IsValid() {
51 dataObj := reflect.New(reflect.TypeOf(data).Elem())
52 if json, err := json.Marshal(dataObj.Interface()); err != nil {
53 fmt.Errorf("problem to marshal data --> err: %s", err.Error())
54 } else {
55 buffer.Write(json)
56 }
57 } else {
58 dataObj := reflect.New(reflect.TypeOf(data).Elem())
59 buffer.Write(dataObj.Bytes())
60 }
61
62 return fmt.Sprintf("%x", md5.Sum(buffer.Bytes()))[:12]
63}