Copyright 2016 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 gensupport

import (
	
	
	
	
	
	
	
	
	
	

	
)

const sniffBuffSize = 512

func ( io.Reader) *contentSniffer {
	return &contentSniffer{r: }
}
contentSniffer wraps a Reader, and reports the content type determined by sniffing up to 512 bytes from the Reader.
type contentSniffer struct {
	r     io.Reader
	start []byte // buffer for the sniffed bytes.
	err   error  // set to any error encountered while reading bytes to be sniffed.

	ctype   string // set on first sniff.
	sniffed bool   // set to true on first sniff.
}

Ensure that the content type is sniffed before any data is consumed from Reader.
	_, _ = .ContentType()

	if len(.start) > 0 {
		 := copy(, .start)
		.start = .start[:]
		return , nil
	}
We may have read some bytes into start while sniffing, even if the read ended in an error. We should first return those bytes, then the error.
	if .err != nil {
		return 0, .err
	}
Now we have handled all bytes that were buffered while sniffing. Now just delegate to the underlying reader.
	return .r.Read()
}
ContentType returns the sniffed content type, and whether the content type was successfully sniffed.
func ( *contentSniffer) () (string, bool) {
	if .sniffed {
		return .ctype, .ctype != ""
	}
If ReadAll hits EOF, it returns err==nil.
Don't try to detect the content type based on possibly incomplete data.
	if .err != nil {
		return "", false
	}

	.ctype = http.DetectContentType(.start)
	return .ctype, true
}
DetermineContentType determines the content type of the supplied reader. If the content type is already known, it can be specified via ctype. Otherwise, the content of media will be sniffed to determine the content type. If media implements googleapi.ContentTyper (deprecated), this will be used instead of sniffing the content. After calling DetectContentType the caller must not perform further reads on media, but rather read from the Reader that is returned.
Note: callers could avoid calling DetectContentType if ctype != "", but doing the check inside this function reduces the amount of generated code.
	if  != "" {
		return , 
	}
For backwards compatibility, allow clients to set content type by providing a ContentTyper for media.
	if ,  := .(googleapi.ContentTyper);  {
		return , .ContentType()
	}

	 := newContentSniffer()
	if ,  := .ContentType();  {
		return , 
If content type could not be sniffed, reads from sniffer will eventually fail with an error.
	return , ""
}

type typeReader struct {
	io.Reader
	typ string
}
multipartReader combines the contents of multiple readers to create a multipart/related HTTP body. Close must be called if reads from the multipartReader are abandoned before reaching EOF.
boundary optionally specifies the MIME boundary
func ( []typeReader,  string) *multipartReader {
	 := &multipartReader{pipeOpen: true}
	var  *io.PipeWriter
	.pr,  = io.Pipe()
	 := multipart.NewWriter()
	if  != "" {
		.SetBoundary()
	}
	.ctype = "multipart/related; boundary=" + .Boundary()
	go func() {
		for ,  := range  {
			,  := .CreatePart(typeHeader(.typ))
			if  != nil {
				.Close()
				.CloseWithError(fmt.Errorf("googleapi: CreatePart failed: %v", ))
				return
			}
			_,  = io.Copy(, .Reader)
			if  != nil {
				.Close()
				.CloseWithError(fmt.Errorf("googleapi: Copy failed: %v", ))
				return
			}
		}

		.Close()
		.Close()
	}()
	return 
}

func ( *multipartReader) ( []byte) ( int,  error) {
	return .pr.Read()
}

func ( *multipartReader) () error {
	.mu.Lock()
	if !.pipeOpen {
		.mu.Unlock()
		return nil
	}
	.pipeOpen = false
	.mu.Unlock()
	return .pr.Close()
}
CombineBodyMedia combines a json body with media content to create a multipart/related HTTP body. It returns a ReadCloser containing the combined body, and the overall "multipart/related" content type, with random boundary. The caller must call Close on the returned ReadCloser if reads are abandoned before reaching EOF.
func ( io.Reader,  string,  io.Reader,  string) (io.ReadCloser, string) {
	return combineBodyMedia(, , , , "")
}
combineBodyMedia is CombineBodyMedia but with an optional mimeBoundary field.
func ( io.Reader,  string,  io.Reader, ,  string) (io.ReadCloser, string) {
	 := newMultipartReader([]typeReader{
		{, },
		{, },
	}, )
	return , .ctype
}

