Browse Source

Merge pull request #23 from tendermint/hexfuncs

IsHex and StripHex
pull/1842/head
Ethan Buchman 8 years ago
committed by GitHub
parent
commit
462243e31a
1 changed files with 24 additions and 0 deletions
  1. +24
    -0
      common/string.go

+ 24
- 0
common/string.go View File

@ -1,12 +1,15 @@
package common package common
import ( import (
"encoding/hex"
"fmt" "fmt"
"strings" "strings"
) )
// Fmt shorthand, XXX DEPRECATED
var Fmt = fmt.Sprintf var Fmt = fmt.Sprintf
// RightPadString adds spaces to the right of a string to make it length totalLength
func RightPadString(s string, totalLength int) string { func RightPadString(s string, totalLength int) string {
remaining := totalLength - len(s) remaining := totalLength - len(s)
if remaining > 0 { if remaining > 0 {
@ -15,6 +18,7 @@ func RightPadString(s string, totalLength int) string {
return s return s
} }
// LeftPadString adds spaces to the left of a string to make it length totalLength
func LeftPadString(s string, totalLength int) string { func LeftPadString(s string, totalLength int) string {
remaining := totalLength - len(s) remaining := totalLength - len(s)
if remaining > 0 { if remaining > 0 {
@ -22,3 +26,23 @@ func LeftPadString(s string, totalLength int) string {
} }
return s return s
} }
// IsHex returns true for non-empty hex-string prefixed with "0x"
func IsHex(s string) bool {
if len(s) > 2 && s[:2] == "0x" {
_, err := hex.DecodeString(s[2:])
if err != nil {
return false
}
return true
}
return false
}
// StripHex returns hex string without leading "0x"
func StripHex(s string) string {
if IsHex(s) {
return s[2:]
}
return s
}

Loading…
Cancel
Save