Copyright 2014 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

package http2

import (
	
	
	
	
	
	
	
	

	
	
)

const frameHeaderLen = 9

var padZeros = make([]byte, 255) // zeros for padding
A FrameType is a registered frame type as defined in http://http2.github.io/http2-spec/#rfc.section.11.2
type FrameType uint8

const (
	FrameData         FrameType = 0x0
	FrameHeaders      FrameType = 0x1
	FramePriority     FrameType = 0x2
	FrameRSTStream    FrameType = 0x3
	FrameSettings     FrameType = 0x4
	FramePushPromise  FrameType = 0x5
	FramePing         FrameType = 0x6
	FrameGoAway       FrameType = 0x7
	FrameWindowUpdate FrameType = 0x8
	FrameContinuation FrameType = 0x9
)

var frameName = map[FrameType]string{
	FrameData:         "DATA",
	FrameHeaders:      "HEADERS",
	FramePriority:     "PRIORITY",
	FrameRSTStream:    "RST_STREAM",
	FrameSettings:     "SETTINGS",
	FramePushPromise:  "PUSH_PROMISE",
	FramePing:         "PING",
	FrameGoAway:       "GOAWAY",
	FrameWindowUpdate: "WINDOW_UPDATE",
	FrameContinuation: "CONTINUATION",
}

func ( FrameType) () string {
	if ,  := frameName[];  {
		return 
	}
	return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8())
}
Flags is a bitmask of HTTP/2 flags. The meaning of flags varies depending on the frame type.
type Flags uint8
Has reports whether f contains all (0 or more) flags in v.
func ( Flags) ( Flags) bool {
	return ( & ) == 
}
Frame-specific FrameHeader flag bits.
Data Frame
Settings Frame
Ping Frame
A FrameHeader is the 9 byte header of all HTTP/2 frames. See http://http2.github.io/http2-spec/#FrameHeader
type FrameHeader struct {
	valid bool // caller can access []byte fields in the Frame
Type is the 1 byte frame type. There are ten standard frame types, but extension frame types may be written by WriteRawFrame and will be returned by ReadFrame (as UnknownFrame).
Flags are the 1 byte of 8 potential bit flags per frame. They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header. The maximum size is one byte less than 16MB (uint24), but only frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames are not stream-specific, in which case this field is 0.
Header returns h. It exists so FrameHeaders can be embedded in other specific frame types and implement the Frame interface.
func ( FrameHeader) () FrameHeader { return  }

func ( FrameHeader) () string {
	var  bytes.Buffer
	.WriteString("[FrameHeader ")
	.writeDebug(&)
	.WriteByte(']')
	return .String()
}

func ( FrameHeader) ( *bytes.Buffer) {
	.WriteString(.Type.String())
	if .Flags != 0 {
		.WriteString(" flags=")
		 := 0
		for  := uint8(0);  < 8; ++ {
			if .Flags&(1<<) == 0 {
				continue
			}
			++
			if  > 1 {
				.WriteByte('|')
			}
			 := flagName[.Type][Flags(1<<)]
			if  != "" {
				.WriteString()
			} else {
				fmt.Fprintf(, "0x%x", 1<<)
			}
		}
	}
	if .StreamID != 0 {
		fmt.Fprintf(, " stream=%d", .StreamID)
	}
	fmt.Fprintf(, " len=%d", .Length)
}

func ( *FrameHeader) () {
	if !.valid {
		panic("Frame accessor called on non-owned Frame")
	}
}

func ( *FrameHeader) () { .valid = false }
frame header bytes. Used only by ReadFrameHeader.
var fhBytes = sync.Pool{
	New: func() interface{} {
		 := make([]byte, frameHeaderLen)
		return &
	},
}
ReadFrameHeader reads 9 bytes from r and returns a FrameHeader. Most users should use Framer.ReadFrame instead.
func ( io.Reader) (FrameHeader, error) {
	 := fhBytes.Get().(*[]byte)
	defer fhBytes.Put()
	return readFrameHeader(*, )
}

func ( []byte,  io.Reader) (FrameHeader, error) {
	,  := io.ReadFull(, [:frameHeaderLen])
	if  != nil {
		return FrameHeader{}, 
	}
	return FrameHeader{
		Length:   (uint32([0])<<16 | uint32([1])<<8 | uint32([2])),
		Type:     FrameType([3]),
		Flags:    Flags([4]),
		StreamID: binary.BigEndian.Uint32([5:]) & (1<<31 - 1),
		valid:    true,
	}, nil
}
A Frame is the base interface implemented by all frame types. Callers will generally type-assert the specific frame type: *HeadersFrame, *SettingsFrame, *WindowUpdateFrame, etc. Frames are only valid until the next call to Framer.ReadFrame.
type Frame interface {
	Header() FrameHeader
invalidate is called by Framer.ReadFrame to make this frame's buffers as being invalid, since the subsequent frame will reuse them.
	invalidate()
}
A Framer reads and writes Frames.
lastHeaderStream is non-zero if the last frame was an unfinished HEADERS/CONTINUATION.
TODO: let getReadBuf be configurable, and use a less memory-pinning allocator in server.go to minimize memory pinned for many idle conns. Will probably also need to make frame invalidation have a hook too.
	getReadBuf func(size uint32) []byte
	readBuf    []byte // cache for default getReadBuf

	maxWriteSize uint32 // zero means unlimited; TODO: implement

	w    io.Writer
	wbuf []byte
AllowIllegalWrites permits the Framer's Write methods to write frames that do not conform to the HTTP/2 spec. This permits using the Framer to test other HTTP/2 implementations' conformance to the spec. If false, the Write methods will prefer to return an error rather than comply.
AllowIllegalReads permits the Framer's ReadFrame method to return non-compliant frames or frame orders. This is for testing and permits using the Framer to test other HTTP/2 implementations' conformance to the spec. It is not compatible with ReadMetaHeaders.
ReadMetaHeaders if non-nil causes ReadFrame to merge HEADERS and CONTINUATION frames together and return MetaHeadersFrame instead.
MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE. It's used only if ReadMetaHeaders is set; 0 means a sane default (currently 16MB) If the limit is hit, MetaHeadersFrame.Truncated is set true.
TODO: track which type of frame & with which flags was sent last. Then return an error (unless AllowIllegalWrites) if we're in the middle of a header block and a non-Continuation or Continuation on a different stream is attempted to be written.

	logReads, logWrites bool

	debugFramer       *Framer // only use for logging written writes
	debugFramerBuf    *bytes.Buffer
	debugReadLoggerf  func(string, ...interface{})
	debugWriteLoggerf func(string, ...interface{})

	frameCache *frameCache // nil if frames aren't reused (default)
}

