You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mask.go 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in the
  3. // LICENSE file.
  4. // +build !appengine
  5. package websocket
  6. import "unsafe"
  7. const wordSize = int(unsafe.Sizeof(uintptr(0)))
  8. func maskBytes(key [4]byte, pos int, b []byte) int {
  9. // Mask one byte at a time for small buffers.
  10. if len(b) < 2*wordSize {
  11. for i := range b {
  12. b[i] ^= key[pos&3]
  13. pos++
  14. }
  15. return pos & 3
  16. }
  17. // Mask one byte at a time to word boundary.
  18. if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 {
  19. n = wordSize - n
  20. for i := range b[:n] {
  21. b[i] ^= key[pos&3]
  22. pos++
  23. }
  24. b = b[n:]
  25. }
  26. // Create aligned word size key.
  27. var k [wordSize]byte
  28. for i := range k {
  29. k[i] = key[(pos+i)&3]
  30. }
  31. kw := *(*uintptr)(unsafe.Pointer(&k))
  32. // Mask one word at a time.
  33. n := (len(b) / wordSize) * wordSize
  34. for i := 0; i < n; i += wordSize {
  35. *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw
  36. }
  37. // Mask one byte at a time for remaining bytes.
  38. b = b[n:]
  39. for i := range b {
  40. b[i] ^= key[pos&3]
  41. pos++
  42. }
  43. return pos & 3
  44. }