Closed
Description
An extremely common string operation is testing if a string is blank and if so replacing it with a default value. I propose adding First(...strings) string
to package strings (and probably an equivalent to bytes for parity, although it is less useful).
// First returns the first non-blank string from its arguments.
func First(ss ...string) string {
for _, s := range ss {
if s != "" {
return s
}
}
return ""
}
Here are three example simplifications from just archive/tar because it shows up first alphabetically when I searched the standard library:
archive/tar diff
diff --git a/src/archive/tar/reader.go b/src/archive/tar/reader.go
index cfa50446ed..bc3489227f 100644
--- a/src/archive/tar/reader.go
+++ b/src/archive/tar/reader.go
@@ -136,12 +136,8 @@ func (tr *Reader) next() (*Header, error) {
if err := mergePAX(hdr, paxHdrs); err != nil {
return nil, err
}
- if gnuLongName != "" {
- hdr.Name = gnuLongName
- }
- if gnuLongLink != "" {
- hdr.Linkname = gnuLongLink
- }
+ hdr.Name = strings.First(gnuLongName, hdr.Name)
+ hdr.Linkname = strings.First(gnuLongLink, hdr.Linkname)
if hdr.Typeflag == TypeRegA {
if strings.HasSuffix(hdr.Name, "/") {
hdr.Typeflag = TypeDir // Legacy archives use trailing slash for directories
@@ -235,13 +231,8 @@ func (tr *Reader) readGNUSparsePAXHeaders(hdr *Header) (sparseDatas, error) {
hdr.Format.mayOnlyBe(FormatPAX)
// Update hdr from GNU sparse PAX headers.
- if name := hdr.PAXRecords[paxGNUSparseName]; name != "" {
- hdr.Name = name
- }
- size := hdr.PAXRecords[paxGNUSparseSize]
- if size == "" {
- size = hdr.PAXRecords[paxGNUSparseRealSize]
- }
+ hdr.Name = strings.First(hdr.PAXRecords[paxGNUSparseName], hdr.Name)
+ size := strings.First(hdr.PAXRecords[paxGNUSparseSize], hdr.PAXRecords[paxGNUSparseRealSize])
if size != "" {
n, err := strconv.ParseInt(size, 10, 64)
if err != nil {
diff --git a/src/archive/tar/writer.go b/src/archive/tar/writer.go
index 1c95f0738a..e9c635a02e 100644
--- a/src/archive/tar/writer.go
+++ b/src/archive/tar/writer.go
@@ -188,10 +188,7 @@ func (tw *Writer) writePAXHeader(hdr *Header, paxHdrs map[string]string) error {
var name string
var flag byte
if isGlobal {
- name = realName
- if name == "" {
- name = "GlobalHead.0.0"
- }
+ name = strings.First(realName, "GlobalHead.0.0")
flag = TypeXGlobalHeader
} else {
dir, file := path.Split(realName)