github.com/viant/toolbox@v0.34.5/writer_at.go (about)

     1  package toolbox
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  //ByteWriterAt  represents a bytes writer at
     8  type ByteWriterAt struct {
     9  	mutex    *sync.Mutex
    10  	Buffer   []byte
    11  	position int
    12  }
    13  
    14  //WriteAt returns number of written bytes or error
    15  func (w *ByteWriterAt) WriteAt(p []byte, offset int64) (n int, err error) {
    16  	w.mutex.Lock()
    17  
    18  	if int(offset) == w.position {
    19  		w.Buffer = append(w.Buffer, p...)
    20  		w.position += len(p)
    21  		w.mutex.Unlock()
    22  		return len(p), nil
    23  	} else if w.position < int(offset) {
    24  		var diff = (int(offset) - w.position)
    25  		var fillingBytes = make([]byte, diff)
    26  		w.position += len(fillingBytes)
    27  		w.Buffer = append(w.Buffer, fillingBytes...)
    28  		w.mutex.Unlock()
    29  		return w.WriteAt(p, offset)
    30  	} else {
    31  		for i := 0; i < len(p); i++ {
    32  			var index = int(offset) + i
    33  			if index < len(w.Buffer) {
    34  				w.Buffer[int(offset)+i] = p[i]
    35  			} else {
    36  				w.Buffer = append(w.Buffer, p[i:]...)
    37  				break
    38  			}
    39  		}
    40  		w.mutex.Unlock()
    41  		return len(p), nil
    42  	}
    43  }
    44  
    45  //NewWriterAt returns a new instance of byte writer at
    46  func NewByteWriterAt() *ByteWriterAt {
    47  	return &ByteWriterAt{
    48  		mutex:  &sync.Mutex{},
    49  		Buffer: make([]byte, 0),
    50  	}
    51  }