// 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 slicewriterimport ()// 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.typeWriteSeekerstruct { payload []byte off int64}func ( *WriteSeeker) ( []byte) ( int, error) { := len() := .payload[.off:]iflen() < { .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 {caseio.SeekStart:if .off != && ( < 0 || > int64(len(.payload))) {return0, fmt.Errorf("invalid seek: new offset %d (out of range [0 %d]", , len(.payload)) } .off = return , nilcaseio.SeekCurrent: := .off + if != .off && ( < 0 || > int64(len(.payload))) {return0, fmt.Errorf("invalid seek: new offset %d (out of range [0 %d]", , len(.payload)) } .off += return .off, nilcaseio.SeekEnd: := int64(len(.payload)) + if != .off && ( < 0 || > int64(len(.payload))) {return0, fmt.Errorf("invalid seek: new offset %d (out of range [0 %d]", , len(.payload)) } .off = return .off, nil }// other modes not supportedreturn0, 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:]iflen() < { = len() }copy(, ) .off += int64()return , nil}
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.