|
| 1 | +// Copyright © 2021 Rak Laptudirm <raklaptudirm@gmail.com> |
| 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 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package manager |
| 15 | + |
| 16 | +import ( |
| 17 | + "errors" |
| 18 | + "fmt" |
| 19 | + "os" |
| 20 | + "path" |
| 21 | +) |
| 22 | + |
| 23 | +// piece represents the piece manager. |
| 24 | +type piece struct { |
| 25 | + src string // storage directory |
| 26 | +} |
| 27 | + |
| 28 | +// ErrManagerClosed is returned when the manager is not initialized, |
| 29 | +// or closed. |
| 30 | +var ErrManagerClosed = errors.New("the manager is closed") |
| 31 | + |
| 32 | +// Init initializes the manager. |
| 33 | +func (p *piece) Init() error { |
| 34 | + home, err := os.UserHomeDir() |
| 35 | + if err != nil { |
| 36 | + return err |
| 37 | + } |
| 38 | + |
| 39 | + // create storage directory |
| 40 | + dir, err := os.MkdirTemp(home, "mtor pieces ") |
| 41 | + if err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + |
| 45 | + p.src = dir |
| 46 | + return nil |
| 47 | +} |
| 48 | + |
| 49 | +// Put stores a piece in the manager. |
| 50 | +func (p *piece) Put(i int, buf []byte) error { |
| 51 | + if p.isClosed() { |
| 52 | + return ErrManagerClosed |
| 53 | + } |
| 54 | + |
| 55 | + file := path.Join(p.src, fmt.Sprintf("%x", i)) |
| 56 | + return os.WriteFile(file, buf, 0600) |
| 57 | +} |
| 58 | + |
| 59 | +// Get fetches a piece from the manager. |
| 60 | +func (p *piece) Get(i int) ([]byte, error) { |
| 61 | + if p.isClosed() { |
| 62 | + return nil, ErrManagerClosed |
| 63 | + } |
| 64 | + |
| 65 | + file := path.Join(p.src, fmt.Sprintf("%x", i)) |
| 66 | + return os.ReadFile(file) |
| 67 | +} |
| 68 | + |
| 69 | +// Close closes the manager. |
| 70 | +func (p *piece) Close() error { |
| 71 | + if p.isClosed() { |
| 72 | + return ErrManagerClosed |
| 73 | + } |
| 74 | + |
| 75 | + // free space |
| 76 | + return os.RemoveAll(p.src) |
| 77 | +} |
| 78 | + |
| 79 | +// isClosed checks if the manager is closed. |
| 80 | +func (p *piece) isClosed() bool { |
| 81 | + return p.src == "" |
| 82 | +} |
| 83 | + |
| 84 | +// New returns a new and un-initialzed instance of the manager. |
| 85 | +func New() *piece { |
| 86 | + return &piece{} |
| 87 | +} |
0 commit comments