go_subnetter/cmd/subnetter/funcs_tblfmt.go

65 lines
1.3 KiB
Go

package main
import (
`fmt`
`strings`
)
func padStr(str string, colSize uint8) (out string) {
var fill int
var lFill int
var rFill int
var strLen int = len(str)
// EZPZ. Exact match.
if strLen+fixedPad == int(colSize) {
out = fmt.Sprintf(
"%s%s%s",
strings.Repeat(padChars, fixedPad/2), str, strings.Repeat(padChars, fixedPad/2),
)
return
}
// This is where it gets... annoying.
fill = int(colSize) - (strLen + fixedPad)
if fill%2 == 0 {
/*
Split evenly left/right.
This condition will be met if BOTH strLen and colSize are even,
or if BOTH strLen and colSize are odd.
Math!
*/
lFill = fill / 2
rFill = fill / 2
} else {
// Either the value or the width is odd, and the other is even.
// (Note: Goland automatically floors an int/int calculation's result.)
// As such, asymmetrical padding is needed.
if strLen%2 == 0 {
/*
String is even, width is odd.
Favor (smaller fill) the left.
*/
lFill = fill / 2
rFill = (fill + 1) / 2 // This works instead of math.Ceil because dividing by 2.
} else {
/*
String is odd, width is even.
Favor right pad.
*/
lFill = (fill + 1) / 2
rFill = fill / 2
}
}
out = fmt.Sprintf(
"%s%s%s",
strings.Repeat(padChars, lFill+fixedPad/2),
str,
strings.Repeat(padChars, rFill+fixedPad/2),
)
return
}