-
Notifications
You must be signed in to change notification settings - Fork 183
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add
cos.Builder
(micro-optimizations)
* separately, cos.BytePack to return unsafe string Signed-off-by: Alex Aizman <[email protected]>
- Loading branch information
1 parent
c6ed50b
commit 1226101
Showing
2 changed files
with
41 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
// Package cos provides common low-level types and utilities for all aistore projects | ||
/* | ||
* Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. | ||
*/ | ||
package cos | ||
|
||
import ( | ||
"unsafe" | ||
) | ||
|
||
// implementation: | ||
// - reusable, single-threaded, best-effort, and once-allocated | ||
// motivation: | ||
// - to optimally replace `strings.Builder` when applicable | ||
|
||
type Builder struct { | ||
buf []byte | ||
} | ||
|
||
func (b *Builder) String() string { | ||
return unsafe.String(unsafe.SliceData(b.buf), len(b.buf)) | ||
} | ||
|
||
func (b *Builder) Reset(size int) { | ||
switch { | ||
case b.buf == nil: | ||
b.buf = make([]byte, 0, size) | ||
case len(b.buf) >= size-size>>1: // vs. previous usage | ||
b.buf = make([]byte, 0, size<<1) | ||
default: | ||
b.buf = b.buf[:0] | ||
} | ||
} | ||
|
||
func (b *Builder) Len() int { return len(b.buf) } | ||
func (b *Builder) Cap() int { return cap(b.buf) } | ||
|
||
func (b *Builder) WriteByte(c byte) { b.buf = append(b.buf, c) } | ||
func (b *Builder) WriteString(s string) { b.buf = append(b.buf, s...) } |