github.com/haraldrudell/parl@v0.4.176/pstrings/fit-value-and-label.go (about) 1 /* 2 © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package pstrings 7 8 import "strings" 9 10 // fitValueAndLabel trums a value and its label to fit into width 11 // - if pad is true and result shorter than width, s is padded with spaces to reach width 12 func FitValueAndLabel(width int, value, label string, pad bool) (s string) { 13 if width == 0 { 14 return 15 } 16 lengthValue := len([]rune(value)) 17 lengthLabel := len([]rune(label)) 18 19 // no cutting case 20 if lengthValue+lengthLabel+1 <= width { 21 s = value + "\x20" + label 22 if pad { 23 if padLength := width - (lengthValue + lengthLabel + 1); padLength > 0 { 24 s += strings.Repeat("\x20", padLength) 25 } 26 } 27 return 28 } 29 30 // value and label case: at least 1 character label 31 if lengthValue+2 <= width { 32 s = value + "\x20" + Fit(label, width-lengthValue-1, pad) 33 return 34 } 35 36 // value alone case 37 s = Fit(value, width, pad) 38 return 39 }