optimize loop logic; reduce redundant checks in XXDReverse

This commit is contained in:
raf 2024-06-07 16:56:01 +03:00
parent 30e0aa5549
commit fea3864961
No known key found for this signature in database
GPG key ID: 02D1DD3FA08B6B29
2 changed files with 24 additions and 44 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
# ignore built binary
hexxy

View file

@ -27,86 +27,64 @@ func XXDReverse(r io.Reader, w io.Writer) error {
octs = 2 octs = 2
} }
if opts.Len != -1 { if opts.Len != -1 && opts.Len < int64(cols) {
if opts.Len < int64(cols) { cols = int(opts.Len)
cols = int(opts.Len)
}
} }
if octs < 1 { if octs < 1 {
octs = cols octs = cols
} }
// character count
c := int64(0) c := int64(0)
rd := bufio.NewReader(r) rd := bufio.NewReader(r)
for { for {
// TODO this is causing issues with plain
line, err := rd.ReadBytes('\n') line, err := rd.ReadBytes('\n')
n := len(line) if err != nil && !errors.Is(err, io.EOF) {
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
return fmt.Errorf("hexxy: %v", err) return fmt.Errorf("hexxy: %v", err)
} }
if n == 0 { if len(line) == 0 {
return nil return nil
} }
if dumpType == dumpHex { n := len(line)
for i := 0; n >= octs; { i := 0
for i < n {
if i+octs > n {
break
}
switch dumpType {
case dumpHex, dumpCformat:
if rv, _ := hexDecode(char, line[i:i+octs]); rv == 0 { if rv, _ := hexDecode(char, line[i:i+octs]); rv == 0 {
w.Write(char) w.Write(char)
i += 2 i += octs
n -= 2
c++ c++
} else if rv == -1 { } else if rv == -1 {
i++ i++
n--
} else { } else {
// rv == -2
i += 2 i += 2
n -= 2
} }
} case dumpBinary:
} else if dumpType == dumpBinary { if binaryDecode(char, line[i:i+octs]) == -1 {
for i := 0; n >= octs; {
if binaryDecode(char, line[i:i+octs]) != -1 {
i++ i++
n--
continue
} else { } else {
w.Write(char) w.Write(char)
i += 8 i += octs
n -= 8
c++ c++
} }
} case dumpPlain:
} else if dumpType == dumpPlain {
for i := 0; n >= octs; i++ {
if rv, _ := hexDecode(char, line[i:i+octs]); rv != 0 { if rv, _ := hexDecode(char, line[i:i+octs]); rv != 0 {
w.Write(char) w.Write(char)
c++ c++
} }
n-- i++
}
} else if dumpType == dumpCformat {
for i := 0; n >= octs; {
if rv, _ := hexDecode(char, line[i:i+octs]); rv == 0 {
w.Write(char)
i += 4
n -= 4
c++
} else if rv == -1 {
i++
n--
} else { // rv == -2
i += 2
n -= 2
}
} }
} }
if c == int64(cols) && cols > 0 { if c >= int64(cols) && cols > 0 {
return nil return nil
} }
} }