github.com/qioalice/ekago/v3@v3.3.2-0.20221202205325-5c262d586ee4/internal/ekaletter/extra.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 ekaletter
     7  
     8  // PrintfVerbsCount reports how much printf verbs 'format' has.
     9  //
    10  // Also fixes 'format' if it's has some incorrect things like e.g.
    11  // no-escaped last percent, etc.
    12  func PrintfVerbsCount(format *string) (verbsCount int) {
    13  
    14  	if format == nil || *format == "" {
    15  		return
    16  	}
    17  
    18  	// because Golang uses UTF8, log messages can be written not using just ASCII.
    19  	// yes, yes, I agree, it's some piece of shit, but who knows?
    20  	// Because of that this loop is so ugly.
    21  
    22  	// Golang promises, that for-range loop of string splits it to runes
    23  	// (and runes could be UTF8 characters).
    24  
    25  	prevWasPercent := false
    26  	for _, char := range *format {
    27  
    28  		switch {
    29  		case char != '%' && prevWasPercent:
    30  			// prev char was a percent but current's one isn't
    31  			// looks like printf verb
    32  			verbsCount++
    33  			prevWasPercent = false
    34  
    35  		case char == '%' && prevWasPercent:
    36  			// prev char was a percent but current's one also too
    37  			// looks like percent escaping
    38  			prevWasPercent = false
    39  
    40  		case char == '%' && !prevWasPercent:
    41  			// prev char wasn't a percent but current's one is
    42  			// it could be a printf verb, but we don't know exactly at this moment
    43  			prevWasPercent = true
    44  
    45  		case char != '%' && !prevWasPercent:
    46  			// just a common regular character, do nothing
    47  		}
    48  	}
    49  
    50  	// fix format string if last char was a percent (and there is EOL)
    51  	if prevWasPercent {
    52  		*format += "%"
    53  	}
    54  
    55  	return
    56  }