util/xpool: package pool
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
		
							
								
								
									
										25
									
								
								util/xpool/pool.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								util/xpool/pool.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,25 @@ | |||||||
|  | package pool | ||||||
|  |  | ||||||
|  | import "sync" | ||||||
|  |  | ||||||
|  | type Pool[T any] struct { | ||||||
|  | 	p *sync.Pool | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func NewPool[T any](fn func() T) Pool[T] { | ||||||
|  | 	return Pool[T]{ | ||||||
|  | 		p: &sync.Pool{ | ||||||
|  | 			New: func() interface{} { | ||||||
|  | 				return fn() | ||||||
|  | 			}, | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (p Pool[T]) Get() T { | ||||||
|  | 	return p.p.Get().(T) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (p Pool[T]) Put(t T) { | ||||||
|  | 	p.p.Put(t) | ||||||
|  | } | ||||||
							
								
								
									
										27
									
								
								util/xpool/pool_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										27
									
								
								util/xpool/pool_test.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,27 @@ | |||||||
|  | package pool | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"bytes" | ||||||
|  | 	"strings" | ||||||
|  | 	"testing" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func TestBytes(t *testing.T) { | ||||||
|  | 	p := NewPool(func() *bytes.Buffer { return bytes.NewBuffer(nil) }) | ||||||
|  | 	b := p.Get() | ||||||
|  | 	b.Write([]byte(`test`)) | ||||||
|  | 	if b.String() != "test" { | ||||||
|  | 		t.Fatal("pool not works") | ||||||
|  | 	} | ||||||
|  | 	p.Put(b) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestStrings(t *testing.T) { | ||||||
|  | 	p := NewPool(func() *strings.Builder { return &strings.Builder{} }) | ||||||
|  | 	b := p.Get() | ||||||
|  | 	b.Write([]byte(`test`)) | ||||||
|  | 	if b.String() != "test" { | ||||||
|  | 		t.Fatal("pool not works") | ||||||
|  | 	} | ||||||
|  | 	p.Put(b) | ||||||
|  | } | ||||||
		Reference in New Issue
	
	Block a user