Skip to content

Commit

Permalink
add cos.Builder (micro-optimizations)
Browse files Browse the repository at this point in the history
* separately, cos.BytePack to return unsafe string

Signed-off-by: Alex Aizman <[email protected]>
  • Loading branch information
alex-aizman committed Jan 3, 2025
1 parent c6ed50b commit 1226101
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
4 changes: 2 additions & 2 deletions cmn/cos/bytepack.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Package cos provides common low-level types and utilities for all aistore projects
/*
* Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2018-2025, NVIDIA CORPORATION. All rights reserved.
*/
package cos

Expand Down Expand Up @@ -195,7 +195,7 @@ func (br *ByteUnpack) ReadString() (string, error) {
if err != nil {
return "", err
}
return string(bytes), nil
return UnsafeS(bytes), nil
}

func (br *ByteUnpack) ReadAny(st Unpacker) error {
Expand Down
39 changes: 39 additions & 0 deletions cmn/cos/sbuilder.go
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...) }

0 comments on commit 1226101

Please sign in to comment.