package httphead

import (
	
)

// ItemType encodes type of the lexing token.
type ItemType int

const (
	// ItemUndef reports that token is undefined.
	ItemUndef ItemType = iota
	// ItemToken reports that token is RFC2616 token.
	ItemToken
	// ItemSeparator reports that token is RFC2616 separator.
	ItemSeparator
	// ItemString reports that token is RFC2616 quouted string.
	ItemString
	// ItemComment reports that token is RFC2616 comment.
	ItemComment
	// ItemOctet reports that token is octet slice.
	ItemOctet
)

// Scanner represents header tokens scanner.
// See https://tools.ietf.org/html/rfc2616#section-2
type Scanner struct {
	data []byte
	pos  int

	itemType  ItemType
	itemBytes []byte

	err bool
}

// NewScanner creates new RFC2616 data scanner.
func ( []byte) *Scanner {
	return &Scanner{data: }
}

// Next scans for next token. It returns true on successful scanning, and false
// on error or EOF.
func ( *Scanner) () bool {
	,  := .nextChar()
	if ! {
		return false
	}
	switch  {
	case '"': // quoted-string;
		return .fetchQuotedString()

	case '(': // comment;
		return .fetchComment()

	case '\\', ')': // unexpected chars;
		.err = true
		return false

	default:
		return .fetchToken()
	}
}

// FetchUntil fetches ItemOctet from current scanner position to first
// occurence of the c or to the end of the underlying data.
func ( *Scanner) ( byte) bool {
	.resetItem()
	if .pos == len(.data) {
		return false
	}
	return .fetchOctet()
}

// Peek reads byte at current position without advancing it. On end of data it
// returns 0.
func ( *Scanner) () byte {
	if .pos == len(.data) {
		return 0
	}
	return .data[.pos]
}

// Peek2 reads two first bytes at current position without advancing it.
// If there not enough data it returs 0.
func ( *Scanner) () (,  byte) {
	if .pos == len(.data) {
		return 0, 0
	}
	if .pos+1 == len(.data) {
		return .data[.pos], 0
	}
	return .data[.pos], .data[.pos+1]
}

// Buffered reporst how many bytes there are left to scan.
func ( *Scanner) () int {
	return len(.data) - .pos
}

// Advance moves current position index at n bytes. It returns true on
// successful move.
func ( *Scanner) ( int) bool {
	.pos += 
	if .pos > len(.data) {
		.pos = len(.data)
		return false
	}
	return true
}

// Skip skips all bytes until first occurence of c.
func ( *Scanner) ( byte) {
	if .err {
		return
	}
	// Reset scanner state.
	.resetItem()

	if  := bytes.IndexByte(.data[.pos:], );  == -1 {
		// Reached the end of data.
		.pos = len(.data)
	} else {
		.pos +=  + 1
	}
}

// SkipEscaped skips all bytes until first occurence of non-escaped c.
func ( *Scanner) ( byte) {
	if .err {
		return
	}
	// Reset scanner state.
	.resetItem()

	if  := ScanUntil(.data[.pos:], );  == -1 {
		// Reached the end of data.
		.pos = len(.data)
	} else {
		.pos +=  + 1
	}
}

// Type reports current token type.
func ( *Scanner) () ItemType {
	return .itemType
}

// Bytes returns current token bytes.
func ( *Scanner) () []byte {
	return .itemBytes
}

func ( *Scanner) () (byte, bool) {
	// Reset scanner state.
	.resetItem()

	if .err {
		return 0, false
	}
	.pos += SkipSpace(.data[.pos:])
	if .pos == len(.data) {
		return 0, false
	}
	return .data[.pos], true
}

func ( *Scanner) () {
	.itemType = ItemUndef
	.itemBytes = nil
}

func ( *Scanner) ( byte) bool {
	 := .pos
	if  := bytes.IndexByte(.data[.pos:], );  == -1 {
		// Reached the end of data.
		.pos = len(.data)
	} else {
		.pos += 
	}

	.itemType = ItemOctet
	.itemBytes = .data[:.pos]

	return true
}

func ( *Scanner) () bool {
	,  := ScanToken(.data[.pos:])
	if  == -1 {
		.err = true
		return false
	}

	.itemType = 
	.itemBytes = .data[.pos : .pos+]
	.pos += 

	return true
}

func ( *Scanner) () ( bool) {
	.pos++

	 := ScanUntil(.data[.pos:], '"')
	if  == -1 {
		.err = true
		return false
	}

	.itemType = ItemString
	.itemBytes = RemoveByte(.data[.pos:.pos+], '\\')
	.pos +=  + 1

	return true
}

func ( *Scanner) () ( bool) {
	.pos++

	 := ScanPairGreedy(.data[.pos:], '(', ')')
	if  == -1 {
		.err = true
		return false
	}

	.itemType = ItemComment
	.itemBytes = RemoveByte(.data[.pos:.pos+], '\\')
	.pos +=  + 1

	return true
}

// ScanUntil scans for first non-escaped character c in given data.
// It returns index of matched c and -1 if c is not found.
func ( []byte,  byte) ( int) {
	for {
		 := bytes.IndexByte([:], )
		if  == -1 {
			return -1
		}
		 += 
		if  == 0 || [-1] != '\\' {
			break
		}
		++
	}
	return
}

// ScanPairGreedy scans for complete pair of opening and closing chars in greedy manner.
// Note that first opening byte must not be present in data.
func ( []byte, ,  byte) ( int) {
	var  int
	 := 1
	for {
		 := bytes.IndexByte([:], )
		if  == -1 {
			return -1
		}
		 += 
		// If found index is not escaped then it is the end.
		if  == 0 || [-1] != '\\' {
			--
		}

		for  <  {
			 := bytes.IndexByte([:], )
			if  == -1 {
				break
			}
			 +=  + 1
			++
		}

		if  == 0 {
			break
		}

		++
		 = 
	}
	return
}

// RemoveByte returns data without c. If c is not present in data it returns
// the same slice. If not, it copies data without c.
func ( []byte,  byte) []byte {
	 := bytes.IndexByte(, )
	if  == -1 {
		return 
	}

	 := len() - 1

	// If character is present, than allocate slice with n-1 capacity. That is,
	// resulting bytes could be at most n-1 length.
	 := make([]byte, )
	 := copy(, [:])

	for  :=  + 1;  < ; {
		 = bytes.IndexByte([:], )
		if  != -1 {
			 += copy([:], [:+])
			 =  +  + 1
		} else {
			 += copy([:], [:])
			break
		}
	}

	return [:]
}

// SkipSpace skips spaces and lws-sequences from p.
// It returns number ob bytes skipped.
func ( []byte) ( int) {
	for len() > 0 {
		switch {
		case len() >= 3 &&
			[0] == '\r' &&
			[1] == '\n' &&
			OctetTypes[[2]].IsSpace():
			 = [3:]
			 += 3
		case OctetTypes[[0]].IsSpace():
			 = [1:]
			++
		default:
			return
		}
	}
	return
}

// ScanToken scan for next token in p. It returns length of the token and its
// type. It do not trim p.
func ( []byte) ( int,  ItemType) {
	if len() == 0 {
		return 0, ItemUndef
	}

	 := [0]
	switch {
	case OctetTypes[].IsSeparator():
		return 1, ItemSeparator

	case OctetTypes[].IsToken():
		for  = 1;  < len(); ++ {
			 := []
			if !OctetTypes[].IsToken() {
				break
			}
		}
		return , ItemToken

	default:
		return -1, ItemUndef
	}
}