func ( *Framer) () uint32 {
	if .MaxHeaderListSize == 0 {
		return 16 << 20 // sane default, per docs
	}
	return .MaxHeaderListSize
}

Write the FrameHeader.
	.wbuf = append(.wbuf[:0],
		0, // 3 bytes of length, filled in in endWrite
		0,
		0,
		byte(),
		byte(),
		byte(>>24),
		byte(>>16),
		byte(>>8),
		byte())
}

Now that we know the final size, fill in the FrameHeader in the space previously reserved for it. Abuse append.
	 := len(.wbuf) - frameHeaderLen
	if  >= (1 << 24) {
		return ErrFrameTooLarge
	}
	_ = append(.wbuf[:0],
		byte(>>16),
		byte(>>8),
		byte())
	if .logWrites {
		.logWrite()
	}

	,  := .w.Write(.wbuf)
	if  == nil &&  != len(.wbuf) {
		 = io.ErrShortWrite
	}
	return 
}

func ( *Framer) () {
	if .debugFramer == nil {
		.debugFramerBuf = new(bytes.Buffer)
		.debugFramer = NewFramer(nil, .debugFramerBuf)
Let us read anything, even if we accidentally wrote it in the wrong order:
		.debugFramer.AllowIllegalReads = true
	}
	.debugFramerBuf.Write(.wbuf)
	,  := .debugFramer.ReadFrame()
	if  != nil {
		.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", )
		return
	}
	.debugWriteLoggerf("http2: Framer %p: wrote %v", , summarizeFrame())
}

func ( *Framer) ( byte)     { .wbuf = append(.wbuf, ) }
func ( *Framer) ( []byte)  { .wbuf = append(.wbuf, ...) }
func ( *Framer) ( uint16) { .wbuf = append(.wbuf, byte(>>8), byte()) }
func ( *Framer) ( uint32) {
	.wbuf = append(.wbuf, byte(>>24), byte(>>16), byte(>>8), byte())
}

const (
	minMaxFrameSize = 1 << 14
	maxFrameSize    = 1<<24 - 1
)
SetReuseFrames allows the Framer to reuse Frames. If called on a Framer, Frames returned by calls to ReadFrame are only valid until the next call to ReadFrame.
func ( *Framer) () {
	if .frameCache != nil {
		return
	}
	.frameCache = &frameCache{}
}

type frameCache struct {
	dataFrame DataFrame
}

