github.com/bhojpur/cache@v0.0.4/pkg/file/types/shard_io.go (about) 1 package types 2 3 // Copyright (c) 2018 Bhojpur Consulting Private Limited, India. All rights reserved. 4 5 // Permission is hereby granted, free of charge, to any person obtaining a copy 6 // of this software and associated documentation files (the "Software"), to deal 7 // in the Software without restriction, including without limitation the rights 8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 // copies of the Software, and to permit persons to whom the Software is 10 // furnished to do so, subject to the following conditions: 11 12 // The above copyright notice and this permission notice shall be included in 13 // all copies or substantial portions of the Software. 14 15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 // THE SOFTWARE. 22 23 import ( 24 "encoding/json" 25 "errors" 26 "fmt" 27 "io/ioutil" 28 "path/filepath" 29 30 "github.com/bhojpur/cache/pkg/file/common" 31 ) 32 33 // ErrInvalidShard is returned when a shard's hash is not valid when loading from memory. 34 var ErrInvalidShard = errors.New("shard from memory is not valid") 35 36 // WriteShardToMemory writes a shard to memory. 37 func (shard *Shard) WriteShardToMemory() error { 38 bytes := shard.Serialize() 39 40 // Create a dir to store the shards 41 err := common.CreateDirIfDoesNotExist("data/shards") 42 if err != nil { 43 return err 44 } 45 46 // Create the filename of the hash 47 shardHashString := (*shard).Hash.String()[0:8] 48 filename := fmt.Sprintf("data/shards/shard_%s.json", shardHashString) 49 50 err = ioutil.WriteFile(filepath.FromSlash(filename), bytes, 0644) 51 if err != nil { 52 return err 53 } 54 55 return nil 56 } 57 58 // ReadShardFromMemory reads a shard from memory. 59 func ReadShardFromMemory(hash string) (*Shard, error) { 60 // Read the file from memory 61 data, err := ioutil.ReadFile(fmt.Sprintf("data/shards/shard_%s.json", hash)) 62 if err != nil { 63 return nil, err 64 } 65 66 buffer := &Shard{} // Init a shard buffer 67 68 // Read into the buffer 69 err = json.Unmarshal(data, buffer) 70 if err != nil { 71 return nil, err 72 } 73 74 if (*buffer).Validate() == false { 75 return nil, ErrInvalidShard 76 } 77 78 return buffer, nil // Return the shard pointer 79 }