github.com/vescale/zgraph@v0.0.0-20230410094002-959c02d50f95/codec/edge_key.go (about) 1 // Copyright 2022 zGraph Authors. 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 15 package codec 16 17 import "errors" 18 19 const ( 20 incomingEdgeSep = 'i' 21 outgoingEdgeSep = 'o' 22 ) 23 24 const EdgeKeyLen = 1 /*prefix*/ + 8 /*graphID*/ + 8 /*srcVertexID*/ + 1 /*edgeSep*/ + 8 /*dstVertexID*/ 25 26 // IncomingEdgeKey encodes the incoming edge key. 27 // 28 // The key format is: ${Prefix}${GraphID}${DstVertexID}${IncomingEdgeSep}${SrcVertexID}. 29 func IncomingEdgeKey(graphID, srcVertexID, dstVertexID int64) []byte { 30 result := make([]byte, 0, EdgeKeyLen) 31 result = append(result, prefix...) 32 result = EncodeInt(result, graphID) 33 result = EncodeInt(result, dstVertexID) 34 result = append(result, incomingEdgeSep) 35 result = EncodeInt(result, srcVertexID) 36 return result 37 } 38 39 // ParseIncomingEdgeKey parse the incoming edge key. 40 func ParseIncomingEdgeKey(key []byte) (graphID, srcVertexID, dstVertexID int64, err error) { 41 if len(key) < EdgeKeyLen { 42 return 0, 0, 0, errors.New("insufficient key length") 43 } 44 _, graphID, err = DecodeInt(key[len(prefix):]) 45 if err != nil { 46 return 47 } 48 _, dstVertexID, err = DecodeInt(key[len(prefix)+8:]) 49 if err != nil { 50 return 51 } 52 _, srcVertexID, err = DecodeInt(key[len(prefix)+8+8+1:]) 53 return 54 } 55 56 // OutgoingEdgeKey encodes the outgoing edge key. 57 // 58 // The key format is: ${Prefix}${GraphID}${SrcVertexID}${outgoingEdgeSep}${DstVertexID}. 59 func OutgoingEdgeKey(graphID, srcVertexID, dstVertexID int64) []byte { 60 result := make([]byte, 0, EdgeKeyLen) 61 result = append(result, prefix...) 62 result = EncodeInt(result, graphID) 63 result = EncodeInt(result, srcVertexID) 64 result = append(result, outgoingEdgeSep) 65 result = EncodeInt(result, dstVertexID) 66 return result 67 } 68 69 // ParseOutgoingEdgeKey parse the outgoing edge key. 70 func ParseOutgoingEdgeKey(key []byte) (graphID, srcVertexID, dstVertexID int64, err error) { 71 if len(key) < EdgeKeyLen { 72 return 0, 0, 0, errors.New("insufficient key length") 73 } 74 _, graphID, err = DecodeInt(key[len(prefix):]) 75 if err != nil { 76 return 77 } 78 _, srcVertexID, err = DecodeInt(key[len(prefix)+8:]) 79 if err != nil { 80 return 81 } 82 _, dstVertexID, err = DecodeInt(key[len(prefix)+8+8+1:]) 83 return 84 }