func ( *frameCache) () *DataFrame {
	if  == nil {
		return &DataFrame{}
	}
	return &.dataFrame
}
NewFramer returns a Framer that writes frames to w and reads them from r.
func ( io.Writer,  io.Reader) *Framer {
	 := &Framer{
		w:                 ,
		r:                 ,
		logReads:          logFrameReads,
		logWrites:         logFrameWrites,
		debugReadLoggerf:  log.Printf,
		debugWriteLoggerf: log.Printf,
	}
	.getReadBuf = func( uint32) []byte {
		if cap(.readBuf) >= int() {
			return .readBuf[:]
		}
		.readBuf = make([]byte, )
		return .readBuf
	}
	.SetMaxReadFrameSize(maxFrameSize)
	return 
}
SetMaxReadFrameSize sets the maximum size of a frame that will be read by a subsequent call to ReadFrame. It is the caller's responsibility to advertise this limit with a SETTINGS frame.
func ( *Framer) ( uint32) {
	if  > maxFrameSize {
		 = maxFrameSize
	}
	.maxReadSize = 
}
ErrorDetail returns a more detailed error of the last error returned by Framer.ReadFrame. For instance, if ReadFrame returns a StreamError with code PROTOCOL_ERROR, ErrorDetail will say exactly what was invalid. ErrorDetail is not guaranteed to return a non-nil value and like the rest of the http2 package, its return value is not protected by an API compatibility promise. ErrorDetail is reset after the next call to ReadFrame.
func ( *Framer) () error {
	return .errDetail
}
ErrFrameTooLarge is returned from Framer.ReadFrame when the peer sends a frame that is larger than declared with SetMaxReadFrameSize.
var ErrFrameTooLarge = errors.New("http2: frame too large")
terminalReadFrameError reports whether err is an unrecoverable error from ReadFrame and no other frames should be read.
func ( error) bool {
	if ,  := .(StreamError);  {
		return false
	}
	return  != nil
}
ReadFrame reads a single frame. The returned Frame is only valid until the next call to ReadFrame. If the frame is larger than previously set with SetMaxReadFrameSize, the returned error is ErrFrameTooLarge. Other errors may be of type ConnectionError, StreamError, or anything else from the underlying reader.
func ( *Framer) () (Frame, error) {
	.errDetail = nil
	if .lastFrame != nil {
		.lastFrame.invalidate()
	}
	,  := readFrameHeader(.headerBuf[:], .r)
	if  != nil {
		return nil, 
	}
	if .Length > .maxReadSize {
		return nil, ErrFrameTooLarge
	}
	 := .getReadBuf(.Length)
	if ,  := io.ReadFull(.r, );  != nil {
		return nil, 
	}
	,  := typeFrameParser(.Type)(.frameCache, , )
	if  != nil {
		if ,  := .(connError);  {
			return nil, .connError(.Code, .Reason)
		}
		return nil, 
	}
	if  := .checkFrameOrder();  != nil {
		return nil, 
	}
	if .logReads {
		.debugReadLoggerf("http2: Framer %p: read %v", , summarizeFrame())
	}
	if .Type == FrameHeaders && .ReadMetaHeaders != nil {
		return .readMetaFrame(.(*HeadersFrame))
	}
	return , nil
}
connError returns ConnectionError(code) but first stashes away a public reason to the caller can optionally relay it to the peer before hanging up on them. This might help others debug their implementations.
func ( *Framer) ( ErrCode,  string) error {
	.errDetail = errors.New()
	return ConnectionError()
}
checkFrameOrder reports an error if f is an invalid frame to return next from ReadFrame. Mostly it checks whether HEADERS and CONTINUATION frames are contiguous.
func ( *Framer) ( Frame) error {
	 := .lastFrame
	.lastFrame = 
	if .AllowIllegalReads {
		return nil
	}

	 := .Header()
	if .lastHeaderStream != 0 {
		if .Type != FrameContinuation {
			return .connError(ErrCodeProtocol,
				fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d",
					.Type, .StreamID,
					.Header().Type, .lastHeaderStream))
		}
		if .StreamID != .lastHeaderStream {
			return .connError(ErrCodeProtocol,
				fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d",
					.StreamID, .lastHeaderStream))
		}
	} else if .Type == FrameContinuation {
		return .connError(ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", .StreamID))
	}

	switch .Type {
	case FrameHeaders, FrameContinuation:
		if .Flags.Has(FlagHeadersEndHeaders) {
			.lastHeaderStream = 0
		} else {
			.lastHeaderStream = .StreamID
		}
	}

	return nil
}
A DataFrame conveys arbitrary, variable-length sequences of octets associated with a stream. See http://http2.github.io/http2-spec/#rfc.section.6.1
Data returns the frame's data octets, not including any padding size byte or padding suffix bytes. The caller must not retain the returned memory past the next call to ReadFrame.
func ( *DataFrame) () []byte {
	.checkValid()
	return .data
}

func ( *frameCache,  FrameHeader,  []byte) (Frame, error) {
DATA frames MUST be associated with a stream. If a DATA frame is received whose stream identifier field is 0x0, the recipient MUST respond with a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
		return nil, connError{ErrCodeProtocol, "DATA frame with stream ID 0"}
	}
	 := .getDataFrame()
	.FrameHeader = 

	var  byte
	if .Flags.Has(FlagDataPadded) {
		var  error
		, ,  = readByte()
		if  != nil {
			return nil, 
		}
	}