func ( string) textproto.MIMEHeader {
	 := make(textproto.MIMEHeader)
	if  != "" {
		.Set("Content-Type", )
	}
	return 
}
PrepareUpload determines whether the data in the supplied reader should be uploaded in a single request, or in sequential chunks. chunkSize is the size of the chunk that media should be split into. If chunkSize is zero, media is returned as the first value, and the other two return values are nil, true. Otherwise, a MediaBuffer is returned, along with a bool indicating whether the contents of media fit in a single chunk. After PrepareUpload has been called, media should no longer be used: the media content should be accessed via one of the return values.
func ( io.Reader,  int) ( io.Reader,  *MediaBuffer,  bool) {
	if  == 0 { // do not chunk
		return , nil, true
	}
	 = NewMediaBuffer(, )
If err is io.EOF, we can upload this in a single request. Otherwise, err is either nil or a non-EOF error. If it is the latter, then the next call to mb.Chunk will return the same error. Returning a MediaBuffer ensures that this error will be handled at some point.
	return nil, ,  == io.EOF
}
MediaInfo holds information for media uploads. It is intended for use by generated code only.
At most one of Media and MediaBuffer will be set.
	media           io.Reader
	buffer          *MediaBuffer
	singleChunk     bool
	mType           string
	size            int64 // mediaSize, if known.  Used only for calls to progressUpdater_.
	progressUpdater googleapi.ProgressUpdater
}
NewInfoFromMedia should be invoked from the Media method of a call. It returns a MediaInfo populated with chunk size and content type, and a reader or MediaBuffer if needed.
func ( io.Reader,  []googleapi.MediaOption) *MediaInfo {
	 := &MediaInfo{}
	 := googleapi.ProcessMediaOptions()
	if !.ForceEmptyContentType {
		, .mType = DetermineContentType(, .ContentType)
	}
	.media, .buffer, .singleChunk = PrepareUpload(, .ChunkSize)
	return 
}
NewInfoFromResumableMedia should be invoked from the ResumableMedia method of a call. It returns a MediaInfo using the given reader, size and media type.
func ( io.ReaderAt,  int64,  string) *MediaInfo {
	 := ReaderAtToReader(, )
	,  := DetermineContentType(, )
	return &MediaInfo{
		size:        ,
		mType:       ,
		buffer:      NewMediaBuffer(, googleapi.DefaultUploadChunkSize),
		media:       nil,
		singleChunk: false,
	}
}
SetProgressUpdater sets the progress updater for the media info.
func ( *MediaInfo) ( googleapi.ProgressUpdater) {
	if  != nil {
		.progressUpdater = 
	}
}
UploadType determines the type of upload: a single request, or a resumable series of requests.
func ( *MediaInfo) () string {
	if .singleChunk {
		return "multipart"
	}
	return "resumable"
}
UploadRequest sets up an HTTP request for media upload. It adds headers as necessary, and returns a replacement for the body and a function for http.Request.GetBody.
func ( *MediaInfo) ( http.Header,  io.Reader) ( io.Reader,  func() (io.ReadCloser, error),  func()) {
	 = func() {}
	if  == nil {
		return , nil, 
	}
	var  io.Reader
This only happens when the caller has turned off chunking. In that case, we write all of media in a single non-retryable request.
		 = .media
The data fits in a single chunk, which has now been read into the MediaBuffer. We obtain that chunk so we can write it in a single request. The request can be retried because the data is stored in the MediaBuffer.
		, _, _, _ = .buffer.Chunk()
	}
	if  != nil {
		 := readerFunc()
		 := readerFunc()
		,  := CombineBodyMedia(, "application/json", , .mType)
		 := []io.Closer{
			,
		}
		if  != nil &&  != nil {
			 = func() (io.ReadCloser, error) {
				 := ioutil.NopCloser(())
				 := ioutil.NopCloser(())
				var  string
				if , ,  := mime.ParseMediaType();  == nil {
					 = ["boundary"]
				}
				,  := combineBodyMedia(, "application/json", , .mType, )
				 = append(, )
				return , nil
			}
		}
		 = func() {
			for ,  := range  {
				_ = .Close()
			}

		}
		.Set("Content-Type", )
		 = 
	}
	if .buffer != nil && .mType != "" && !.singleChunk {
		.Set("X-Upload-Content-Type", .mType)
	}
	return , , 
}
readerFunc returns a function that always returns an io.Reader that has the same contents as r, provided that can be done without consuming r. Otherwise, it returns nil. See http.NewRequest (in net/http/request.go).
func ( io.Reader) func() io.Reader {
	switch r := .(type) {
	case *bytes.Buffer:
		 := .Bytes()
		return func() io.Reader { return bytes.NewReader() }
	case *bytes.Reader:
		 := *
		return func() io.Reader {  := ; return & }
	case *strings.Reader:
		 := *
		return func() io.Reader {  := ; return & }
	default:
		return nil
	}
}
ResumableUpload returns an appropriately configured ResumableUpload value if the upload is resumable, or nil otherwise.
func ( *MediaInfo) ( string) *ResumableUpload {
	if  == nil || .singleChunk {
		return nil
	}
	return &ResumableUpload{
		URI:       ,
		Media:     .buffer,
		MediaType: .mType,
		Callback: func( int64) {
			if .progressUpdater != nil {
				.progressUpdater(, .size)
			}
		},
	}
}
SetGetBody sets the GetBody field of req to f. This was once needed to gracefully support Go 1.7 and earlier which didn't have that field. Deprecated: the code generator no longer uses this as of 2019-02-19. Nothing else should be calling this anyway, but we won't delete this immediately; it will be deleted in as early as 6 months.
func ( *http.Request,  func() (io.ReadCloser, error)) {
	.GetBody =