Пример #1
0
func TestTakeFromEmpty(t *testing.T) {
	bp := bufferpool.New(1, 1)
	poolBuf := bp.Take()
	if !bytes.Equal(poolBuf.Bytes(), []byte("")) {
		t.Fatalf("Buffer from empty bufferpool was allocated incorrectly.")
	}
}
Пример #2
0
func TestSliceSemantics(t *testing.T) {
	bp := bufferpool.New(1, 8)

	buf := bp.Take()
	buf.WriteString("abc")
	bp.Give(buf)

	buf2 := bp.TakeSlice()

	if !bytes.Equal(buf2[:3], []byte("abc")) {
		t.Fatalf("Buffer from filled bufferpool was recycled incorrectly.")
	}
}
Пример #3
0
func ExampleNew() {
	bp := bufferpool.New(10, 255)

	dogBuffer := bp.Take()
	dogBuffer.WriteString("Dog!")
	bp.Give(dogBuffer)

	catBuffer := bp.Take() // dogBuffer is reused and reset.
	catBuffer.WriteString("Cat!")

	fmt.Println(catBuffer)
	// Output:
	// Cat!
}
Пример #4
0
func TestTakeFromFilled(t *testing.T) {
	bp := bufferpool.New(1, 1)

	origBuf := bytes.NewBuffer([]byte("X"))
	bp.Give(origBuf)

	reusedBuf := bp.Take()
	if !bytes.Equal(reusedBuf.Bytes(), []byte("")) {
		t.Fatalf("Buffer from filled bufferpool was recycled incorrectly.")
	}

	// Compare addresses of the first element in the underlying slice.
	if &origBuf.Bytes()[:1][0] != &reusedBuf.Bytes()[:1][0] {
		t.Fatalf("Recycled buffer points at different address.")
	}
}
Пример #5
0
func (s *Server) serve(listenAddr string) error {
	if s.sock != nil {
		return errors.New("server already booted")
	}

	udpAddr, err := net.ResolveUDPAddr("udp", listenAddr)
	if err != nil {
		close(s.booting)
		return err
	}

	sock, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		close(s.booting)
		return err
	}
	defer sock.Close()

	if s.config.UDPReadBufferSize > 0 {
		sock.SetReadBuffer(s.config.UDPReadBufferSize)
	}

	pool := bufferpool.New(1000, 2048)
	s.sock = sock
	close(s.booting)

	for !s.done {
		buffer := pool.TakeSlice()
		sock.SetReadDeadline(time.Now().Add(time.Second))
		n, addr, err := sock.ReadFromUDP(buffer)

		if err != nil {
			if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
				pool.GiveSlice(buffer)
				continue
			}
			return err
		}

		go func() {
			start := time.Now()
			response, action, err := s.handlePacket(buffer[:n], addr)
			defer pool.GiveSlice(buffer)
			duration := time.Since(start)

			if len(response) > 0 {
				sock.WriteToUDP(response, addr)
			}

			if glog.V(2) {
				if err != nil {
					glog.Infof("[UDP - %9s] %s %s (%s)", duration, action, addr, err)
				} else {
					glog.Infof("[UDP - %9s] %s %s", duration, action, addr)
				}
			}
		}()
	}

	return nil
}