If the length of the padding is greater than the length of the frame payload, the recipient MUST treat this as a connection error. Filed: https://github.com/http2/http2-spec/issues/610
		return nil, connError{ErrCodeProtocol, "pad size larger than data payload"}
	}
	.data = [:len()-int()]
	return , nil
}

var (
	errStreamID    = errors.New("invalid stream ID")
	errDepStreamID = errors.New("invalid dependent stream ID")
	errPadLength   = errors.New("pad length too large")
	errPadBytes    = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled")
)

func ( uint32) bool {
	return &(1<<31) == 0
}

func ( uint32) bool {
	return  != 0 && &(1<<31) == 0
}
WriteData writes a DATA frame. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility not to violate the maximum frame size and to not call other Write methods concurrently.
func ( *Framer) ( uint32,  bool,  []byte) error {
	return .WriteDataPadded(, , , nil)
}
WriteDataPadded writes a DATA frame with optional padding. If pad is nil, the padding bit is not sent. The length of pad must not exceed 255 bytes. The bytes of pad must all be zero, unless f.AllowIllegalWrites is set. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility not to violate the maximum frame size and to not call other Write methods concurrently.
func ( *Framer) ( uint32,  bool, ,  []byte) error {
	if !validStreamID() && !.AllowIllegalWrites {
		return errStreamID
	}
	if len() > 0 {
		if len() > 255 {
			return errPadLength
		}
		if !.AllowIllegalWrites {
			for ,  := range  {
"Padding octets MUST be set to zero when sending."
					return errPadBytes
				}
			}
		}
	}
	var  Flags
	if  {
		 |= FlagDataEndStream
	}
	if  != nil {
		 |= FlagDataPadded
	}
	.startWrite(FrameData, , )
	if  != nil {
		.wbuf = append(.wbuf, byte(len()))
	}
	.wbuf = append(.wbuf, ...)
	.wbuf = append(.wbuf, ...)
	return .endWrite()
}
A SettingsFrame conveys configuration parameters that affect how endpoints communicate, such as preferences and constraints on peer behavior. See http://http2.github.io/http2-spec/#SETTINGS
When this (ACK 0x1) bit is set, the payload of the SETTINGS frame MUST be empty. Receipt of a SETTINGS frame with the ACK flag set and a length field value other than 0 MUST be treated as a connection error (Section 5.4.1) of type FRAME_SIZE_ERROR.
SETTINGS frames always apply to a connection, never a single stream. The stream identifier for a SETTINGS frame MUST be zero (0x0). If an endpoint receives a SETTINGS frame whose stream identifier field is anything other than 0x0, the endpoint MUST respond with a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
Expecting even number of 6 byte settings.
Values above the maximum flow control window size of 2^31 - 1 MUST be treated as a connection error (Section 5.4.1) of type FLOW_CONTROL_ERROR.
		return nil, ConnectionError(ErrCodeFlowControl)
	}
	return , nil
}

func ( *SettingsFrame) () bool {
	return .FrameHeader.Flags.Has(FlagSettingsAck)
}

func ( *SettingsFrame) ( SettingID) ( uint32,  bool) {
	.checkValid()
	for  := 0;  < .NumSettings(); ++ {
		if  := .Setting(); .ID ==  {
			return .Val, true
		}
	}
	return 0, false
}
Setting returns the setting from the frame at the given 0-based index. The index must be >= 0 and less than f.NumSettings().
func ( *SettingsFrame) ( int) Setting {
	 := .p
	return Setting{
		ID:  SettingID(binary.BigEndian.Uint16([*6 : *6+2])),
		Val: binary.BigEndian.Uint32([*6+2 : *6+6]),
	}
}

