// writer provides the main implementation of the Writer method. The caller
// must hold the lock correctly and release on error if there is a problem.
165678
func (s *store) writer(ctx context.Context, ref string, total int64, expected digest.Digest) (content.Writer, error) {
	// TODO(stevvooe): Need to actually store expected here. We have
	// code in the service that shouldn't be dealing with this.
	if expected != "" {
		p := s.blobPath(expected)
		if _, err := os.Stat(p); err == nil {
			return nil, errors.Wrapf(errdefs.ErrAlreadyExists, "content %v", expected)
		}
	}

	path, refp, data := s.ingestPaths(ref)

	var (
		digester  = digest.Canonical.Digester()
		offset    int64
		startedAt time.Time
		updatedAt time.Time
	)

	foundValidIngest := false
	// ensure that the ingest path has been created.
	if err := os.Mkdir(path, 0755); err != nil {
		if !os.IsExist(err) {
			return nil, err
		}
		status, err := s.resumeStatus(ref, total, digester)
		if err == nil {
			foundValidIngest = true
			updatedAt = status.UpdatedAt
			startedAt = status.StartedAt
			total = status.Total
			offset = status.Offset
		} else {
			logrus.Infof("failed to resume the status from path %s: %s. will recreate them", path, err.Error())
		}
	}

	if !foundValidIngest {
		startedAt = time.Now()
		updatedAt = startedAt

		// the ingest is new, we need to setup the target location.
		// write the ref to a file for later use
		if err := ioutil.WriteFile(refp, []byte(ref), 0666); err != nil {
			return nil, err
		}

		if err := writeTimestampFile(filepath.Join(path, "startedat"), startedAt); err != nil {
			return nil, err
		}

		if err := writeTimestampFile(filepath.Join(path, "updatedat"), startedAt); err != nil {
			return nil, err
		}

		if total > 0 {
			if err := ioutil.WriteFile(filepath.Join(path, "total"), []byte(fmt.Sprint(total)), 0666); err != nil {
				return nil, err
			}
		}
	}

	fp, err := os.OpenFile(data, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		return nil, errors.Wrap(err, "failed to open data file")
	}

	if _, err := fp.Seek(offset, io.SeekStart); err != nil {
		return nil, errors.Wrap(err, "could not seek to current write offset")
	}

	return &writer{
		s:         s,
		fp:        fp,
		ref:       ref,
		path:      path,
		offset:    offset,
		total:     total,
		digester:  digester,
		startedAt: startedAt,
		updatedAt: updatedAt,
	}, nil
}
990526
func (w *gzipResponseWriter) Writer() io.Writer {
	if w.internalWriter == nil {
		w.internalWriter = w.newWriter()
	}
	return w.internalWriter
}
386350
func (w *Writer) Write(p []byte) (n int, err error) {
	n = len(p)

	if len(w.inbuf) > 0 {
		w.inbuf = append(w.inbuf, p...)
		p = w.inbuf
	}

	if len(w.outbuf) < len(p) {
		w.outbuf = make([]byte, len(p)+10)
	}

	outpos := 0

	for len(p) > 0 {
		rune, size := utf8.DecodeRune(p)
		if rune == 0xfffd && !utf8.FullRune(p) {
			break
		}

		p = p[size:]

	retry:
		size, status := w.encode(w.outbuf[outpos:], rune)

		if status == NO_ROOM {
			newDest := make([]byte, len(w.outbuf)*2)
			copy(newDest, w.outbuf)
			w.outbuf = newDest
			goto retry
		}

		if status == STATE_ONLY {
			outpos += size
			goto retry
		}

		outpos += size
	}

	w.inbuf = w.inbuf[:0]
	if len(p) > 0 {
		w.inbuf = append(w.inbuf, p...)
	}

	n1, err := w.wr.Write(w.outbuf[0:outpos])

	if err != nil && n1 < n {
		n = n1
	}

	return
}
637328
func (w *Writer) Write(row []string) error {
	err := w.w.Write(row)
	if err != nil {
		return err
	}
	w.r++
	return nil
}
1053443
func Writer(unit string, l kitlog.Logger) io.WriteCloser {
	l = kitlog.With(l, "unit", unit)
	pr, pw := io.Pipe()
	go func() {
		s := bufio.NewScanner(pr)
		for s.Scan() {
			l.Log("msg", s.Text())
		}
		if err := s.Err(); err != nil {
			l.Log("msg", "scanner error", "err", err)
		}
	}()
	return pw
}
217939
func (wr *Writer) Write(p []byte) (n int, err error) {
	wr.bf.Write(p)
	if bytes.HasSuffix(p, []byte(wr.lastElement)) {
		return wr.writer.Write([]byte(Format(wr.bf.String()) + "\n"))
	}
	return 0, nil
}
771573
func (s *Logging) SetWriter(w io.Writer) {
	var sw zapcore.WriteSyncer
	switch t := w.(type) {
	case *os.File:
		sw = zapcore.Lock(t)
	case zapcore.WriteSyncer:
		sw = t
	default:
		sw = zapcore.AddSync(w)
	}

	s.mutex.Lock()
	s.writer = sw
	s.mutex.Unlock()
}
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
}
253989
func (w *syncWriter) Write(p []byte) (n int, err error) {
	w.Lock()
	n, err = w.Writer.Write(p)
	w.Unlock()
	return n, err
}
1311191
func (tw *Writer) Write(b []byte) (n int, err error) {
	if tw.closed {
		err = ErrWriteAfterClose
		return
	}
	overwrite := false
	if int64(len(b)) > tw.nb {
		b = b[0:tw.nb]
		overwrite = true
	}
	n, err = tw.w.Write(b)
	tw.nb -= int64(n)
	if err == nil && overwrite {
		err = ErrWriteTooLong
		return
	}
	tw.err = err
	return
}
1200593
func (cn *connection) writer(keepAliveTimeout time.Duration) {
	var (
		lastWrite      time.Time = time.Now()
		keepAliveTimer *time.Timer
	)
	keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
		cn.mu().Lock()
		defer cn.mu().Unlock()
		if time.Since(lastWrite) >= keepAliveTimeout {
			cn.tickleWriter()
		}
		keepAliveTimer.Reset(keepAliveTimeout)
	})
	cn.mu().Lock()
	defer cn.mu().Unlock()
	defer cn.Close()
	defer keepAliveTimer.Stop()
	frontBuf := new(bytes.Buffer)
	for {
		if cn.closed.IsSet() {
			return
		}
		if cn.writeBuffer.Len() == 0 {
			cn.fillWriteBuffer(func(msg pp.Message) bool {
				cn.wroteMsg(&msg)
				cn.writeBuffer.Write(msg.MustMarshalBinary())
				torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
				return cn.writeBuffer.Len() < 1<<16 // 64KiB
			})
		}
		if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
			cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
			postedKeepalives.Add(1)
		}
		if cn.writeBuffer.Len() == 0 {
			// TODO: Minimize wakeups....
			cn.writerCond.Wait()
			continue
		}
		// Flip the buffers.
		frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
		cn.mu().Unlock()
		n, err := cn.w.Write(frontBuf.Bytes())
		cn.mu().Lock()
		if n != 0 {
			lastWrite = time.Now()
			keepAliveTimer.Reset(keepAliveTimeout)
		}
		if err != nil {
			return
		}
		if n != frontBuf.Len() {
			panic("short write")
		}
		frontBuf.Reset()
	}
}
1159217
func (mw multiWriter) Write(p []byte) (int, error) {
	done := make(chan result, len(mw))
	for _, w := range mw {
		go send(w, p, done)
	}
	endResult := result{n: len(p)}
	for _ = range mw {
		res := <-done
		if res.err != nil && (endResult.err == nil || res.n < endResult.n) {
			endResult = res
		}
	}
	return endResult.n, endResult.err
}
691186
func Writer(outW, errW io.Writer) POption {
	return func(p *POptions) {
		p.outWriter, p.errWriter = outW, errW
	}
}
728920
func (u User) Write(w io.Writer, handle string) {
	fmt.Fprintf(w, "%s (@%s)\n%s\n", u.Name, handle, u.Bio)
}
1182871
func (f *StandaloneFile) Writer() (filesystem.Writer, error) {
	return f.filespace.Writer(f.path)
}
394827
func (fw *flushWriter) Write(p []byte) (n int, err error) {
	n, err = fw.w.Write(p)
	if fw.f != nil {
		fw.f.Flush()
	}
	return
}
996444
func (w *Writer) Write(p []byte) (n int, err error) {
	var linelen int
	var lastWasColon bool
	for i, c := range p {
		w.buf = append(w.buf, c)
		linelen++
		if c == '\t' {
			w.buf[len(w.buf)-1] = ' '
			for linelen%tab != 0 {
				w.buf = append(w.buf, ' ')
				linelen++
			}
		}
		if w.flag&BreakOnColon != 0 && c == ':' {
			lastWasColon = true
		} else if lastWasColon {
			if c == '\n' {
				pos := bytes.LastIndex(w.buf[:len(w.buf)-1], []byte{'\n'})
				if pos < 0 {
					pos = 0
				}
				line := w.buf[pos:]
				w.buf = w.buf[:pos]
				if err = w.columnate(); err != nil {
					if len(line) < i {
						return i - len(line), err
					}
					return 0, err
				}
				if n, err := w.w.Write(line); err != nil {
					if r := len(line) - n; r < i {
						return i - r, err
					}
					return 0, err
				}
			}
			lastWasColon = false
		}
		if c == '\n' {
			linelen = 0
		}
	}
	return len(p), nil
}