// From https://golang.org/src/mime/multipart/writer.go
359580
func (client *restClient) randomBoundary() string {
	var buf [30]byte
	_, err := io.ReadFull(rand.Reader, buf[:])
	if err != nil {
		panic(err)
	}
	return fmt.Sprintf("%x", buf[:])
}
31128
func (cw *chunkedWriter) Write(data []byte) (n int, err error) {

	// Don't send 0-length data. It looks like EOF for chunked encoding.
	if len(data) == 0 {
		return 0, nil
	}

	head := strconv.FormatInt(int64(len(data)), 16) + "\r\n"

	if _, err = io.WriteString(cw.Wire, head); err != nil {
		return 0, err
	}
	if n, err = cw.Wire.Write(data); err != nil {
		return
	}
	if n != len(data) {
		err = io.ErrShortWrite
		return
	}
	_, err = io.WriteString(cw.Wire, "\r\n")

	return
}
1116349
func (w *writer) prepare() error {
	if w.prepared {
		return nil
	}
	req, err := http.NewRequest("POST", w.o.url("?uploads"), nil)
	if err != nil {
		return err
	}

	// detect mime type
	ext := filepath.Ext(w.o.key)
	contentType := "application/octet-stream"
	if v, ok := mimeTypes[ext]; ok {
		contentType = v
	}
	req.Header.Set(`Content-Type`, contentType)

	// sign and send
	w.o.s3.signRequest(req)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if c := resp.StatusCode; c != 200 {
		return newS3Error(resp, "could not create multipart upload: %d", c)
	}

	var result struct {
		UploadId string
	}
	err = xml.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return err
	}

	w.uploadId = result.UploadId
	w.prepared = true

	return nil
}
929335
func (w *ResponseWriter) Write(p []byte) (int, error) {
	return w.w.Write(p)
}
687369
func (w *BatchedFileWriter) Write(p []byte) (n int, err error) {
	return w.file.Write(p)
}
732990
func createWriter(w io.Writer, header *Header) (*Writer, error) {
	ww := &Writer{w: w}

	mediaType, mediaParams, _ := header.ContentType()
	if strings.HasPrefix(mediaType, "multipart/") {
		ww.mw = multipart.NewWriter(ww.w)

		// Do not set ww's io.Closer for now: if this is a multipart entity but
		// CreatePart is not used (only Write is used), then the final boundary
		// is expected to be written by the user too. In this case, ww.Close
		// shouldn't write the final boundary.

		if mediaParams["boundary"] != "" {
			ww.mw.SetBoundary(mediaParams["boundary"])
		} else {
			mediaParams["boundary"] = ww.mw.Boundary()
			header.SetContentType(mediaType, mediaParams)
		}

		header.Del("Content-Transfer-Encoding")
	} else {
		wc, err := encodingWriter(header.Get("Content-Transfer-Encoding"), ww.w)
		if err != nil {
			return nil, err
		}
		ww.w = wc
		ww.c = wc
	}

	switch strings.ToLower(mediaParams["charset"]) {
	case "", "us-ascii", "utf-8":
		// This is OK
	default:
		// Anything else is invalid
		return nil, fmt.Errorf("unhandled charset %q", mediaParams["charset"])
	}

	return ww, nil
}
1360698
func (w *Writer) Write(data []byte) (n int, err error) {
	src := data
	if w.n > 0 {
		// Append bytes from data to the last remainder.
		// TODO: limit the amount copied on first try.
		n = copy(w.src[w.n:], data)
		w.n += n
		src = w.src[:w.n]
	}
	for {
		nDst, nSrc, err := w.t.Transform(w.dst, src, false)
		if _, werr := w.w.Write(w.dst[:nDst]); werr != nil {
			return n, werr
		}
		src = src[nSrc:]
		if w.n > 0 && len(src) <= n {
			// Enough bytes from w.src have been consumed. We make src point
			// to data instead to reduce the copying.
			w.n = 0
			n -= len(src)
			src = data[n:]
			if n < len(data) && (err == nil || err == ErrShortSrc) {
				continue
			}
		} else {
			n += nSrc
		}
		switch {
		case err == ErrShortDst && (nDst > 0 || nSrc > 0):
		case err == ErrShortSrc && len(src) < len(w.src):
			m := copy(w.src, src)
			// If w.n > 0, bytes from data were already copied to w.src and n
			// was already set to the number of bytes consumed.
			if w.n == 0 {
				n += m
			}
			w.n = m
			return n, nil
		case err == nil && w.n > 0:
			return n, errInconsistentByteCount
		default:
			return n, err
		}
	}
}
15156
func (w *BatchedFileWriter) Write(p []byte) (n int, err error) {
	w.activeBuffer.Write(p)

	if size, _ := w.activeBuffer.Size(); size >= minUploadPartSize {
		w.logger.WithField("size", size).Debug("Buffer size ready for request")
		w.uploadPartInput()
	} else {
		w.logger.WithField("size", size).Debug("Buffer size not big enough vor request")
	}

	length := len(p)
	w.totalSize += length
	return length, nil
}
385024
func (w *wrapper) Write(b []byte) (int, error) {
	n, err := w.ResponseWriter.Write(b)
	w.written += n
	return n, err
}
312469
func NewWriter(w io.Writer) *Writer {
	return &Writer{
		w:         multipart.NewWriter(w),
		firstPart: false,
		rootPart:  false,
	}
}
785063
func (w *gzipResponseWriter) WriteHeader(code int) {
	w.Header().Del("Content-Length")
	w.Header().Set("Content-Encoding", "gzip")
	w.Header().Add("Vary", "Accept-Encoding")
	originalEtag := w.Header().Get("ETag")
	if originalEtag != "" && !strings.HasPrefix(originalEtag, "W/") {
		w.Header().Set("ETag", "W/"+originalEtag)
	}
	w.ResponseWriterWrapper.WriteHeader(code)
	w.statusCodeWritten = true
}
728520
func (w *Writer) WriteBytes(bytes []byte) {
	setWriterRef(w, nil, nil)
	writeBytes(w, bytes)
}
177616
func Writer(w io.Writer) (io.Writer, func()) {
	var out = os.Stderr
	if f, ok := w.(*os.File); ok && f == os.Stderr {
		out = os.Stdout
	}
	sprk := Spark(time.Millisecond * 33)
	sprk.Units = Bytes
	sprk.Out = out
	started := false
	return writer(func(b []byte) (int, error) {
		if !started {
			sprk.Start()
			started = true
		}
		n, err := w.Write(b)
		if err == nil {
			sprk.Add(float64(n))
		} else {
			sprk.Stop()
		}
		return n, err
	}), sprk.Stop
}
1110409
func StorageWriter(storage StorageAPI, volume, path string) io.Writer {
	return &storageWriter{storage, volume, path}
}
977831
func (d *driver) Writer(context context.Context, path string, append bool) (storagedriver.FileWriter, error) {
	writer := &writer{
		client: d.client,
		bucket: d.bucket,
		name:   d.pathToKey(path),
		buffer: make([]byte, d.chunkSize),
	}

	if append {
		err := writer.init(path)
		if err != nil {
			return nil, err
		}
	}
	return writer, nil
}
1039987
func Write(out io.Writer, node ast.Node, options Options) (err error) {
	defer errRecover(&err)

	if options.Formatter == nil {
		options.Formatter = &ES5Formatter{}
	}

	var (
		tmpOut     = &bytes.Buffer{}
		importsBuf = &bytes.Buffer{}
		s          = &state{
			wr:          tmpOut,
			options:     options,
			funcsCalled: map[string]string{},
			funcsInFile: map[string]bool{},
		}
	)

	s.scope.push()
	s.walk(node)

	if len(s.funcsCalled) > 0 {
		for _, f := range difference(s.funcsCalled, s.funcsInFile) {
			importsBuf.WriteString(s.funcsCalled[f])
			importsBuf.WriteRune('\n')
		}
		importsBuf.WriteRune('\n')
	}

	out.Write(importsBuf.Bytes())
	out.Write(tmpOut.Bytes())

	return nil
}
1039124
func (w *Writer) CreatePart(header Header) (*Writer, error) {
	if w.mw == nil {
		return nil, errors.New("cannot create a part in a non-multipart message")
	}

	if w.c == nil {
		// We know that the user calls CreatePart so Close should write the final
		// boundary
		w.c = w.mw
	}

	// cw -> ww -> pw -> w.mw -> w.w

	ww := &struct{ io.Writer }{nil}
	cw, err := createWriter(ww, &header)
	if err != nil {
		return nil, err
	}
	pw, err := w.mw.CreatePart(headerToMap(header.Header))
	if err != nil {
		return nil, err
	}

	ww.Writer = pw
	return cw, nil
}