2024-10-03 10:51:39 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
2024-10-03 12:28:33 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/vmihailenco/msgpack"
|
|
|
|
"github.com/klauspost/compress/zstd"
|
2024-10-03 10:51:39 +02:00
|
|
|
)
|
|
|
|
|
2024-10-03 12:28:33 +02:00
|
|
|
func loadPrimes(useTxt bool) []int64 {
|
|
|
|
if useTxt {
|
|
|
|
return loadPrimesTxt()
|
|
|
|
} else {
|
|
|
|
return loadPrimesMsgpack()
|
|
|
|
}
|
2024-10-03 10:51:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func loadPrimesTxt() []int64 {
|
2024-10-03 12:28:33 +02:00
|
|
|
file := must(os.Open("prime.txt"))
|
|
|
|
defer file.Close()
|
2024-10-03 10:51:39 +02:00
|
|
|
|
|
|
|
var primes []int64
|
|
|
|
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
|
|
|
|
|
|
for scanner.Scan() {
|
2024-10-03 12:28:33 +02:00
|
|
|
nextPrime := must(strconv.ParseInt(scanner.Text(), 10, 64))
|
2024-10-03 10:51:39 +02:00
|
|
|
primes = append(primes, nextPrime)
|
|
|
|
}
|
|
|
|
|
|
|
|
return primes
|
|
|
|
}
|
|
|
|
|
2024-10-03 12:28:33 +02:00
|
|
|
func loadPrimesMsgpack() []int64 {
|
|
|
|
file := must(os.Open("prime.msgpack.zst"))
|
|
|
|
defer file.Close()
|
2024-10-03 10:51:39 +02:00
|
|
|
|
2024-10-03 12:28:33 +02:00
|
|
|
zstdDecoder := must(zstd.NewReader(file))
|
|
|
|
defer zstdDecoder.Close()
|
|
|
|
|
|
|
|
var primes []int64
|
|
|
|
msgpackDecoder := msgpack.NewDecoder(zstdDecoder)
|
|
|
|
err := msgpackDecoder.Decode(&primes)
|
2024-10-03 10:51:39 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2024-10-03 12:28:33 +02:00
|
|
|
return primes
|
|
|
|
}
|
|
|
|
|
|
|
|
func writePrimes(primes []int64, useTxt bool) {
|
|
|
|
startTime := time.Now()
|
|
|
|
|
|
|
|
if useTxt {
|
|
|
|
writePrimesTxt(primes)
|
|
|
|
} else {
|
|
|
|
writePrimesMsgpack(primes)
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Printf("File writing took %v\n", time.Now().Sub(startTime))
|
|
|
|
}
|
|
|
|
|
|
|
|
func writePrimesTxt(primes []int64) {
|
|
|
|
file := must(os.Create("prime.txt"))
|
|
|
|
defer file.Close()
|
|
|
|
|
2024-10-03 10:51:39 +02:00
|
|
|
writer := bufio.NewWriter(file)
|
|
|
|
|
|
|
|
for _, prime := range primes {
|
|
|
|
writer.WriteString(fmt.Sprintf("%d\n", prime))
|
|
|
|
}
|
|
|
|
|
|
|
|
writer.Flush()
|
2024-10-03 12:28:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func writePrimesMsgpack(primes []int64) {
|
|
|
|
file := must(os.Create("prime.msgpack.zst"))
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
zstdEncoder := must(zstd.NewWriter(file, zstd.WithEncoderLevel(zstd.SpeedBestCompression)))
|
|
|
|
defer zstdEncoder.Close()
|
|
|
|
|
|
|
|
msgpackEncoder := msgpack.NewEncoder(zstdEncoder)
|
|
|
|
err := msgpackEncoder.Encode(&primes)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2024-10-03 10:51:39 +02:00
|
|
|
}
|