2018-03-25 14:51
浏览 677


Is there an implementation of io.ReadWriteSeeker to use in Golang?

Since, bytes.Buffer does not implement Seek method, I need to find such an implementation to use as a buffer written by zipwriter and to be read with seeking.

In addition I wont go with Reader(buff.Bytes()) to covert with memory copy, because I can not afford double memory size for buffered data.

In addition, when using os.File as the option, if I wont call f.Sync, it will never touch file system, right? Thanks.

My simplified codes:

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

图片转代码服务由CSDN问答提供 功能建议

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

由于 bytes.Buffer 不实现 Seek 方法,我需要找到这样的实现以用作由编写的缓冲区 zipwriter ,请与读者一起阅读。

此外,我不会选择 Reader(buff.Bytes())来进行内存复制,因为我无法承受缓冲数据的两倍内存大小。

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


  func process(){
 buff:= new(bytes.Buffer)
 zipWriter  := zip.NewWriter(buff)
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • 普通网友 2018-03-25 17:46

    For example, using the same underlying array for (uBuf and zBuf) buffers,

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


    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.

    The tuple assignment statement

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

    gets the slice descriptor for the zipped bytes (zBuf.Bytes()) and assigns it to the slice descriptor uBuf. A slice descriptor is a struct with a pointer to the underlying array, the slice length, and the slice capacity. For example,

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

    Then, for safety, we assign nil to zBuf to ensure that no further changes can be made to its underlying array, which is now used by uBuf.

    解决 无用
    打赏 举报

相关推荐 更多相似问题