// readBlockSwitch handles a block switch command according to RFC section 6.
421070
func (br *Reader) readBlockSwitch(bd *blockDecoder) {
	symType := br.rd.ReadSymbol(&bd.decType)
	switch symType {
	case 0:
		symType = uint(bd.types[1])
	case 1:
		symType = uint(bd.types[0]) + 1
		if symType >= uint(bd.numTypes) {
			symType -= uint(bd.numTypes)
		}
	default:
		symType -= 2
	}
	bd.types = [2]uint8{uint8(symType), bd.types[0]}

	symLen := br.rd.ReadSymbol(&bd.decLen)
	bd.typeLen = int(br.rd.ReadOffset(symLen, blkLenRanges))
}
713674
func GetBlockFromBlockBytes(blockBytes []byte) (*cb.Block, error) {
	block := &cb.Block{}
	err := proto.Unmarshal(blockBytes, block)
	if err != nil {
		return block, errors.Wrap(err, "error unmarshaling block")
	}
	return block, nil
}
1020675
func ReadSysBlockDeviceStat(sysfs string, device string) (IOStats, int, error) {
	stat := IOStats{}
	bytes, err := ioutil.ReadFile(path.Join(sysfs, sysBlockPath, device, "stat"))
	if err != nil {
		return stat, 0, err
	}
	count, err := fmt.Sscanf(strings.TrimSpace(string(bytes)), sysBlockStatFormat,
		&stat.ReadIOs,
		&stat.ReadMerges,
		&stat.ReadSectors,
		&stat.ReadTicks,
		&stat.WriteIOs,
		&stat.WriteMerges,
		&stat.WriteSectors,
		&stat.WriteTicks,
		&stat.IOsInProgress,
		&stat.IOsTotalTicks,
		&stat.WeightedIOTicks,
		&stat.DiscardIOs,
		&stat.DiscardMerges,
		&stat.DiscardSectors,
		&stat.DiscardTicks,
	)
	// An io.EOF error is ignored because it just means we read fewer than the full 15 fields.
	if err == io.EOF {
		return stat, count, nil
	}
	return stat, count, err
}
702993
func (br *Reader) readCommands() {
	// Since Go does not support tail call optimization, we use goto statements
	// to achieve higher performance processing each command. Each label can be
	// thought of as a mini function, and each goto as a cheap function call.
	// The following code follows this control flow.
	//
	// The bulk of the action will be in the following loop:
	//	startCommand -> readLiterals -> readDistance -> copyDynamicDict ->
	//		finishCommand -> startCommand -> ...
	/*
		             readCommands()
		                   |
		+----------------> +
		|                  |
		|                  V
		|         +-- startCommand
		|         |        |
		|         |        V
		|         |   readLiterals ----------+
		|         |        |                 |
		|         |        V                 |
		|         +-> readDistance           |
		|                  |                 |
		|         +--------+--------+        |
		|         |                 |        |
		|         V                 V        |
		|  copyDynamicDict   copyStaticDict  |
		|         |                 |        |
		|         +--------+--------+        |
		|                  |                 |
		|                  V                 |
		+----------- finishCommand <---------+
		                   |
		                   V
		           readBlockHeader()
	*/

	const (
		stateInit = iota // Zero value must be stateInit

		// Some labels (readLiterals, copyDynamicDict, copyStaticDict) require
		// work to be continued if more buffer space is needed. This is achieved
		// by the  switch block right below, which continues the work at the
		// right label based on the given sub-step value.
		stateLiterals
		stateDynamicDict
		stateStaticDict
	)

	switch br.stepState {
	case stateInit:
		goto startCommand
	case stateLiterals:
		goto readLiterals
	case stateDynamicDict:
		goto copyDynamicDict
	case stateStaticDict:
		goto copyStaticDict
	}

startCommand:
	// Read the insert and copy lengths according to RFC section 5.
	{
		if br.iacBlk.typeLen == 0 {
			br.readBlockSwitch(&br.iacBlk)
		}
		br.iacBlk.typeLen--

		iacTree := &br.iacBlk.prefixes[br.iacBlk.types[0]]
		iacSym, ok := br.rd.TryReadSymbol(iacTree)
		if !ok {
			iacSym = br.rd.ReadSymbol(iacTree)
		}
		rec := iacLUT[iacSym]
		insExtra, ok := br.rd.TryReadBits(uint(rec.ins.bits))
		if !ok {
			insExtra = br.rd.ReadBits(uint(rec.ins.bits))
		}
		cpyExtra, ok := br.rd.TryReadBits(uint(rec.cpy.bits))
		if !ok {
			cpyExtra = br.rd.ReadBits(uint(rec.cpy.bits))
		}
		br.insLen = int(rec.ins.base) + int(insExtra)
		br.cpyLen = int(rec.cpy.base) + int(cpyExtra)
		br.distZero = iacSym < 128
		if br.insLen > 0 {
			goto readLiterals
		}
		goto readDistance
	}

readLiterals:
	// Read literal symbols as uncompressed data according to RFC section 9.3.
	{
		buf := br.dict.WriteSlice()
		if len(buf) > br.insLen {
			buf = buf[:br.insLen]
		}

		p1, p2 := br.dict.LastBytes()
		for i := range buf {
			if br.litBlk.typeLen == 0 {
				br.readBlockSwitch(&br.litBlk)
				br.litMapType = br.litMap[64*int(br.litBlk.types[0]):]
				br.cmode = br.cmodes[br.litBlk.types[0]] // 0..3
			}
			br.litBlk.typeLen--

			litCID := getLitContextID(p1, p2, br.cmode) // 0..63
			litTree := &br.litBlk.prefixes[br.litMapType[litCID]]
			litSym, ok := br.rd.TryReadSymbol(litTree)
			if !ok {
				litSym = br.rd.ReadSymbol(litTree)
			}

			buf[i] = byte(litSym)
			p1, p2 = byte(litSym), p1
			br.dict.WriteMark(1)
		}
		br.insLen -= len(buf)
		br.blkLen -= len(buf)

		if br.insLen > 0 {
			br.toRead = br.dict.ReadFlush()
			br.step = (*Reader).readCommands
			br.stepState = stateLiterals // Need to continue work here
			return
		}
		if br.blkLen > 0 {
			goto readDistance
		}
		goto finishCommand
	}

readDistance:
	// Read and decode the distance length according to RFC section 9.3.
	{
		if br.distZero {
			br.dist = br.dists[0]
		} else {
			if br.distBlk.typeLen == 0 {
				br.readBlockSwitch(&br.distBlk)
				br.distMapType = br.distMap[4*int(br.distBlk.types[0]):]
			}
			br.distBlk.typeLen--

			distCID := getDistContextID(br.cpyLen) // 0..3
			distTree := &br.distBlk.prefixes[br.distMapType[distCID]]
			distSym, ok := br.rd.TryReadSymbol(distTree)
			if !ok {
				distSym = br.rd.ReadSymbol(distTree)
			}

			if distSym < 16 { // Short-code
				rec := distShortLUT[distSym]
				br.dist = br.dists[rec.index] + rec.delta
			} else if distSym < uint(16+br.ndirect) { // Direct-code
				br.dist = int(distSym - 15) // 1..ndirect
			} else { // Long-code
				rec := distLongLUT[br.npostfix][distSym-uint(16+br.ndirect)]
				extra, ok := br.rd.TryReadBits(uint(rec.bits))
				if !ok {
					extra = br.rd.ReadBits(uint(rec.bits))
				}
				br.dist = int(br.ndirect) + int(rec.base) + int(extra<<br.npostfix)
			}
			br.distZero = bool(distSym == 0)
			if br.dist <= 0 {
				errors.Panic(errCorrupted)
			}
		}

		if br.dist <= br.dict.HistSize() {
			if !br.distZero {
				br.dists[3] = br.dists[2]
				br.dists[2] = br.dists[1]
				br.dists[1] = br.dists[0]
				br.dists[0] = br.dist
			}
			goto copyDynamicDict
		}
		goto copyStaticDict
	}

copyDynamicDict:
	// Copy a string from the past uncompressed data according to RFC section 2.
	{
		cnt := br.dict.WriteCopy(br.dist, br.cpyLen)
		br.blkLen -= cnt
		br.cpyLen -= cnt

		if br.cpyLen > 0 {
			br.toRead = br.dict.ReadFlush()
			br.step = (*Reader).readCommands
			br.stepState = stateDynamicDict // Need to continue work here
			return
		}
		goto finishCommand
	}

copyStaticDict:
	// Copy a string from the static dictionary according to RFC section 8.
	{
		if len(br.word) == 0 {
			if br.cpyLen < minDictLen || br.cpyLen > maxDictLen {
				errors.Panic(errCorrupted)
			}
			wordIdx := br.dist - (br.dict.HistSize() + 1)
			index := wordIdx % dictSizes[br.cpyLen]
			offset := dictOffsets[br.cpyLen] + index*br.cpyLen
			baseWord := dictLUT[offset : offset+br.cpyLen]
			transformIdx := wordIdx >> uint(dictBitSizes[br.cpyLen])
			if transformIdx >= len(transformLUT) {
				errors.Panic(errCorrupted)
			}
			cnt := transformWord(br.wordBuf[:], baseWord, transformIdx)
			br.word = br.wordBuf[:cnt]
		}

		buf := br.dict.WriteSlice()
		cnt := copy(buf, br.word)
		br.word = br.word[cnt:]
		br.blkLen -= cnt
		br.dict.WriteMark(cnt)

		if len(br.word) > 0 {
			br.toRead = br.dict.ReadFlush()
			br.step = (*Reader).readCommands
			br.stepState = stateStaticDict // Need to continue work here
			return
		}
		goto finishCommand
	}

finishCommand:
	// Finish off this command and check if we need to loop again.
	if br.blkLen < 0 {
		errors.Panic(errCorrupted)
	}
	if br.blkLen > 0 {
		goto startCommand // More commands in this block
	}

	// Done with this block.
	br.toRead = br.dict.ReadFlush()
	br.step = (*Reader).readBlockHeader
	br.stepState = stateInit // Next call to readCommands must start here
}
1180140
func (c *Client) readRoutine() {
	c.disconnectEvent = DisconnectEvent{
		Client: c,
		Type:   DisconnectError,
	}

	for {
		pType, data, err := c.Conn.ReadPacket()
		if err != nil {
			break
		}
		if int(pType) < len(handlers) {
			handlers[pType](c, data)
		}
	}

	wasSynced := c.State() == StateSynced
	atomic.StoreUint32(&c.state, uint32(StateDisconnected))
	close(c.end)
	if wasSynced {
		c.Config.Listeners.onDisconnect(&c.disconnectEvent)
	}
}
86784
func (s *Skein) processBlock(bytes int) {
	s.cipher.SetKey(s.state)                 // state is the key
	s.ubiParameters.addBytesProcessed(bytes) // Update tweak
	s.cipher.SetTweak(s.ubiParameters.getTweak())

	s.cipher.Encrypt64(s.state, s.cipherInput)

	// Feed-forward input with state
	for i := 0; i < len(s.cipherInput); i++ {
		s.state[i] ^= s.cipherInput[i]
	}
}
1277547
func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error {
	return readElements(r, &bh.Version, &bh.PrevBlock, &bh.MerkleRoot,
		(*uint32Time)(&bh.Timestamp), &bh.Bits, &bh.Nonce)
}
751525
func (t *TSMReader) BlockIterator() *BlockIterator {
	t.mu.RLock()
	iter := t.index.Iterator(nil)
	t.mu.RUnlock()

	return &BlockIterator{
		r:    t,
		iter: iter,
	}
}
985818
func getSwitchesCmd(params *Parameters) *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "get-switches [-name <name>]... [-rack <rack>]... [-dc <datacenter>]...",
		ShortDesc: "retrieves switches",
		LongDesc:  "Retrieves switches matching the given names, racks and dcs, or all switches if names, racks, and dcs are omitted.\n\nExample to get all switches:\ncrimson get-switches\nExample to get the switch of rack xx1:\ncrimson get-switches -rack xx1",
		CommandRun: func() subcommands.CommandRun {
			cmd := &GetSwitchesCmd{}
			cmd.Initialize(params)
			cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a switch to filter by. Can be specified multiple times.")
			cmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), "rack", "Name of a rack to filter by. Can be specified multiple times.")
			cmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), "dc", "Name of a datacenter to filter by. Can be specified multiple times.")
			return cmd
		},
	}
}
889979
func NewBlockFromReader(r io.Reader) (*Block, error) {
	// Deserialize the bytes into a MsgBlock.
	var msgBlock wire.MsgBlock
	err := msgBlock.Deserialize(r)
	if err != nil {
		return nil, err
	}

	b := Block{
		msgBlock:    &msgBlock,
		blockHeight: BlockHeightUnknown,
	}
	return &b, nil
}
560402
func (s *Block) SetBlockType(v string) *Block {
	s.BlockType = &v
	return s
}
308678
func (k *KeyReadWriter) readKey() (*pem.Block, error) {
	keyBlock, err := k.readKeyblock()
	if err != nil {
		return nil, err
	}

	if !keyutils.IsEncryptedPEMBlock(keyBlock) {
		return keyBlock, nil
	}

	// If it's encrypted, we can't read without a passphrase (we're assuming
	// empty passphrases are invalid)
	if k.kekData.KEK == nil {
		return nil, ErrInvalidKEK{Wrapped: x509.IncorrectPasswordError}
	}

	derBytes, err := k.keyFormatter.DecryptPEMBlock(keyBlock, k.kekData.KEK)
	if err == keyutils.ErrFIPSUnsupportedKeyFormat {
		return nil, err
	} else if err != nil {
		return nil, ErrInvalidKEK{Wrapped: err}
	}

	// change header only if its pkcs8
	if keyBlock.Type == "ENCRYPTED PRIVATE KEY" {
		keyBlock.Type = "PRIVATE KEY"
	}

	// remove encryption PEM headers
	headers := make(map[string]string)
	mergePEMHeaders(headers, keyBlock.Headers)

	return &pem.Block{
		Type:    keyBlock.Type, // the key type doesn't change
		Bytes:   derBytes,
		Headers: headers,
	}, nil
}
1013487
func (st *State) SwitchBlockOn(t BlockType, msg string) error {
	return setModelBlock(st, t, msg)
}
26641
func (sc *SwitchConfig) ReadFrom(r io.Reader) (int64, error) {
	return encoding.ReadFrom(r, &sc.Flags, &sc.MissSendLength)
}
826219
func (c *ConfigLocal) SetBlockServer(b BlockServer) {
	c.lock.Lock()
	defer c.lock.Unlock()
	c.bserv = b
}
716466
func (b *BlockIterator) Read() (key []byte, minTime int64, maxTime int64, typ byte, checksum uint32, buf []byte, err error) {
	if err := b.iter.Err(); err != nil {
		return nil, 0, 0, 0, 0, nil, err
	}
	checksum, buf, err = b.r.ReadBytes(&b.entries[0], nil)
	if err != nil {
		return nil, 0, 0, 0, 0, nil, err
	}
	return b.iter.Key(), b.entries[0].MinTime, b.entries[0].MaxTime, b.iter.Type(), checksum, buf, err
}
144905
func (fbo *folderBlockOps) Read(
	ctx context.Context, lState *kbfssync.LockState, kmd libkey.KeyMetadata, file Node,
	dest []byte, off int64) (int64, error) {
	fbo.blockLock.RLock(lState)
	defer fbo.blockLock.RUnlock(lState)

	filePath := fbo.nodeCache.PathFromNode(file)

	fbo.vlog.CLogf(ctx, libkb.VLog1, "Reading from %v", filePath.TailPointer())

	var id keybase1.UserOrTeamID // Data reads don't depend on the id.
	fd := fbo.newFileData(lState, filePath, id, kmd)
	return fd.Read(ctx, dest, data.Int64Offset(off))
}