package ws

import (
	
)

// Cipher applies XOR cipher to the payload using mask.
// Offset is used to cipher chunked data (e.g. in io.Reader implementations).
//
// To convert masked data into unmasked data, or vice versa, the following
// algorithm is applied.  The same algorithm applies regardless of the
// direction of the translation, e.g., the same steps are applied to
// mask the data as to unmask the data.
func ( []byte,  [4]byte,  int) {
	 := len()
	if  < 8 {
		for  := 0;  < ; ++ {
			[] ^= [(+)%4]
		}
		return
	}

	// Calculate position in mask due to previously processed bytes number.
	 :=  % 4
	// Count number of bytes will processed one by one from the beginning of payload.
	 := remain[]
	// Count number of bytes will processed one by one from the end of payload.
	// This is done to process payload by 16 bytes in each iteration of main loop.
	 := ( - ) % 16

	for  := 0;  < ; ++ {
		[] ^= [(+)%4]
	}
	for  :=  - ;  < ; ++ {
		[] ^= [(+)%4]
	}

	// NOTE: we use here binary.LittleEndian regardless of what is real
	// endianness on machine is. To do so, we have to use binary.LittleEndian in
	// the masking loop below as well.
	var (
		  = binary.LittleEndian.Uint32([:])
		 = uint64()<<32 | uint64()
	)
	// Skip already processed right part.
	// Get number of uint64 parts remaining to process.
	 = ( -  - ) >> 4
	 := 
	for  := 0;  < ; ++ {
		 := [ : +16]
		 := binary.LittleEndian.Uint64() ^ 
		 := binary.LittleEndian.Uint64([8:]) ^ 
		binary.LittleEndian.PutUint64(, )
		binary.LittleEndian.PutUint64([8:], )
		 += 16
	}
}

// remain maps position in masking key [0,4) to number
// of bytes that need to be processed manually inside Cipher().
var remain = [4]int{0, 3, 2, 1}