func ( *SettingsFrame) () int { return len(.p) / 6 }
HasDuplicates reports whether f contains any duplicate setting IDs.
func ( *SettingsFrame) () bool {
	 := .NumSettings()
	if  == 0 {
		return false
If it's small enough (the common case), just do the n^2 thing and avoid a map allocation.
	if  < 10 {
		for  := 0;  < ; ++ {
			 := .Setting().ID
			for  :=  + 1;  < ; ++ {
				 := .Setting().ID
				if  ==  {
					return true
				}
			}
		}
		return false
	}
	 := map[SettingID]bool{}
	for  := 0;  < ; ++ {
		 := .Setting().ID
		if [] {
			return true
		}
		[] = true
	}
	return false
}
ForeachSetting runs fn for each setting. It stops and returns the first error.
func ( *SettingsFrame) ( func(Setting) error) error {
	.checkValid()
	for  := 0;  < .NumSettings(); ++ {
		if  := (.Setting());  != nil {
			return 
		}
	}
	return nil
}
WriteSettings writes a SETTINGS frame with zero or more settings specified and the ACK bit not set. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility to not call other Write methods concurrently.
func ( *Framer) ( ...Setting) error {
	.startWrite(FrameSettings, 0, 0)
	for ,  := range  {
		.writeUint16(uint16(.ID))
		.writeUint32(.Val)
	}
	return .endWrite()
}
WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility to not call other Write methods concurrently.
A PingFrame is a mechanism for measuring a minimal round trip time from the sender, as well as determining whether an idle connection is still functional. See http://http2.github.io/http2-spec/#rfc.section.6.7
type PingFrame struct {
	FrameHeader
	Data [8]byte
}

func ( *PingFrame) () bool { return .Flags.Has(FlagPingAck) }

func ( *frameCache,  FrameHeader,  []byte) (Frame, error) {
	if len() != 8 {
		return nil, ConnectionError(ErrCodeFrameSize)
	}
	if .StreamID != 0 {
		return nil, ConnectionError(ErrCodeProtocol)
	}
	 := &PingFrame{FrameHeader: }
	copy(.Data[:], )
	return , nil
}

func ( *Framer) ( bool,  [8]byte) error {
	var  Flags
	if  {
		 = FlagPingAck
	}
	.startWrite(FramePing, , 0)
	.writeBytes([:])
	return .endWrite()
}
A GoAwayFrame informs the remote peer to stop creating streams on this connection. See http://http2.github.io/http2-spec/#rfc.section.6.8
DebugData returns any debug data in the GOAWAY frame. Its contents are not defined. The caller must not retain the returned memory past the next call to ReadFrame.
func ( *GoAwayFrame) () []byte {
	.checkValid()
	return .debugData
}

func ( *frameCache,  FrameHeader,  []byte) (Frame, error) {
	if .StreamID != 0 {
		return nil, ConnectionError(ErrCodeProtocol)
	}
	if len() < 8 {
		return nil, ConnectionError(ErrCodeFrameSize)
	}
	return &GoAwayFrame{
		FrameHeader:  ,
		LastStreamID: binary.BigEndian.Uint32([:4]) & (1<<31 - 1),
		ErrCode:      ErrCode(binary.BigEndian.Uint32([4:8])),
		debugData:    [8:],
	}, nil
}

func ( *Framer) ( uint32,  ErrCode,  []byte) error {
	.startWrite(FrameGoAway, 0, 0)
	.writeUint32( & (1<<31 - 1))
	.writeUint32(uint32())
	.writeBytes()
	return .endWrite()
}
An UnknownFrame is the frame type returned when the frame type is unknown or no specific frame type parser exists.
type UnknownFrame struct {
	FrameHeader
	p []byte
}
Payload returns the frame's payload (after the header). It is not valid to call this method after a subsequent call to Framer.ReadFrame, nor is it valid to retain the returned slice. The memory is owned by the Framer and is invalidated when the next frame is read.
func ( *UnknownFrame) () []byte {
	.checkValid()
	return .p
}

func ( *frameCache,  FrameHeader,  []byte) (Frame, error) {
	return &UnknownFrame{, }, nil
}
A WindowUpdateFrame is used to implement flow control. See http://http2.github.io/http2-spec/#rfc.section.6.9
type WindowUpdateFrame struct {
	FrameHeader
	Increment uint32 // never read with high bit set
}

func ( *frameCache,  FrameHeader,  []byte) (Frame, error) {
	if len() != 4 {
		return nil, ConnectionError(ErrCodeFrameSize)
	}
	 := binary.BigEndian.Uint32([:4]) & 0x7fffffff // mask off high reserved bit
A receiver MUST treat the receipt of a WINDOW_UPDATE frame with an flow control window increment of 0 as a stream error (Section 5.4.2) of type PROTOCOL_ERROR; errors on the connection flow control window MUST be treated as a connection error (Section 5.4.1).
WriteWindowUpdate writes a WINDOW_UPDATE frame. The increment value must be between 1 and 2,147,483,647, inclusive. If the Stream ID is zero, the window update applies to the connection as a whole.
"The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
	if ( < 1 ||  > 2147483647) && !.AllowIllegalWrites {
		return errors.New("illegal window increment value")
	}
	.startWrite(FrameWindowUpdate, 0, )
	.writeUint32()
	return .endWrite()
}
A HeadersFrame is used to open a stream and additionally carries a header block fragment.
type HeadersFrame struct {
	FrameHeader
Priority is set if FlagHeadersPriority is set in the FrameHeader.
HEADERS frames MUST be associated with a stream. If a HEADERS frame is received whose stream identifier field is 0x0, the recipient MUST respond with a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
		return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"}
	}
	var  uint8
	if .Flags.Has(FlagHeadersPadded) {
		if , ,  = readByte();  != nil {
			return
		}
	}
	if .Flags.Has(FlagHeadersPriority) {
		var  uint32
		, ,  = readUint32()
		if  != nil {
			return nil, 
		}
		.Priority.StreamDep =  & 0x7fffffff
		.Priority.Exclusive = ( != .Priority.StreamDep) // high bit was set
		, .Priority.Weight,  = readByte()
		if  != nil {
			return nil, 
		}
	}
	if len()-int() <= 0 {
		return nil, streamError(.StreamID, ErrCodeProtocol)
	}
	.headerFragBuf = [:len()-int()]
	return , nil
}
HeadersFrameParam are the parameters for writing a HEADERS frame.
StreamID is the required Stream ID to initiate.
BlockFragment is part (or all) of a Header Block.
EndStream indicates that the header block is the last that the endpoint will send for the identified stream. Setting this flag causes the stream to enter one of "half closed" states.
EndHeaders indicates that this frame contains an entire header block and is not followed by any CONTINUATION frames.
PadLength is the optional number of bytes of zeros to add to this frame.
Priority, if non-zero, includes stream priority information in the HEADER frame.
WriteHeaders writes a single HEADERS frame. This is a low-level header writing method. Encoding headers and splitting them into any necessary CONTINUATION frames is handled elsewhere. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility to not call other Write methods concurrently.
func ( *Framer) ( HeadersFrameParam) error {
	if !validStreamID(.StreamID) && !.AllowIllegalWrites {
		return errStreamID
	}
	var  Flags
	if .PadLength != 0 {
		 |= FlagHeadersPadded
	}
	if .EndStream {
		 |= FlagHeadersEndStream
	}
	if .EndHeaders {
		 |= FlagHeadersEndHeaders
	}
	if !.Priority.IsZero() {
		 |= FlagHeadersPriority
	}
	.startWrite(FrameHeaders, , .StreamID)
	if .PadLength != 0 {
		.writeByte(.PadLength)
	}
	if !.Priority.IsZero() {
		 := .Priority.StreamDep
		if !validStreamIDOrZero() && !.AllowIllegalWrites {
			return errDepStreamID
		}
		if .Priority.Exclusive {
			 |= 1 << 31
		}
		.writeUint32()
		.writeByte(.Priority.Weight)
	}
	.wbuf = append(.wbuf, .BlockFragment...)
	.wbuf = append(.wbuf, padZeros[:.PadLength]...)
	return .endWrite()
}
A PriorityFrame specifies the sender-advised priority of a stream. See http://http2.github.io/http2-spec/#rfc.section.6.3
PriorityParam are the stream prioritzation parameters.
StreamDep is a 31-bit stream identifier for the stream that this stream depends on. Zero means no dependency.
Exclusive is whether the dependency is exclusive.
Weight is the stream's zero-indexed weight. It should be set together with StreamDep, or neither should be set. Per the spec, "Add one to the value to obtain a weight between 1 and 256."
	Weight uint8
}

