]> Sergey Matveev's repositories - rutrackerer.git/blob - cmd/search/main.go
Less gob calls -- several times faster search
[rutrackerer.git] / cmd / search / main.go
1 package main
2
3 import (
4         "bufio"
5         "encoding/gob"
6         "encoding/hex"
7         "fmt"
8         "os"
9         "os/exec"
10         "strconv"
11         "strings"
12
13         "github.com/dustin/go-humanize"
14         "go.stargrave.org/rutrackerer"
15 )
16
17 func main() {
18         cmd := exec.Command("grep", append([]string{"-n"}, os.Args[1:]...)...)
19         grepStdin, err := cmd.StdinPipe()
20         if err != nil {
21                 panic(err)
22         }
23         grepStdout, err := cmd.StdoutPipe()
24         if err != nil {
25                 panic(err)
26         }
27         if err = cmd.Start(); err != nil {
28                 panic(err)
29         }
30         var torrents []*rutrackerer.Torrent
31         gobDec := gob.NewDecoder(bufio.NewReader(os.Stdin))
32         if err = gobDec.Decode(&torrents); err != nil {
33                 panic(err)
34         }
35         printer := make(chan struct{})
36         go func() {
37                 scanner := bufio.NewScanner(grepStdout)
38                 var t string
39                 var i int
40                 var err error
41                 var torrent *rutrackerer.Torrent
42                 for scanner.Scan() {
43                         t = scanner.Text()
44                         i = strings.IndexByte(t, ':')
45                         i, err = strconv.Atoi(t[:i])
46                         if err != nil {
47                                 panic(err)
48                         }
49                         torrent = torrents[i-1]
50                         fmt.Printf(
51                                 `%s
52         %s %s %d
53         https://rutracker.org/forum/viewtopic.php?t=%d
54         magnet:?xt=urn:btih:%s
55 `,
56                                 torrent.Title,
57                                 torrent.Registered.Format("2006-01-02T15:04:05"),
58                                 humanize.IBytes(uint64(torrent.Size)),
59                                 torrent.Offset,
60                                 torrent.Id,
61                                 strings.ToUpper(hex.EncodeToString(torrent.Hash[:])),
62                         )
63                 }
64                 if err = scanner.Err(); err != nil {
65                         panic(err)
66                 }
67                 close(printer)
68         }()
69         for _, t := range torrents {
70                 if _, err = grepStdin.Write([]byte(t.Title + "\n")); err != nil {
71                         panic(err)
72                 }
73         }
74         grepStdin.Close()
75         <-printer
76         if err = cmd.Wait(); err != nil {
77                 panic(err)
78         }
79 }