io.ReadWriteSeeker在golang中的实现

Implementation of io.ReadWriteSeeker in golang

是否有 io.ReadWriteSeeker 的实现可以在 Golang 中使用?

由于bytes.Buffer没有实现Seek方法,所以我需要找到这样的实现来作为zipwriter写的缓冲区,用seeking来读取。

此外,我不会使用 Reader(buff.Bytes()) 来隐藏内存副本,因为我无法为缓冲数据提供双倍的内存大小。

此外,当使用os.File作为选项时,如果我不调用f.Sync,它永远不会触及文件系统,对吧?谢谢。

我的简化代码:

func process() {
  buff := new(bytes.Buffer)
  zipWriter := zip.NewWriter(buff)
  // here to add data into zipWriter in sequence
  zipWriter.Close()
  upload(buff) // upload(io.ReadSeeker)
}

例如,对(uBufzBuf)缓冲区使用相同的底层数组,

package main

import (
    "archive/zip"
    "bytes"
    "io"
)

func upload(io.ReadSeeker) {}

func process() {
    zBuf := new(bytes.Buffer)
    zipWriter := zip.NewWriter(zBuf)
    // add data into zipWriter in sequence
    zipWriter.Close()
    uBuf, zBuf := zBuf.Bytes(), nil
    // upload(io.ReadSeeker)
    upload(bytes.NewReader(uBuf))
}

func main() {}

游乐场:https://play.golang.org/p/8TKmnL_vRY9


Package bytes

import "bytes" 

func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

Bytes returns a slice of length b.Len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification (that is, only until the next call to a method like Read, Write, Reset, or Truncate). The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.

元组赋值语句

    uBuf, zBuf := zBuf.Bytes(), nil

获取压缩字节 (zBuf.Bytes()) 的切片描述符并将其分配给切片描述符 uBuf。切片描述符是一个 struct,带有指向底层数组、切片长度和切片容量的指针。例如,

type slice struct {
    array unsafe.Pointer
    len   int
    cap   int
}

然后,为了安全起见,我们将nil分配给zBuf,以确保不能对其底层数组进行进一步的更改,该数组现在由uBuf使用。