func ( PriorityParam) () bool {
	return  == PriorityParam{}
}

func ( *frameCache,  FrameHeader,  []byte) (Frame, error) {
	if .StreamID == 0 {
		return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
	}
	if len() != 5 {
		return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len())}
	}
	 := binary.BigEndian.Uint32([:4])
	 :=  & 0x7fffffff // mask off high bit
	return &PriorityFrame{
		FrameHeader: ,
		PriorityParam: PriorityParam{
			Weight:    [4],
			StreamDep: ,
			Exclusive:  != , // was high bit set?
		},
	}, nil
}
WritePriority writes a PRIORITY frame. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility to not call other Write methods concurrently.
func ( *Framer) ( uint32,  PriorityParam) error {
	if !validStreamID() && !.AllowIllegalWrites {
		return errStreamID
	}
	if !validStreamIDOrZero(.StreamDep) {
		return errDepStreamID
	}
	.startWrite(FramePriority, 0, )
	 := .StreamDep
	if .Exclusive {
		 |= 1 << 31
	}
	.writeUint32()
	.writeByte(.Weight)
	return .endWrite()
}
A RSTStreamFrame allows for abnormal termination of a stream. See http://http2.github.io/http2-spec/#rfc.section.6.4
WriteRSTStream writes a RST_STREAM frame. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility to not call other Write methods concurrently.
func ( *Framer) ( uint32,  ErrCode) error {
	if !validStreamID() && !.AllowIllegalWrites {
		return errStreamID
	}
	.startWrite(FrameRSTStream, 0, )
	.writeUint32(uint32())
	return .endWrite()
}
A ContinuationFrame is used to continue a sequence of header block fragments. See http://http2.github.io/http2-spec/#rfc.section.6.10
type ContinuationFrame struct {
	FrameHeader
	headerFragBuf []byte
}

