Commits

Eric Roshan Eisner committed ca71c78 Draft

demo/sshuf: numeric sorting

  • Participants
  • Parent commits 9babe0c

Comments (0)

Files changed (1)

 	decryption    = flag.Bool("d", false, "Extract and decrypt hidden data.")
 	plaintextFile = flag.String("p", "", "Optional source of plaintext data.")
 	outfile       = flag.String("o", "", "Optional output file.")
+	numeric       = flag.Bool("n", false, "Compare according to string numerical value.")
 	// TODO:
-	// numeric = flag.Bool("n", false, "Compare according to string numerical value.")
 	// inputRange = flag.Bool("i", false, "(LO-HI) Treat each number LO HI as input line")
 	// delim = flag.String("e", "\n", "Line delimiter")
 )
 	os.Exit(1)
 }
 
+func parse(line []byte) (num int64) {
+	for i, b := range line {
+		if b < '0' || '9' < b {
+			if i == 0 {
+				fail("could not find a number in a line")
+			}
+			break
+		}
+		num *= 10
+		num += int64(b)
+	}
+	return
+}
+
 // getInputList reads the input to memory, then returns a slice of lineslices
 // pointing into this list.
 func getInputList() sort.Interface {
 	}
 
 	// Assemble slice of lineslices
+	if *numeric {
+		var lines []intbytes
+		prev := 0
+		for i := 0; i < len(input); i++ {
+			if input[i] == delim {
+				line := input[prev:i]
+				lines = append(lines, intbytes{parse(line), line})
+				prev = i + 1
+			}
+		}
+		if prev != len(input) {
+			line := input[prev:len(input)]
+			lines = append(lines, intbytes{parse(line), line})
+		}
+		return ibslice(lines)
+	}
 	var lines [][]byte
 	prev := 0
 	for i := 0; i < len(input); i++ {
 		b := bufio.NewWriter(outstream)
 		defer b.Flush()
 
-		endline := []byte{delim}
-		for _, line := range lines.(byteslice) {
-			b.Write(line)
-			b.Write(endline)
+		switch ls := lines.(type) {
+		case byteslice:
+			for _, line := range ls {
+				b.Write(line)
+				b.WriteByte(delim)
+			}
+		case ibslice:
+			for _, line := range ls {
+				b.Write(line.b)
+				b.WriteByte(delim)
+			}
 		}
 	}
 }
 func (b byteslice) Len() int           { return len(b) }
 func (b byteslice) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }
 func (b byteslice) Less(i, j int) bool { return bytes.Compare(b[i], b[j]) < 0 }
+
+type intbytes struct {
+	n int64
+	b []byte
+}
+type ibslice []intbytes
+
+func (s ibslice) Len() int           { return len(s) }
+func (s ibslice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
+func (s ibslice) Less(i, j int) bool { return s[i].n < s[j].n }