// FwdToPCM forwards the underlying reader until the start of the PCM chunk.
// If the PCM chunk was already read, no data will be found (you need to rewind).
17304
func (d *Decoder) FwdToPCM() error {
	if d.err = d.readHeaders(); d.err != nil {
		d.err = fmt.Errorf("failed to read header - %v", d.err)
		return nil
	}

	// read the file information to setup the audio clip
	// find the beginning of the SSND chunk and set the clip reader to it.
	var rewindBytes int64

	var chunk *Chunk
	for d.err == nil {
		chunk, d.err = d.NextChunk()
		if d.err != nil {
			return d.err
		}
		switch chunk.ID {
		case COMMID:
			if err := d.parseCommChunk(uint32(chunk.Size)); err != nil {
				return err
			}
			// if we found the sound data before the COMM,
			// we need to rewind the reader so we can properly
			// set the clip reader.
			if rewindBytes > 0 {
				d.r.Seek(-rewindBytes, 1)
			}
		case SSNDID:
			//            SSND chunk: Must be defined
			//   0      4 bytes  "SSND"
			//   4      4 bytes  <Chunk size(x)>
			//   8      4 bytes  <Offset(n)>
			//  12      4 bytes  <block size>
			//  16     (n)bytes  Comment
			//  16+(n) (s)bytes  <Sample data>

			var offset uint32
			if d.err = chunk.ReadBE(&offset); d.err != nil {
				d.err = fmt.Errorf("PCM offset failed to parse - %s", d.err)
				return d.err
			}

			if d.err = chunk.ReadBE(&d.PCMSize); d.err != nil {
				d.err = fmt.Errorf("PCMSize failed to parse - %s", d.err)
				return d.err
			}
			if offset > 0 {
				d.PCMSize -= offset
				// skip pcm comment
				buf := make([]byte, offset)
				if err := chunk.ReadBE(&buf); err != nil {
					return err
				}
			}
			d.PCMChunk = chunk
			d.pcmDataAccessed = true
			return nil

		default:
			// if we read SSN but didn't read the COMM, we need to track location
			if d.SampleRate == 0 {
				rewindBytes += int64(chunk.Size)
			}
			chunk.Done()
		}
	}
	return nil
}
390152
func (s *SkipList) SeekToFirst() Iterator {
	if s.length == 0 {
		return nil
	}

	current := s.header.next()

	return &iter{
		current: current,
		key:     current.key,
		list:    s,
		value:   current.value,
	}
}
181670
func (surface *Surface) WriteToPNG(w io.Writer) error {
	data := writeClosure{w: w}
	key := goPointers.put(data)
	status := C.cairo_surface_write_to_png_stream((*C.cairo_surface_t)(surface.Ptr),
		(C.cairo_write_func_t)(unsafe.Pointer(C.gocairo_write_func)),
		unsafe.Pointer(&key))
	goPointers.clear(key)
	// TODO: which should we prefer between writeClosure.err and status?
	// Perhaps test against CAIRO_STATUS_WRITE_ERROR?  Needs a test case.
	return Status(status).toError()
}
177669
func (f *segmentTermsEnumFrame) scanToTermLeaf(target []byte, exactOnly bool) (status SeekStatus, err error) {
	// fmt.Printf("    scanToTermLeaf: block fp=%v prefix=%v nextEnt=%v (of %v) target=%v term=%v\n",
	// 	f.fp, f.prefix, f.nextEnt, f.entCount, brToString(target), f.ste.term)
	assert(f.nextEnt != -1)

	f.ste.termExists = true
	f.subCode = 0
	if f.nextEnt == f.entCount {
		if exactOnly {
			f.fillTerm()
		}
		return SEEK_STATUS_END, nil
	}

	if !f.prefixMatches(target) {
		panic("assert fail")
	}

	// Loop over each entry (term or sub-block) in this block:
	//nextTerm: while(nextEnt < entCount) {
	for {
		f.nextEnt++
		f.suffix, err = asInt(f.suffixesReader.ReadVInt())
		if err != nil {
			return 0, err
		}

		// suffixReaderPos := f.suffixesReader.Pos
		// fmt.Printf("      cycle: term %v (of %v) suffix=%v\n",
		// 	f.nextEnt-1, f.entCount, brToString(f.suffixBytes[suffixReaderPos:suffixReaderPos+f.suffix]))

		termLen := f.prefix + f.suffix
		f.startBytePos = f.suffixesReader.Pos
		f.suffixesReader.SkipBytes(int64(f.suffix))

		targetLimit := termLen
		if len(target) < termLen {
			targetLimit = len(target)
		}
		targetPos := f.prefix

		// Loop over bytes in the suffix, comparing to
		// the target
		bytePos := f.startBytePos
		isDone := false
		for {
			var cmp int
			var stop bool
			if targetPos < targetLimit {
				cmp = int(f.suffixBytes[bytePos]) - int(target[targetPos])
				bytePos++
				targetPos++
				stop = false
			} else {
				if targetPos != targetLimit {
					panic("assert fail")
				}
				cmp = termLen - len(target)
				stop = true
			}

			if cmp < 0 {
				// Current entry is still before the target;
				// keep scanning

				if f.nextEnt == f.entCount {
					if exactOnly {
						f.fillTerm()
					}
					// We are done scanning this block
					isDone = true
				}
				break
			} else if cmp > 0 {
				// // Done!  Current entry is after target --
				//     // return NOT_FOUND:
				f.fillTerm()

				// fmt.Println("        not found")
				return SEEK_STATUS_NOT_FOUND, nil
			} else if stop {
				// Exact match!

				// This cannot be a sub-block because we
				// would have followed the index to this
				// sub-block from the start:

				assert(f.ste.termExists)
				f.fillTerm()
				// fmt.Println("        found!")
				return SEEK_STATUS_FOUND, nil
			}
		}
		if isDone {
			// double jump
			break
		}
	}

	// It is possible (and OK) that terms index pointed us
	// at this block, but, we scanned the entire block and
	// did not find the term to position to.  This happens
	// when the target is after the last term in the block
	// (but, before the next term in the index).  EG
	// target could be foozzz, and terms index pointed us
	// to the foo* block, but the last term in this block
	// was fooz (and, eg, first term in the next block will
	// bee fop).
	fmt.Println("      block end")
	if exactOnly {
		f.fillTerm()
	}

	// TODO: not consistent that in the
	// not-exact case we don't next() into the next
	// frame here
	return SEEK_STATUS_END, nil
}
1317588
func (r *Reader) NextPart() (*Part, error) {
	wrap, err := r.r.NextPart()
	if err != nil {
		return nil, err
	}
	p := &Part{
		Header: wrap.Header,
		Root:   false,
	}

	contentId := parseContentId(p.Header.Get("Content-Id"))
	if r.start != "" && r.start == contentId {
		if r.rootRead {
			return nil, ErrDupRoot
		} else {
			p.Root = true
			r.rootRead = true
		}
	} else if !r.rootRead && r.start == "" {
		p.Root = true
		r.rootRead = true
	}
	p.r = wrap

	switch strings.ToLower(p.Header.Get("Content-Transfer-Encoding")) {
	case "base64":
		p.Header.Del("Content-Transfer-Encoding")
		p.r = base64.NewDecoder(base64.StdEncoding, p.r)
		break
		// TODO binary reader
	}
	// TODO SkipMatch

	return p, nil
}
340957
func (o *IntOptions) getFmtOpt(name string) string {
	define := o.Library.Define(name)
	if define == "" {
		return ""
	}

	value := o.getValue(name)
	if value != OptionDisabled {
		return fmt.Sprintf("#define %s %d", o.Library.Define(name), value)
	}
	return "#undef " + o.Library.Define(name)
}
695695
func destinationTerm(cinfo *C.struct_jpeg_compress_struct) {
	// just empty buffer
	mgr := getDestinationManager(cinfo)
	inBuffer := int(writeBufferSize - mgr.pub.free_in_buffer)
	flushBuffer(mgr, inBuffer)
}
877636
func (l *icmpPacketList) PushFront(e *icmpPacket) {
	icmpPacketElementMapper{}.linkerFor(e).SetNext(l.head)
	icmpPacketElementMapper{}.linkerFor(e).SetPrev(nil)

	if l.head != nil {
		icmpPacketElementMapper{}.linkerFor(l.head).SetPrev(e)
	} else {
		l.tail = e
	}

	l.head = e
}
572637
func (c *Client) SendFromAsync(fromAccount string, toAddress btcutil.Address, amount btcutil.Amount) FutureSendFromResult {
	addr := toAddress.EncodeAddress()
	cmd := btcjson.NewSendFromCmd(fromAccount, addr, amount.ToBTC(), nil,
		nil, nil)
	return c.sendCmd(cmd)
}
119931
func (i *FSTIterator) pointTo(key []byte) error {
	// tried to seek before start
	if bytes.Compare(key, i.startKeyInclusive) < 0 {
		key = i.startKeyInclusive
	}

	// tried to see past end
	if i.endKeyExclusive != nil &&
		bytes.Compare(key, i.endKeyExclusive) > 0 {
		key = i.endKeyExclusive
	}

	// reset any state, pointTo always starts over
	i.statesStack = i.statesStack[:0]
	i.keysStack = i.keysStack[:0]
	i.keysPosStack = i.keysPosStack[:0]
	i.valsStack = i.valsStack[:0]
	i.autStatesStack = i.autStatesStack[:0]

	root, err := i.f.decoder.stateAt(i.f.decoder.getRoot(), nil)
	if err != nil {
		return err
	}

	autStart := i.aut.Start()

	maxQ := -1
	// root is always part of the path
	i.statesStack = append(i.statesStack, root)
	i.autStatesStack = append(i.autStatesStack, autStart)
	for j := 0; j < len(key); j++ {
		keyJ := key[j]
		curr := i.statesStack[len(i.statesStack)-1]
		autCurr := i.autStatesStack[len(i.autStatesStack)-1]

		pos, nextAddr, nextVal := curr.TransitionFor(keyJ)
		if nextAddr == noneAddr {
			// needed transition doesn't exist
			// find last trans before the one we needed
			for q := curr.NumTransitions() - 1; q >= 0; q-- {
				if curr.TransitionAt(q) < keyJ {
					maxQ = q
					break
				}
			}
			break
		}
		autNext := i.aut.Accept(autCurr, keyJ)

		next, err := i.f.decoder.stateAt(nextAddr, nil)
		if err != nil {
			return err
		}

		i.statesStack = append(i.statesStack, next)
		i.keysStack = append(i.keysStack, keyJ)
		i.keysPosStack = append(i.keysPosStack, pos)
		i.valsStack = append(i.valsStack, nextVal)
		i.autStatesStack = append(i.autStatesStack, autNext)
		continue
	}

	if !i.statesStack[len(i.statesStack)-1].Final() ||
		!i.aut.IsMatch(i.autStatesStack[len(i.autStatesStack)-1]) ||
		bytes.Compare(i.keysStack, key) < 0 {
		return i.next(maxQ)
	}

	return nil
}
784456
func DecodeExpfmt(r io.Reader, format expfmt.Format) ([]*dto.MetricFamily, error) {
	dec := expfmt.NewDecoder(r, format)
	mfs := []*dto.MetricFamily{}
	for {
		var mf dto.MetricFamily
		if err := dec.Decode(&mf); err != nil {
			if err == io.EOF {
				break
			}
			if err != nil {
				return nil, err
			}
		}
		mfs = append(mfs, &mf)
	}
	return mfs, nil
}
162544
func (p PrefetchProgress) ToProtocolProgress(clock Clock) (
	out keybase1.PrefetchProgress) {
	out.BytesFetched = int64(p.SubtreeBytesFetched)
	out.BytesTotal = int64(p.SubtreeBytesTotal)
	out.Start = keybase1.ToTime(p.Start)

	if out.BytesTotal == 0 || out.Start == 0 {
		return out
	}

	timeRunning := clock.Now().Sub(p.Start)
	fracDone := float64(out.BytesFetched) / float64(out.BytesTotal)
	totalTimeEstimate := time.Duration(float64(timeRunning) / fracDone)
	endEstimate := p.Start.Add(totalTimeEstimate)
	out.EndEstimate = keybase1.ToTime(endEstimate)
	return out
}
29500
func Tcflush(fd, which uintptr) error {
	var com int
	switch which {
	case syscall.TCIFLUSH:
		com = FREAD
	case syscall.TCOFLUSH:
		com = FWRITE
	case syscall.TCIOFLUSH:
		com = FREAD | FWRITE
	default:
		return syscall.EINVAL
	}
	return ioctl(fd, syscall.TIOCFLUSH, uintptr(unsafe.Pointer(&com)))
}
1144004
func (m *Meter) StartTransfer(name string) {
	if m == nil {
		return
	}

	defer m.update(false)
	idx := atomic.AddInt64(&m.transferringFiles, 1)
	m.fileIndexMutex.Lock()
	m.fileIndex[name] = idx
	m.fileIndexMutex.Unlock()
}
187120
func (t *TTFParser) ParseHmtx(fd *bytes.Reader) error {

	t.Seek(fd, "hmtx")
	i := uint(0)
	for i < t.numberOfHMetrics {
		advanceWidth, err := t.ReadUShort(fd)
		if err != nil {
			return err
		}
		err = t.Skip(fd, 2)
		if err != nil {
			return err
		}
		t.widths = append(t.widths, advanceWidth)
		i++
	}
	if t.numberOfHMetrics < t.numGlyphs {
		var err error
		lastWidth := t.widths[t.numberOfHMetrics-1]
		t.widths, err = t.ArrayPadUint(t.widths, t.numGlyphs, lastWidth)
		if err != nil {
			return err
		}
	}

	return nil
}
756759
func (c *SessionClient) FileSink(fp, fn string) {
	// We must close the channel for the main thread to work properly. Defer ensures
	// when the function ends, this is closed. We also want to be sure we mark this
	// attempt as completed
	defer close(c.errors)
	defer c.wg.Done()

	logrus.Debugln("Beginning transfer")
	successfulByte := []byte{0}
	// Send a null byte saying that we are ready to receive the data
	c.writer.Write(successfulByte)

	// We want to first receive the command input from remote machine
	// e.g. C0644 113828 test.csv
	scpCommandArray := make([]byte, 500)
	bytesRead, err := c.reader.Read(scpCommandArray)
	if err != nil {
		if err == io.EOF {
			//no problem.
		} else {
			c.errors <- err
			return
		}
	}

	scpStartLine := string(scpCommandArray[:bytesRead])
	scpStartLineArray := strings.Split(scpStartLine, " ")

	filePermission := scpStartLineArray[0][1:]
	fileSize := scpStartLineArray[1]
	fileName := scpStartLineArray[2]

	logrus.Debugf("File with permissions: %s, File Size: %s, File Name: %s", filePermission, fileSize, fileName)

	// Confirm to the remote host that we have received the command line
	c.writer.Write(successfulByte)

	// Now we want to start receiving the file itself from the remote machine
	// one byte at a time
	fileContents := make([]byte, 1)

	var file *os.File
	if fn == "" {
		file, err = scpFile.Create(fmt.Sprintf("%s/%s", fp, fn))
		if err != nil {
			c.errors <- err
			return
		}
	} else {
		file, err = scpFile.Create(fmt.Sprintf("%s/%s", fp, fn))
		if err != nil {
			c.errors <- err
			return
		}
	}

	more := true
	for more {
		bytesRead, err = c.reader.Read(fileContents)
		if err != nil {
			if err == io.EOF {
				more = false
			} else {
				c.errors <- err
				return
			}
		}
		_, err = scpFile.WriteBytes(file, fileContents[:bytesRead])
		if err != nil {
			c.errors <- err
			return
		}
		c.writer.Write(successfulByte)
	}
	err = file.Sync()
	if err != nil {
		c.errors <- err
		return
	}
}
429902
func (p *Port) ReadFrom(r io.Reader) (int64, error) {
	p.HWAddr = make(net.HardwareAddr, 6)
	var name [portNameLen]byte

	n, err := encoding.ReadFrom(r, &p.PortNo, &defaultPad4, &p.HWAddr,
		&defaultPad2, &name, &p.Config, &p.State, &p.Curr, &p.Advertised,
		&p.Supported, &p.Peer, &p.CurrSpeed, &p.MaxSpeed,
	)

	p.Name = string(name[:])
	return n, err
}