func ( *frameCache,  FrameHeader,  []byte) (Frame, error) {
	if .StreamID == 0 {
		return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
	}
	return &ContinuationFrame{, }, nil
}

func ( *ContinuationFrame) () []byte {
	.checkValid()
	return .headerFragBuf
}

func ( *ContinuationFrame) () bool {
	return .FrameHeader.Flags.Has(FlagContinuationEndHeaders)
}
WriteContinuation writes a CONTINUATION frame. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility to not call other Write methods concurrently.
func ( *Framer) ( uint32,  bool,  []byte) error {
	if !validStreamID() && !.AllowIllegalWrites {
		return errStreamID
	}
	var  Flags
	if  {
		 |= FlagContinuationEndHeaders
	}
	.startWrite(FrameContinuation, , )
	.wbuf = append(.wbuf, ...)
	return .endWrite()
}
A PushPromiseFrame is used to initiate a server stream. See http://http2.github.io/http2-spec/#rfc.section.6.6
PUSH_PROMISE frames MUST be associated with an existing, peer-initiated stream. The stream identifier of a PUSH_PROMISE frame indicates the stream it is associated with. If the stream identifier field specifies the value 0x0, a recipient MUST respond with a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
The PUSH_PROMISE frame includes optional padding. Padding fields and flags are identical to those defined for DATA frames
	var  uint8
	if .Flags.Has(FlagPushPromisePadded) {
		if , ,  = readByte();  != nil {
			return
		}
	}

	, .PromiseID,  = readUint32()
	if  != nil {
		return
	}
	.PromiseID = .PromiseID & (1<<31 - 1)

like the DATA frame, error out if padding is longer than the body.
		return nil, ConnectionError(ErrCodeProtocol)
	}
	.headerFragBuf = [:len()-int()]
	return , nil
}
PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
StreamID is the required Stream ID to initiate.
PromiseID is the required Stream ID which this Push Promises
BlockFragment is part (or all) of a Header Block.
EndHeaders indicates that this frame contains an entire header block and is not followed by any CONTINUATION frames.
PadLength is the optional number of bytes of zeros to add to this frame.
WritePushPromise writes a single PushPromise Frame. As with Header Frames, This is the low level call for writing individual frames. Continuation frames are handled elsewhere. It will perform exactly one Write to the underlying Writer. It is the caller's responsibility to not call other Write methods concurrently.
WriteRawFrame writes a raw frame. This can be used to write extension frames unknown to this package.
func ( *Framer) ( FrameType,  Flags,  uint32,  []byte) error {
	.startWrite(, , )
	.writeBytes()
	return .endWrite()
}

func ( []byte) ( []byte,  byte,  error) {
	if len() == 0 {
		return nil, 0, io.ErrUnexpectedEOF
	}
	return [1:], [0], nil
}

func ( []byte) ( []byte,  uint32,  error) {
	if len() < 4 {
		return nil, 0, io.ErrUnexpectedEOF
	}
	return [4:], binary.BigEndian.Uint32([:4]), nil
}

type streamEnder interface {
	StreamEnded() bool
}

type headersEnder interface {
	HeadersEnded() bool
}

type headersOrContinuation interface {
	headersEnder
	HeaderBlockFragment() []byte
}
A MetaHeadersFrame is the representation of one HEADERS frame and zero or more contiguous CONTINUATION frames and the decoding of their HPACK-encoded contents. This type of frame does not appear on the wire and is only returned by the Framer when Framer.ReadMetaHeaders is set.
Fields are the fields contained in the HEADERS and CONTINUATION frames. The underlying slice is owned by the Framer and must not be retained after the next call to ReadFrame. Fields are guaranteed to be in the correct http2 order and not have unknown pseudo header fields or invalid header field names or values. Required pseudo header fields may be missing, however. Use the MetaHeadersFrame.Pseudo accessor method access pseudo headers.
Truncated is whether the max header list size limit was hit and Fields is incomplete. The hpack decoder state is still valid, however.
PseudoValue returns the given pseudo header field's value. The provided pseudo field should not contain the leading colon.
func ( *MetaHeadersFrame) ( string) string {
	for ,  := range .Fields {
		if !.IsPseudo() {
			return ""
		}
		if .Name[1:] ==  {
			return .Value
		}
	}
	return ""
}
RegularFields returns the regular (non-pseudo) header fields of mh. The caller does not own the returned slice.
func ( *MetaHeadersFrame) () []hpack.HeaderField {
	for ,  := range .Fields {
		if !.IsPseudo() {
			return .Fields[:]
		}
	}
	return nil
}
PseudoFields returns the pseudo header fields of mh. The caller does not own the returned slice.
func ( *MetaHeadersFrame) () []hpack.HeaderField {
	for ,  := range .Fields {
		if !.IsPseudo() {
			return .Fields[:]
		}
	}
	return .Fields
}

