package httphead

import 

var (
	comma     = []byte{','}
	equality  = []byte{'='}
	semicolon = []byte{';'}
	quote     = []byte{'"'}
	escape    = []byte{'\\'}
)

// WriteOptions write options list to the dest.
// It uses the same form as {Scan,Parse}Options functions:
// values = 1#value
// value = token *( ";" param )
// param = token [ "=" (token | quoted-string) ]
//
// It wraps valuse into the quoted-string sequence if it contains any
// non-token characters.
func ( io.Writer,  []Option) ( int,  error) {
	 := writer{w: }
	for ,  := range  {
		if  > 0 {
			.write(comma)
		}

		writeTokenSanitized(&, .Name)

		for ,  := range .Parameters.data() {
			.write(semicolon)
			writeTokenSanitized(&, .key)
			if len(.value) != 0 {
				.write(equality)
				writeTokenSanitized(&, .value)
			}
		}
	}
	return .result()
}

// writeTokenSanitized writes token as is or as quouted string if it contains
// non-token characters.
//
// Note that is is not expects LWS sequnces be in s, cause LWS is used only as
// header field continuation:
// "A CRLF is allowed in the definition of TEXT only as part of a header field
// continuation. It is expected that the folding LWS will be replaced with a
// single SP before interpretation of the TEXT value."
// See https://tools.ietf.org/html/rfc2616#section-2
//
// That is we sanitizing s for writing, so there could not be any header field
// continuation.
// That is any CRLF will be escaped as any other control characters not allowd in TEXT.
func writeTokenSanitized( *writer,  []byte) {
	var  bool
	var  int
	for  := 0;  < len(); ++ {
		 := []
		if !OctetTypes[].IsToken() && ! {
			 = true
			.write(quote)
		}
		if OctetTypes[].IsControl() ||  == '"' {
			if ! {
				 = true
				.write(quote)
			}
			.write([:])
			.write(escape)
			.write([ : +1])
			 =  + 1
		}
	}
	if ! {
		.write()
	} else {
		.write([:])
		.write(quote)
	}
}

type writer struct {
	w   io.Writer
	n   int
	err error
}

func ( *writer) ( []byte) {
	if .err != nil {
		return
	}
	var  int
	, .err = .w.Write()
	.n += 
	return
}

func ( *writer) () (int, error) {
	return .n, .err
}