// WriteEnveloped writes enveloped value using the strict envelope.
323956
func (bw *Writer) WriteEnveloped(e wire.Envelope) error {
	version := uint32(version1) | uint32(e.Type)

	if err := bw.writeInt32(int32(version)); err != nil {
		return err
	}

	if err := bw.writeString(e.Name); err != nil {
		return err
	}

	if err := bw.writeInt32(e.SeqID); err != nil {
		return err
	}

	return bw.WriteValue(e.Value)
}
1094392
func GetBytesEnvelope(env *common.Envelope) ([]byte, error) {
	bytes, err := proto.Marshal(env)
	return bytes, errors.Wrap(err, "error marshaling Envelope")
}
1330931
func (f *Formatter) WriteWrapped(str string, a ...interface{}) error {
	if f.Wrap == 0 {
		return f.Write(str, a...)
	}
	text := fmt.Sprintf(str, a...)
	strs := wrapString(text, f.Wrap-f.IndentLevel)
	for _, substr := range strs {
		if err := f.Write(substr); err != nil {
			return err
		}
	}
	return nil
}
873575
func (f HandshakeHeaderFunc) WriteTo(w io.Writer) (int64, error) {
	return f(w)
}
783586
func (o *orderedDict) serialized() []entry {
	out := make([]entry, 0, o.length())
	for e := o.ll.Front(); e != nil; e = e.Next() {
		out = append(out, *e.Value.(*entry))
	}
	return out
}
1048579
func (w *Whisper) GetEnvelope(hash common.Hash) *Envelope {
	w.poolMu.RLock()
	defer w.poolMu.RUnlock()
	return w.envelopes[hash]
}
892209
func (c *C2) maxWritten() int {
	if c.totalWritten < c.blocksize {
		return c.totalWritten
	}

	return c.blocksize
}
813226
func (fbo *folderBranchOps) createEntryLocked(
	ctx context.Context, lState *kbfssync.LockState, dir Node, name string,
	entryType data.EntryType, excl Excl) (childNode Node, de data.DirEntry, err error) {
	fbo.mdWriterLock.AssertLocked(lState)

	if err := checkDisallowedPrefixes(ctx, name); err != nil {
		return nil, data.DirEntry{}, err
	}

	if uint32(len(name)) > fbo.config.MaxNameBytes() {
		return nil, data.DirEntry{},
			NameTooLongError{name, fbo.config.MaxNameBytes()}
	}

	if err := fbo.checkForUnlinkedDir(dir); err != nil {
		return nil, data.DirEntry{}, err
	}

	filename, err := fbo.canonicalPath(ctx, dir, name)
	if err != nil {
		return nil, data.DirEntry{}, err
	}

	// Verify we have permission to write (but don't make a successor yet).
	md, err := fbo.getMDForWriteLockedForFilename(ctx, lState, filename)
	if err != nil {
		return nil, data.DirEntry{}, err
	}

	dirPath, err := fbo.pathFromNodeForMDWriteLocked(lState, dir)
	if err != nil {
		return nil, data.DirEntry{}, err
	}

	// does name already exist?
	_, err = fbo.blocks.GetEntry(
		ctx, lState, md.ReadOnly(), dirPath.ChildPathNoPtr(name))
	if err == nil {
		return nil, data.DirEntry{}, data.NameExistsError{Name: name}
	} else if _, notExists := errors.Cause(err).(idutil.NoSuchNameError); !notExists {
		return nil, data.DirEntry{}, err
	}

	parentPtr := dirPath.TailPointer()
	co, err := newCreateOp(name, parentPtr, entryType)
	if err != nil {
		return nil, data.DirEntry{}, err
	}
	co.setFinalPath(dirPath)
	// create new data block
	var newBlock data.Block
	if entryType == data.Dir {
		newBlock = &data.DirBlock{
			Children: make(map[string]data.DirEntry),
		}
	} else {
		newBlock = &data.FileBlock{}
	}

	// Cache update and operations until batch happens.  Make a new
	// temporary ID and directory entry.
	newID, err := fbo.config.cryptoPure().MakeTemporaryBlockID()
	if err != nil {
		return nil, data.DirEntry{}, err
	}

	chargedTo, err := chargedToForTLF(
		ctx, fbo.config.KBPKI(), fbo.config.KBPKI(), fbo.config,
		md.GetTlfHandle())
	if err != nil {
		return nil, data.DirEntry{}, err
	}

	newPtr := data.BlockPointer{
		ID:         newID,
		KeyGen:     md.LatestKeyGeneration(),
		DataVer:    fbo.config.DataVersion(),
		DirectType: data.DirectBlock,
		Context: kbfsblock.MakeFirstContext(
			chargedTo, fbo.config.DefaultBlockType()),
	}
	co.AddRefBlock(newPtr)
	co.AddSelfUpdate(parentPtr)

	node, err := fbo.nodeCache.GetOrCreate(newPtr, name, dir, entryType)
	if err != nil {
		return nil, data.DirEntry{}, err
	}

	err = fbo.config.DirtyBlockCache().Put(
		ctx, fbo.id(), newPtr, fbo.branch(), newBlock)
	if err != nil {
		return nil, data.DirEntry{}, err
	}

	now := fbo.nowUnixNano()
	de = data.DirEntry{
		BlockInfo: data.BlockInfo{
			BlockPointer: newPtr,
			EncodedSize:  0,
		},
		EntryInfo: data.EntryInfo{
			Type:  entryType,
			Size:  0,
			Mtime: now,
			Ctime: now,
		},
	}

	// Set the TeamWriter for team TLFs, so we can return the
	// LastWriterUnverified before the writes are flushed from memory.
	if fbo.id().Type() == tlf.SingleTeam {
		session, err := fbo.config.KBPKI().GetCurrentSession(ctx)
		if err != nil {
			return nil, data.DirEntry{}, err
		}
		de.TeamWriter = session.UID
	}

	dirCacheUndoFn, err := fbo.blocks.AddDirEntryInCache(
		ctx, lState, md.ReadOnly(), dirPath, name, de)
	if err != nil {
		return nil, data.DirEntry{}, err
	}
	fbo.dirOps = append(fbo.dirOps, cachedDirOp{co, []Node{dir, node}})
	added := fbo.status.addDirtyNode(dir)

	cleanupFn := func() {
		if added {
			fbo.status.rmDirtyNode(dir)
		}
		fbo.dirOps = fbo.dirOps[:len(fbo.dirOps)-1]
		if dirCacheUndoFn != nil {
			dirCacheUndoFn(lState)
		}
		// Delete should never fail.
		_ = fbo.config.DirtyBlockCache().Delete(fbo.id(), newPtr, fbo.branch())
	}
	defer func() {
		if err != nil && cleanupFn != nil {
			cleanupFn()
		}
	}()

	if entryType != data.Dir {
		// Dirty the file with a zero-byte write, to ensure the new
		// block is synced in SyncAll.  TODO: remove this if we ever
		// embed 0-byte files in the directory entry itself.
		err = fbo.blocks.Write(
			ctx, lState, md.ReadOnly(), node, []byte{}, 0)
		if err != nil {
			return nil, data.DirEntry{}, err
		}
		oldCleanupFn := cleanupFn
		cleanupFn = func() {
			fbo.blocks.ClearCacheInfo(lState, fbo.nodeCache.PathFromNode(node))
			oldCleanupFn()
		}
	}

	// It's safe to notify before we've synced, since it is only
	// sending invalidation notifications.  At worst the upper layer
	// will just have to refresh its cache needlessly.
	err = fbo.notifyOneOp(ctx, lState, co, md.ReadOnly(), false)
	if err != nil {
		return nil, data.DirEntry{}, err
	}

	if excl == WithExcl {
		// Sync this change to the server.
		err := fbo.syncAllLocked(ctx, lState, WithExcl)
		_, isNoUpdatesWhileDirty := errors.Cause(err).(NoUpdatesWhileDirtyError)
		if isNoUpdatesWhileDirty {
			// If an exclusive write hits a conflict, it will try to
			// update, but won't be able to because of the dirty
			// directory entries.  We need to clean up the dirty
			// entries here first before trying to apply the updates
			// again.  By returning `ExclOnUnmergedError` below, we
			// force the caller to retry the whole operation again.
			fbo.log.CDebugf(ctx, "Clearing dirty entry before applying new "+
				"updates for exclusive write")
			cleanupFn()
			cleanupFn = nil

			// Sync anything else that might be buffered (non-exclusively).
			err = fbo.syncAllLocked(ctx, lState, NoExcl)
			if err != nil {
				return nil, data.DirEntry{}, err
			}

			// Now we should be in a clean state, so this should work.
			err = fbo.getAndApplyMDUpdates(
				ctx, lState, nil, fbo.applyMDUpdatesLocked)
			if err != nil {
				return nil, data.DirEntry{}, err
			}
			return nil, data.DirEntry{}, ExclOnUnmergedError{}
		} else if err != nil {
			return nil, data.DirEntry{}, err
		}
	} else {
		err = fbo.syncDirUpdateOrSignal(ctx, lState)
		if err != nil {
			return nil, data.DirEntry{}, err
		}
	}

	return node, de, nil
}
25455
func (enc *Encoder) writeString(s string) {
	enc.buf = append(enc.buf, s...)
}
544175
func (b *Bitmap) writeToUnoptimized(w io.Writer) (n int64, err error) {
	// Remove empty containers before persisting.
	//b.removeEmptyContainers()

	containerCount := b.Containers.Size() - b.countEmptyContainers()
	headerSize := headerBaseSize
	byte2 := make([]byte, 2)
	byte4 := make([]byte, 4)
	byte8 := make([]byte, 8)

	// Build header before writing individual container blocks.
	// Metadata for each container is 8+2+2+4 = sizeof(key) + sizeof(type)+sizeof(cardinality) + sizeof(file offset)
	// Type is stored as 2 bytes, even though it's only got values 1..3.
	// Cookie header section.
	ew := &errWriter{
		w: w,
		n: 0,
	}

	ew.WriteUint32(byte4, cookie)
	ew.WriteUint32(byte4, uint32(containerCount))

	// Descriptive header section: encode keys and cardinality.
	// Key and cardinality are stored interleaved here, 12 bytes per container.
	citer, _ := b.Containers.Iterator(0)
	for citer.Next() {
		key, c := citer.Value()
		// Verify container count before writing.
		// TODO: instead of commenting this out, we need to make it a configuration option
		//count := c.count()
		//assert(c.count() == c.n, "cannot write container count, mismatch: count=%d, n=%d", count, c.n)
		if c.n > 0 {
			ew.WriteUint64(byte8, key)
			ew.WriteUint16(byte2, uint16(c.typ))
			ew.WriteUint16(byte2, uint16(c.n-1))
		}

	}

	// Offset header section: write the offset for each container block.
	// 4 bytes per container.
	offset := uint32(headerSize + (containerCount * (8 + 2 + 2 + 4)))
	citer, _ = b.Containers.Iterator(0)
	for citer.Next() {
		_, c := citer.Value()
		if c.n > 0 {
			ew.WriteUint32(byte4, offset)
			offset += uint32(c.size())
		}

	}
	if ew.err != nil {
		return int64(ew.n), ew.err
	}

	n = int64(headerSize + (containerCount * (8 + 2 + 2 + 4)))

	// Container storage section: write each container block.
	citer, _ = b.Containers.Iterator(0)
	for citer.Next() {
		_, c := citer.Value()
		if c.n > 0 {
			nn, err := c.WriteTo(w)
			n += nn
			if err != nil {
				return n, err
			}
		}
	}
	return n, nil
}
1062644
func (e entityMsgPackAccess) Write(resp *restful.Response, status int, v interface{}) error {
	if v == nil {
		resp.WriteHeader(status)
		// do not write a nil representation
		return nil
	}
	resp.WriteHeader(status)
	return msgpack.NewEncoder(resp).Encode(v)
}
653505
func (out *DataOutputImpl) WriteVLong(i int64) error {
	assert(i >= 0)
	return out.writeNegativeVLong(i)
}
581058
func (s *syncWriter) WriteLevel(l Level, p []byte) (n int, err error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.lw.WriteLevel(l, p)
}
642659
func UnmarshalEnvelopeOfType(envelope *cb.Envelope, headerType cb.HeaderType, message proto.Message) (*cb.ChannelHeader, error) {
	payload, err := UnmarshalPayload(envelope.Payload)
	if err != nil {
		return nil, err
	}

	if payload.Header == nil {
		return nil, errors.New("envelope must have a Header")
	}

	chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader)
	if err != nil {
		return nil, err
	}

	if chdr.Type != int32(headerType) {
		return nil, errors.Errorf("invalid type %s, expected %s", cb.HeaderType(chdr.Type), headerType)
	}

	err = proto.Unmarshal(payload.Data, message)
	err = errors.Wrapf(err, "error unmarshaling message for type %s", headerType)
	return chdr, err
}
860555
func (i RawVInt) WriteTo(w Writer) error {
	var arr [8]byte
	n := 0
	for i != 0 {
		arr[n] = byte(i & 0xff)
		n++
		i >>= 8
	}
	_, err := w.Write(arr[:n])
	return errorsp.WithStacks(err)
}
149659
func (e *IntegerEncoder) Write(v int64) {
	// Delta-encode each value as it's written.  This happens before
	// ZigZagEncoding because the deltas could be negative.
	delta := v - e.prev
	e.prev = v
	enc := ZigZagEncode(delta)
	if len(e.values) > 1 {
		e.rle = e.rle && e.values[len(e.values)-1] == enc
	}

	e.values = append(e.values, enc)
}
621372
func (e *encoder) Write(t int64) {
	e.ts = append(e.ts, uint64(t))
}