// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package slicewriter

import (
	
	
)

// WriteSeeker is a helper object that implements the io.WriteSeeker
// interface. Clients can create a WriteSeeker, make a series of Write
// calls to add data to it (and possibly Seek calls to update
// previously written portions), then finally invoke BytesWritten() to
// get a pointer to the constructed byte slice.
type WriteSeeker struct {
	payload []byte
	off     int64
}

func ( *WriteSeeker) ( []byte) ( int,  error) {
	 := len()
	 := .payload[.off:]
	if len() <  {
		.payload = append(.payload, make([]byte, -len())...)
		 = .payload[.off:]
	}
	copy(, )
	.off += int64()
	return , nil
}

// Seek repositions the read/write position of the WriteSeeker within
// its internally maintained slice. Note that it is not possible to
// expand the size of the slice using SEEK_SET; trying to seek outside
// the slice will result in an error.
func ( *WriteSeeker) ( int64,  int) (int64, error) {
	switch  {
	case io.SeekStart:
		if .off !=  && ( < 0 ||  > int64(len(.payload))) {
			return 0, fmt.Errorf("invalid seek: new offset %d (out of range [0 %d]", , len(.payload))
		}
		.off = 
		return , nil
	case io.SeekCurrent:
		 := .off + 
		if  != .off && ( < 0 ||  > int64(len(.payload))) {
			return 0, fmt.Errorf("invalid seek: new offset %d (out of range [0 %d]", , len(.payload))
		}
		.off += 
		return .off, nil
	case io.SeekEnd:
		 := int64(len(.payload)) + 
		if  != .off && ( < 0 ||  > int64(len(.payload))) {
			return 0, fmt.Errorf("invalid seek: new offset %d (out of range [0 %d]", , len(.payload))
		}
		.off = 
		return .off, nil
	}
	// other modes not supported
	return 0, fmt.Errorf("unsupported seek mode %d", )
}

// BytesWritten returns the underlying byte slice for the WriteSeeker,
// containing the data written to it via Write/Seek calls.
func ( *WriteSeeker) () []byte {
	return .payload
}

func ( *WriteSeeker) ( []byte) ( int,  error) {
	 := len()
	 := .payload[.off:]
	if len() <  {
		 = len()
	}
	copy(, )
	.off += int64()
	return , nil
}