Skip to content

Instantly share code, notes, and snippets.

@zerosign
Created November 14, 2020 07:34
Show Gist options
  • Save zerosign/a0022f99b11b23403e8cb3119bf8c8b3 to your computer and use it in GitHub Desktop.
Save zerosign/a0022f99b11b23403e8cb3119bf8c8b3 to your computer and use it in GitHub Desktop.
// -*- mode:go;mode:go-playground -*-
// snippet of code @ 2020-11-14 14:23:30
// === Go Playground ===
// Execute the snippet with Ctl-Return
// Provide custom arguments to compile with Alt-Return
// Remove the snippet completely with its dir and all files M-x `go-playground-rm`
package main
import (
"crypto/rand"
"time"
"github.com/cnf/structhash"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
type State struct {
Clock time.Time
Hash string `hash:"~"`
}
type ParticipantList struct {
Participants []string
State State
}
func (p *ParticipantList) Modify(modifier func(p *ParticipantList)) error {
modifier(p)
return p.Rehash()
}
func (p *ParticipantList) Rehash() error {
var err error
p.State.Clock = time.Now()
p.State.Hash, err = structhash.Hash(p, 0)
return err
}
func Generate(times int) []string {
data := make([]string, 0)
for ii := 0; ii < times; ii++ {
id, err := uuid.NewRandomFromReader(rand.Reader)
if err != nil {
continue
}
data = append(data, id.String())
}
return data
}
func main() {
participants := ParticipantList{
Participants: Generate(10),
}
log.Debug().Interface("participants", participants).Msg("before rehash")
err := participants.Rehash()
if err != nil {
log.Fatal().Err(err).Send()
}
log.Debug().Interface("participants", participants).Msg("after rehash")
participants.Participants = append(
participants.Participants,
Generate(1)...,
)
err = participants.Rehash()
if err != nil {
log.Fatal().Err(err).Send()
}
err = participants.Modify(func(p *ParticipantList) {
p.Participants = append(
p.Participants,
Generate(2)...,
)
})
if err != nil {
log.Fatal().Err(err).Send()
}
log.Debug().Interface("participants", participants).Msg("after modification")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment