// NewFrame creates frame with given operation code,
// flag of completeness and payload bytes.
761004
func NewFrame(op OpCode, fin bool, p []byte) Frame {
	return Frame{
		Header: Header{
			Fin:    fin,
			OpCode: op,
			Length: int64(len(p)),
		},
		Payload: p,
	}
}
1263486
func CreateScrollFrame(x, y, w, h int, fg, bg termbox.Attribute) *ScrollFrame {
	c := ScrollFrame{
		x: x, y: y, width: w, height: h,
		fg: fg, bg: bg, activeFg: fg, activeBg: bg,
	}
	return &c
}
1107473
func Newf(cause error, format string, args ...interface{}) Error {
	return makeErrorf(UnknownErrorError, cause, format, args...)
}
1068797
func NewButtonBlockElement(actionID, value string, text *TextBlockObject) *ButtonBlockElement {
	return &ButtonBlockElement{
		Type:     metButton,
		ActionID: actionID,
		Text:     text,
		Value:    value,
	}
}
52326
func DecodeFrame(r io.Reader) (frame []byte, err error) {
	var size int16
	err = binary.Read(r, binary.LittleEndian, &size)
	if err != nil {
		return
	}

	if size < 0 {
		return nil, ErrNegativeFrameSize
	}

	frame = make([]byte, size)
	err = binary.Read(r, binary.LittleEndian, &frame)
	return
}
850647
func NewStackFrame(pc uintptr) (frame StackFrame) {

	frame = StackFrame{ProgramCounter: pc}
	if frame.Func() == nil {
		return
	}
	frame.Package, frame.Name = packageAndName(frame.Func())

	// pc -1 because the program counters we use are usually return addresses,
	// and we want to show the line that corresponds to the function call
	frame.File, frame.LineNumber = frame.Func().FileLine(pc - 1)
	return

}
213027
func (lengthDelimitedFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
	return framer.NewLengthDelimitedFrameReader(r)
}
469530
func (d *llvmSymbolizer) readFrame() (plugin.Frame, bool) {
	funcname, err := d.readString()
	if err != nil {
		return plugin.Frame{}, true
	}

	switch funcname {
	case "":
		return plugin.Frame{}, true
	case "??":
		funcname = ""
	}

	fileline, err := d.readString()
	if err != nil {
		return plugin.Frame{Func: funcname}, true
	}

	linenumber := 0
	if fileline == "??:0" {
		fileline = ""
	} else {
		switch split := strings.Split(fileline, ":"); len(split) {
		case 1:
			// filename
			fileline = split[0]
		case 2, 3:
			// filename:line , or
			// filename:line:disc , or
			fileline = split[0]
			if line, err := strconv.Atoi(split[1]); err == nil {
				linenumber = line
			}
		default:
			// Unrecognized, ignore
		}
	}

	return plugin.Frame{Func: funcname, File: fileline, Line: linenumber}, false
}
1357943
func NewBox(width, height int, flags int) *Box {
	width, height = GetXY(width, height)

	box := new(Box)
	box.Buf = new(bytes.Buffer)
	box.Width = width
	box.Height = height
	box.Border = DEFAULT_BORDER
	box.PaddingX = 1
	box.PaddingY = 0
	box.Flags = flags

	return box
}
609831
func NewFramework(r Registry, _ *runtime.Unknown) (Framework, error) {
	f := &framework{
		registry:         r,
		nodeInfoSnapshot: cache.NewNodeInfoSnapshot(),
		plugins:          make(map[string]Plugin),
	}

	// TODO: The framework needs to read the scheduler config and initialize only
	// needed plugins. In this initial version of the code, we initialize all.
	for name, factory := range r {
		// TODO: 'nil' should be replaced by plugin config.
		p, err := factory(nil, f)
		if err != nil {
			return nil, fmt.Errorf("error initializing plugin %v: %v", name, err)
		}
		f.plugins[name] = p

		// TODO: For now, we assume any plugins that implements an extension
		// point wants to be called at that extension point. We should change this
		// later and add these plugins based on the configuration.
		if rp, ok := p.(ReservePlugin); ok {
			f.reservePlugins = append(f.reservePlugins, rp)
		}
		if pp, ok := p.(PrebindPlugin); ok {
			f.prebindPlugins = append(f.prebindPlugins, pp)
		}
	}
	return f, nil
}
1084013
func CreateFrame(x, y, w, h int, fg, bg termbox.Attribute) *Frame {
	c := Frame{x: x, y: y, width: w, height: h,
		fg: fg, bg: bg, activeFg: fg, activeBg: bg,
		bordered: true,
	}
	return &c
}
757887
func UnsnapOneFrame(r io.Reader, encBuf *FixedSizeRingBuf, outDecodedBuf *FixedSizeRingBuf, fname string) (nEnc int64, nDec int64, err error) {
	//	b, err := ioutil.ReadAll(r)
	//	if err != nil {
	//		panic(err)
	//	}

	nEnc = 0
	nDec = 0

	// read up to 65536 bytes from r into encBuf, at least a snappy frame
	nread, err := io.CopyN(encBuf, r, 65536) // returns nwrotebytes, err
	nEnc += nread
	if err != nil {
		if err == io.EOF {
			if nread == 0 {
				if encBuf.Readable == 0 {
					return nEnc, nDec, io.EOF
				}
				// else we have bytes in encBuf, so decode them!
				err = nil
			} else {
				// continue below, processing the nread bytes
				err = nil
			}
		} else {
			panic(err)
		}
	}

	// flag for printing chunk size alignment messages
	verbose := false

	const snappyStreamHeaderSz = 10
	const headerSz = 4
	const crc32Sz = 4
	// the magic 18 bytes accounts for the snappy streaming header and the first chunks size and checksum
	// http://code.google.com/p/snappy/source/browse/trunk/framing_format.txt

	chunk := (*encBuf).Bytes()

	// however we exit, advance as
	//	defer func() { (*encBuf).Next(N) }()

	// 65536 is the max size of a snappy framed chunk. See
	// http://code.google.com/p/snappy/source/browse/trunk/framing_format.txt:91
	// buf := make([]byte, 65536)

	//	fmt.Printf("read from file, b is len:%d with value: %#v\n", len(b), b)
	//	fmt.Printf("read from file, bcut is len:%d with value: %#v\n", len(bcut), bcut)

	//fmt.Printf("raw bytes of chunksz are: %v\n", b[11:14])

	fourbytes := make([]byte, 4)
	chunkCount := 0

	for nDec < 65536 {
		if len(chunk) == 0 {
			break
		}
		chunkCount++
		fourbytes[3] = 0
		copy(fourbytes, chunk[1:4])
		chunksz := binary.LittleEndian.Uint32(fourbytes)
		chunk_type := chunk[0]

		switch true {
		case chunk_type == 0xff:
			{ // stream identifier

				streamHeader := chunk[:snappyStreamHeaderSz]
				if 0 != bytes.Compare(streamHeader, []byte{0xff, 0x06, 0x00, 0x00, 0x73, 0x4e, 0x61, 0x50, 0x70, 0x59}) {
					panic("file had chunk starting with 0xff but then no magic snappy streaming protocol bytes, aborting.")
				} else {
					//fmt.Printf("got streaming snappy magic header just fine.\n")
				}
				chunk = chunk[snappyStreamHeaderSz:]
				(*encBuf).Advance(snappyStreamHeaderSz)
				nEnc += snappyStreamHeaderSz
				continue
			}
		case chunk_type == 0x00:
			{ // compressed data
				if verbose {
					fmt.Fprintf(os.Stderr, "chunksz is %d  while  total bytes avail are: %d\n", int(chunksz), len(chunk)-4)
				}

				crc := binary.LittleEndian.Uint32(chunk[headerSz:(headerSz + crc32Sz)])
				section := chunk[(headerSz + crc32Sz):(headerSz + chunksz)]

				dec, ok := snappy.Decode(nil, section)
				if ok != nil {
					// we've probably truncated a snappy frame at this point
					// ok=snappy: corrupt input
					// len(dec) == 0
					//
					panic(fmt.Sprintf("could not decode snappy stream: '%s' and len dec=%d and ok=%v\n", fname, len(dec), ok))

					// get back to caller with what we've got so far
					return nEnc, nDec, nil
				}
				//	fmt.Printf("ok, b is %#v , %#v\n", ok, dec)

				// spit out decoded text
				// n, err := w.Write(dec)
				//fmt.Printf("len(dec) = %d,   outDecodedBuf.Readable=%d\n", len(dec), outDecodedBuf.Readable)
				bnb := bytes.NewBuffer(dec)
				n, err := io.Copy(outDecodedBuf, bnb)
				if err != nil {
					//fmt.Printf("got n=%d, err= %s ; when trying to io.Copy(outDecodedBuf: N=%d, Readable=%d)\n", n, err, outDecodedBuf.N, outDecodedBuf.Readable)
					panic(err)
				}
				if n != int64(len(dec)) {
					panic("could not write all bytes to outDecodedBuf")
				}
				nDec += n

				// verify the crc32 rotated checksum
				m32 := masked_crc32c(dec)
				if m32 != crc {
					panic(fmt.Sprintf("crc32 masked failiure. expected: %v but got: %v", crc, m32))
				} else {
					//fmt.Printf("\nchecksums match: %v == %v\n", crc, m32)
				}

				// move to next header
				inc := (headerSz + int(chunksz))
				chunk = chunk[inc:]
				(*encBuf).Advance(inc)
				nEnc += int64(inc)
				continue
			}
		case chunk_type == 0x01:
			{ // uncompressed data

				//n, err := w.Write(chunk[(headerSz+crc32Sz):(headerSz + int(chunksz))])
				n, err := io.Copy(outDecodedBuf, bytes.NewBuffer(chunk[(headerSz+crc32Sz):(headerSz+int(chunksz))]))
				if verbose {
					//fmt.Printf("debug: n=%d  err=%v  chunksz=%d  outDecodedBuf='%v'\n", n, err, chunksz, outDecodedBuf)
				}
				if err != nil {
					panic(err)
				}
				if n != int64(chunksz-crc32Sz) {
					panic("could not write all bytes to stdout")
				}
				nDec += n

				inc := (headerSz + int(chunksz))
				chunk = chunk[inc:]
				(*encBuf).Advance(inc)
				nEnc += int64(inc)
				continue
			}
		case chunk_type == 0xfe:
			fallthrough // padding, just skip it
		case chunk_type >= 0x80 && chunk_type <= 0xfd:
			{ //  Reserved skippable chunks
				//fmt.Printf("\nin reserved skippable chunks, at nEnc=%v\n", nEnc)
				inc := (headerSz + int(chunksz))
				chunk = chunk[inc:]
				nEnc += int64(inc)
				(*encBuf).Advance(inc)
				continue
			}

		default:
			panic(fmt.Sprintf("unrecognized/unsupported chunk type %#v", chunk_type))
		}

	} // end for{}

	return nEnc, nDec, err
	//return int64(N), nil
}
972598
func (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
	// we need to extract the JSON chunks of data to pass to Decode()
	return framer.NewJSONFramedReader(r)
}
1068632
func (e *Encoder) WriteFrame(value interface{}) error {
	if !e.wroteHeader {
		e.writeHeader()
	}
	if !e.pcmChunkStarted {
		// sound header
		if err := e.AddLE(riff.DataFormatID); err != nil {
			return fmt.Errorf("error encoding sound header %v", err)
		}
		e.pcmChunkStarted = true

		// write a temporary chunksize
		e.pcmChunkSizePos = e.WrittenBytes
		if err := e.AddLE(uint32(42)); err != nil {
			return fmt.Errorf("%v when writing wav data chunk size header", err)
		}
	}

	e.frames++
	return e.AddLE(value)
}
683733
func (err *Error) StackFrames() []StackFrame {
	if err.frames == nil {
		err.frames = make([]StackFrame, len(err.stack))

		for i, pc := range err.stack {
			err.frames[i] = NewStackFrame(pc)
		}
	}

	return err.frames
}
378149
func topframe(g *G, thread Thread) (Stackframe, Stackframe, error) {
	var frames []Stackframe
	var err error

	if g == nil {
		if thread.Blocked() {
			return Stackframe{}, Stackframe{}, ErrThreadBlocked{}
		}
		frames, err = ThreadStacktrace(thread, 1)
	} else {
		frames, err = g.Stacktrace(1, true)
	}
	if err != nil {
		return Stackframe{}, Stackframe{}, err
	}
	switch len(frames) {
	case 0:
		return Stackframe{}, Stackframe{}, errors.New("empty stack trace")
	case 1:
		return frames[0], Stackframe{}, nil
	default:
		return frames[0], frames[1], nil
	}
}
510404
func (f *framer) readFrame(head *frameHeader) error {
	if head.length < 0 {
		return fmt.Errorf("frame body length can not be less than 0: %d", head.length)
	} else if head.length > maxFrameSize {
		// need to free up the connection to be used again
		_, err := io.CopyN(ioutil.Discard, f.r, int64(head.length))
		if err != nil {
			return fmt.Errorf("error whilst trying to discard frame with invalid length: %v", err)
		}
		return ErrFrameTooBig
	}

	if cap(f.readBuffer) >= head.length {
		f.rbuf = f.readBuffer[:head.length]
	} else {
		f.readBuffer = make([]byte, head.length)
		f.rbuf = f.readBuffer
	}

	// assume the underlying reader takes care of timeouts and retries
	n, err := io.ReadFull(f.r, f.rbuf)
	if err != nil {
		return fmt.Errorf("unable to read frame body: read %d/%d bytes: %v", n, head.length, err)
	}

	if head.flags&flagCompress == flagCompress {
		if f.compres == nil {
			return NewErrProtocol("no compressor available with compressed frame body")
		}

		f.rbuf, err = f.compres.Decode(f.rbuf)
		if err != nil {
			return err
		}
	}

	f.header = head
	return nil
}