github.com/pawelgaczynski/gain@v0.4.0-alpha.0.20230821120126-41f1e60a18da/conn_pool.go (about)

     1  // Copyright (c) 2023 Paweł Gaczyński
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package gain
    16  
    17  import (
    18  	"github.com/pawelgaczynski/gain/pkg/pool/ringbuffer"
    19  	"github.com/pawelgaczynski/gain/pkg/pool/sync"
    20  )
    21  
    22  var builtinConnectionPool = newConnectionPool()
    23  
    24  func getConnection() *connection {
    25  	return builtinConnectionPool.Get()
    26  }
    27  
    28  func putConnection(conn *connection) {
    29  	builtinConnectionPool.Put(conn)
    30  }
    31  
    32  type connectionPool struct {
    33  	internalPool sync.Pool[*connection]
    34  }
    35  
    36  func (c *connectionPool) Put(conn *connection) {
    37  	ringbuffer.Put(conn.inboundBuffer)
    38  	ringbuffer.Put(conn.outboundBuffer)
    39  	conn.inboundBuffer = nil
    40  	conn.outboundBuffer = nil
    41  	conn.fd = 0
    42  	conn.key = 0
    43  	conn.state = 0
    44  	conn.msgHdr = nil
    45  	conn.rawSockaddr = nil
    46  	conn.mode.Store(0)
    47  	conn.closed.Store(false)
    48  	conn.network = 0
    49  	conn.ctx = nil
    50  
    51  	c.internalPool.Put(conn)
    52  }
    53  
    54  func (c *connectionPool) Get() *connection {
    55  	conn := c.internalPool.Get()
    56  	if conn != nil {
    57  		conn.inboundBuffer = ringbuffer.Get()
    58  		conn.outboundBuffer = ringbuffer.Get()
    59  
    60  		return conn
    61  	}
    62  
    63  	return newConnection()
    64  }
    65  
    66  func newConnectionPool() *connectionPool {
    67  	return &connectionPool{
    68  		internalPool: sync.NewPool[*connection](),
    69  	}
    70  }