Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

78 rindas
2.3 KiB

  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gensupport
  5. import (
  6. "bytes"
  7. "io"
  8. "google.golang.org/api/googleapi"
  9. )
  10. // MediaBuffer buffers data from an io.Reader to support uploading media in retryable chunks.
  11. type MediaBuffer struct {
  12. media io.Reader
  13. chunk []byte // The current chunk which is pending upload. The capacity is the chunk size.
  14. err error // Any error generated when populating chunk by reading media.
  15. // The absolute position of chunk in the underlying media.
  16. off int64
  17. }
  18. func NewMediaBuffer(media io.Reader, chunkSize int) *MediaBuffer {
  19. return &MediaBuffer{media: media, chunk: make([]byte, 0, chunkSize)}
  20. }
  21. // Chunk returns the current buffered chunk, the offset in the underlying media
  22. // from which the chunk is drawn, and the size of the chunk.
  23. // Successive calls to Chunk return the same chunk between calls to Next.
  24. func (mb *MediaBuffer) Chunk() (chunk io.Reader, off int64, size int, err error) {
  25. // There may already be data in chunk if Next has not been called since the previous call to Chunk.
  26. if mb.err == nil && len(mb.chunk) == 0 {
  27. mb.err = mb.loadChunk()
  28. }
  29. return bytes.NewReader(mb.chunk), mb.off, len(mb.chunk), mb.err
  30. }
  31. // loadChunk will read from media into chunk, up to the capacity of chunk.
  32. func (mb *MediaBuffer) loadChunk() error {
  33. bufSize := cap(mb.chunk)
  34. mb.chunk = mb.chunk[:bufSize]
  35. read := 0
  36. var err error
  37. for err == nil && read < bufSize {
  38. var n int
  39. n, err = mb.media.Read(mb.chunk[read:])
  40. read += n
  41. }
  42. mb.chunk = mb.chunk[:read]
  43. return err
  44. }
  45. // Next advances to the next chunk, which will be returned by the next call to Chunk.
  46. // Calls to Next without a corresponding prior call to Chunk will have no effect.
  47. func (mb *MediaBuffer) Next() {
  48. mb.off += int64(len(mb.chunk))
  49. mb.chunk = mb.chunk[0:0]
  50. }
  51. type readerTyper struct {
  52. io.Reader
  53. googleapi.ContentTyper
  54. }
  55. // ReaderAtToReader adapts a ReaderAt to be used as a Reader.
  56. // If ra implements googleapi.ContentTyper, then the returned reader
  57. // will also implement googleapi.ContentTyper, delegating to ra.
  58. func ReaderAtToReader(ra io.ReaderAt, size int64) io.Reader {
  59. r := io.NewSectionReader(ra, 0, size)
  60. if typer, ok := ra.(googleapi.ContentTyper); ok {
  61. return readerTyper{r, typer}
  62. }
  63. return r
  64. }