func ( *MetaHeadersFrame) () error {
	var ,  bool
	 := .PseudoFields()
	for ,  := range  {
		switch .Name {
		case ":method", ":path", ":scheme", ":authority":
			 = true
		case ":status":
			 = true
		default:
			return pseudoHeaderError(.Name)
Check for duplicates. This would be a bad algorithm, but N is 4. And this doesn't allocate.
		for ,  := range [:] {
			if .Name == .Name {
				return duplicatePseudoHeaderError(.Name)
			}
		}
	}
	if  &&  {
		return errMixPseudoHeaderTypes
	}
	return nil
}

func ( *Framer) () int {
	 := .maxHeaderListSize()
	if uint32(int()) ==  {
		return int()
They had a crazy big number for MaxHeaderBytes anyway, so give them unlimited header lengths:
	return 0
}
readMetaFrame returns 0 or more CONTINUATION frames from fr and merge them into the provided hf and returns a MetaHeadersFrame with the decoded hpack values.
func ( *Framer) ( *HeadersFrame) (*MetaHeadersFrame, error) {
	if .AllowIllegalReads {
		return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
	}
	 := &MetaHeadersFrame{
		HeadersFrame: ,
	}
	var  = .maxHeaderListSize()
	var  bool

	var  error // pseudo header field errors
	 := .ReadMetaHeaders
	.SetEmitEnabled(true)
	.SetMaxStringLength(.maxHeaderStringLen())
	.SetEmitFunc(func( hpack.HeaderField) {
		if VerboseLogs && .logReads {
			.debugReadLoggerf("http2: decoded hpack field %+v", )
		}
		if !httpguts.ValidHeaderFieldValue(.Value) {
			 = headerFieldValueError(.Value)
		}
		 := strings.HasPrefix(.Name, ":")
		if  {
			if  {
				 = errPseudoAfterRegular
			}
		} else {
			 = true
			if !validWireHeaderFieldName(.Name) {
				 = headerFieldNameError(.Name)
			}
		}

		if  != nil {
			.SetEmitEnabled(false)
			return
		}

		 := .Size()
		if  >  {
			.SetEmitEnabled(false)
			.Truncated = true
			return
		}
		 -= 

		.Fields = append(.Fields, )
Lose reference to MetaHeadersFrame:
	defer .SetEmitFunc(func( hpack.HeaderField) {})

	var  headersOrContinuation = 
	for {
		 := .HeaderBlockFragment()
		if ,  := .Write();  != nil {
			return nil, ConnectionError(ErrCodeCompression)
		}

		if .HeadersEnded() {
			break
		}
		if ,  := .ReadFrame();  != nil {
			return nil, 
		} else {
			 = .(*ContinuationFrame) // guaranteed by checkFrameOrder
		}
	}

	.HeadersFrame.headerFragBuf = nil
	.HeadersFrame.invalidate()

	if  := .Close();  != nil {
		return nil, ConnectionError(ErrCodeCompression)
	}
	if  != nil {
		.errDetail = 
		if VerboseLogs {
			log.Printf("http2: invalid header: %v", )
		}
		return nil, StreamError{.StreamID, ErrCodeProtocol, }
	}
	if  := .checkPseudos();  != nil {
		.errDetail = 
		if VerboseLogs {
			log.Printf("http2: invalid pseudo headers: %v", )
		}
		return nil, StreamError{.StreamID, ErrCodeProtocol, }
	}
	return , nil
}

func ( Frame) string {
	var  bytes.Buffer
	.Header().writeDebug(&)
	switch f := .(type) {
	case *SettingsFrame:
		 := 0
		.ForeachSetting(func( Setting) error {
			++
			if  == 1 {
				.WriteString(", settings:")
			}
			fmt.Fprintf(&, " %v=%v,", .ID, .Val)
			return nil
		})
		if  > 0 {
			.Truncate(.Len() - 1) // remove trailing comma
		}
	case *DataFrame:
		 := .Data()
		const  = 256
		if len() >  {
			 = [:]
		}
		fmt.Fprintf(&, " data=%q", )
		if len(.Data()) >  {
			fmt.Fprintf(&, " (%d bytes omitted)", len(.Data())-)
		}
	case *WindowUpdateFrame:
		if .StreamID == 0 {
			.WriteString(" (conn)")
		}
		fmt.Fprintf(&, " incr=%v", .Increment)
	case *PingFrame:
		fmt.Fprintf(&, " ping=%q", .Data[:])
	case *GoAwayFrame:
		fmt.Fprintf(&, " LastStreamID=%v ErrCode=%v Debug=%q",
			.LastStreamID, .ErrCode, .debugData)
	case *RSTStreamFrame:
		fmt.Fprintf(&, " ErrCode=%v", .ErrCode)
	}
	return .String()