github.com/qioalice/ekago/v3@v3.3.2-0.20221202205325-5c262d586ee4/ekalog/extra_private.go (about)

     1  // Copyright © 2020. All rights reserved.
     2  // Author: Ilya Stroy.
     3  // Contacts: iyuryevich@pm.me, https://github.com/qioalice
     4  // License: https://opensource.org/licenses/MIT
     5  
     6  package ekalog
     7  
     8  import (
     9  	"strings"
    10  )
    11  
    12  // hpm is "has prefix many" just like strings.HasPrefix,
    13  // but you can check many prefixes at the same time.
    14  func hpm(verb string, prefixes []string) bool {
    15  	for _, prefix := range prefixes {
    16  		if strings.HasPrefix(verb, prefix) {
    17  			return true
    18  		}
    19  	}
    20  	return false
    21  }
    22  
    23  // bufgr is buffer grow - a function that takes some buffer 'buf',
    24  // and checks whether it has at least 'required' free bytes. Returns 'buf' if it so.
    25  // Otherwise creates a new buffer, with X as a new capacity, where:
    26  //
    27  // 		X ~= 'cap(buf) * 1.5 + required', but can be more,
    28  //
    29  // and copies all data from 'buf' to a new buffer, then returns it.
    30  func bufgr(buf []byte, required int) []byte {
    31  
    32  	if cap(buf)-len(buf) >= required {
    33  		return buf
    34  	}
    35  	// https://github.com/golang/go/wiki/SliceTricks#extend
    36  	return append(buf, make([]byte, required+cap(buf)/2)...)[:len(buf)]
    37  
    38  	// TODO: Maybe strict and guarantee that new cap === required + cap(buf) * 1.5?
    39  	//  ATM Golang may reserve a few bytes for internal prediction purpose I guess.
    40  }
    41  
    42  // bufw writes 'text' to 'buf', growing 'buf' if it's need to write 'text'.
    43  // Returns grown 'buf' (if it has been grown) or originally 'buf'.
    44  // So, it's recommend to use it func like Golang's one 'append'.
    45  func bufw(buf []byte, text string) []byte {
    46  	return append(bufgr(buf, len(text)), text...)
    47  }
    48  
    49  // bufw2 writes 'raw' to 'buf', growing 'buf' if it's need to write 'raw'.
    50  // Returns grown 'buf' (if it has been grown) or originally 'buf'.
    51  // So, it's recommend to use it func like Golang's one 'append'.
    52  func bufw2(buf, raw []byte) []byte {
    53  	return append(bufgr(buf, len(raw)), raw...)
    54  }
    55  
    56  // bufwc adds 'c' to 'buf', growing 'buf' if it's required to write that byte.
    57  // Returns grown 'buf' (if it's so) or originally 'buf'.
    58  // Use this function as Golang's append().
    59  //
    60  // It's a new function. In the old code a bufw or a bufw2 still may be used
    61  // to write a single byte. Replace them by this function.
    62  func bufwc(buf []byte, c byte) []byte {
    63  	return append(bufgr(buf, 1), c)
    64  }