Line data Source code
1 : // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 : // of this source code is governed by a BSD-style license that can be found in 3 : // the LICENSE file. 4 : 5 : package objstorage 6 : 7 : import ( 8 : "bytes" 9 : "context" 10 : 11 : "github.com/pkg/errors" 12 : ) 13 : 14 : // MemObj is an in-memory implementation of the Writable and Readable that holds 15 : // all data in memory. 16 : // 17 : // A zero MemObj can be populated with data through its Writable methods, and 18 : // then can be repeatedly used as a Readable. 19 : type MemObj struct { 20 : buf bytes.Buffer 21 : } 22 : 23 : var _ Writable = (*MemObj)(nil) 24 : var _ Readable = (*MemObj)(nil) 25 : 26 : // Finish is part of the Writable interface. 27 1 : func (f *MemObj) Finish() error { return nil } 28 : 29 : // Abort is part of the Writable interface. 30 0 : func (f *MemObj) Abort() { f.buf.Reset() } 31 : 32 : // Write is part of the Writable interface. 33 1 : func (f *MemObj) Write(p []byte) error { 34 1 : _, err := f.buf.Write(p) 35 1 : return err 36 1 : } 37 : 38 : // Data returns the in-memory buffer behind this MemObj. 39 1 : func (f *MemObj) Data() []byte { 40 1 : return f.buf.Bytes() 41 1 : } 42 : 43 : // ReadAt is part of the Readable interface. 44 1 : func (f *MemObj) ReadAt(ctx context.Context, p []byte, off int64) error { 45 1 : if f.Size() < off+int64(len(p)) { 46 0 : return errors.Errorf("read past the end of object") 47 0 : } 48 1 : copy(p, f.Data()[off:off+int64(len(p))]) 49 1 : return nil 50 : } 51 : 52 : // Close is part of the Readable interface. 53 1 : func (f *MemObj) Close() error { return nil } 54 : 55 : // Size is part of the Readable interface. 56 1 : func (f *MemObj) Size() int64 { 57 1 : return int64(f.buf.Len()) 58 1 : } 59 : 60 : // NewReadHandle is part of the Readable interface. 61 1 : func (f *MemObj) NewReadHandle(ctx context.Context, readBeforeSize ReadBeforeSize) ReadHandle { 62 1 : return &NoopReadHandle{readable: f} 63 1 : }