Merge pull request 'primetime' (#2) from primetime into master

Reviewed-on: https://git.fputs.com/fputs/protohackers/pulls/2
This commit is contained in:
Evan Burkey 2022-11-07 20:26:46 +01:00
commit bc17b6befc
3 changed files with 89 additions and 22 deletions

52
cmd/primetime/main.go Normal file
View File

@ -0,0 +1,52 @@
package main
import (
"bufio"
"encoding/json"
"log"
"math/big"
"net"
"protohackers/pkg/conn"
)
var (
malformedResponse = []byte("malformed\n")
trueResponse = []byte(`{"method":"isPrime","prime":true}` + "\n")
falseResponse = []byte(`{"method":"isPrime","prime":false}` + "\n")
)
type data struct {
Method string `json:"method"`
Number *float64 `json:"number"`
}
func main() {
err := conn.StartSimple(primetime)
if err != nil {
log.Fatalln(err)
}
}
func primetime(c net.Conn) {
defer c.Close()
sc := bufio.NewScanner(c)
for sc.Scan() {
response := process(sc.Bytes())
c.Write(response)
}
if err := sc.Err(); err != nil {
log.Fatalln(err)
}
}
func process(buf []byte) []byte {
var in data
err := json.Unmarshal(buf, &in)
if err != nil || in.Method != "isPrime" || in.Number == nil {
return malformedResponse
} else if big.NewInt(int64(*in.Number)).ProbablyPrime(0) {
return trueResponse
}
return falseResponse
}

View File

@ -1,40 +1,23 @@
package main package main
import ( import (
"fmt"
"io" "io"
"log" "log"
"net" "net"
"os"
)
const ( "protohackers/pkg/conn"
connPort = "3030"
connType = "tcp4"
) )
func main() { func main() {
l, err := net.Listen(connType, ":"+connPort) err := conn.StartSimple(smoketest)
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
defer l.Close()
fmt.Println(fmt.Sprintf("Listening on port %s", connPort))
for {
conn, err := l.Accept()
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
go handleRequest(conn)
}
} }
func handleRequest(conn net.Conn) { func smoketest(c net.Conn) {
defer conn.Close() defer c.Close()
if _, err := io.Copy(conn, conn); err != nil { if _, err := io.Copy(c, c); err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
} }

32
pkg/conn/conn.go Normal file
View File

@ -0,0 +1,32 @@
package conn
import (
"fmt"
"net"
)
const (
Port = ":3030"
Type = "tcp4"
)
func StartSimple(handler func(conn net.Conn)) error {
l, err := net.Listen(Type, Port)
if err != nil {
return err
}
defer l.Close()
fmt.Println(fmt.Sprintf("Listening on port %s", Port))
for {
c, err := l.Accept()
if err != nil {
return err
}
go handler(c)
if err != nil {
return err
}
}
}