Skip to content
Snippets Groups Projects
Commit dc31b5bd authored by capossele's avatar capossele
Browse files

:sparkles: adds Float64()

parent b7a3eb44
Branches
Tags
No related merge requests found
package state package state
import ( import (
"encoding/binary"
"sync" "sync"
"time" "time"
...@@ -13,6 +14,11 @@ type Randomness struct { ...@@ -13,6 +14,11 @@ type Randomness struct {
Timestamp time.Time Timestamp time.Time
} }
// Float64 returns a float64 [0.0,1.0) rapresentation of the randomness byte slice
func (r Randomness) Float64() float64 {
return float64(binary.BigEndian.Uint64(r.Randomness[:8])>>11) / (1 << 53)
}
type Committee struct { type Committee struct {
InstanceID uint32 InstanceID uint32
Threshold uint8 Threshold uint8
...@@ -21,7 +27,7 @@ type Committee struct { ...@@ -21,7 +27,7 @@ type Committee struct {
} }
type State struct { type State struct {
randomness *Randomness randomness *Randomness
committe *Committee committee *Committee
mutex sync.RWMutex mutex sync.RWMutex
} }
...@@ -34,7 +40,7 @@ func New(setters ...Option) *State { ...@@ -34,7 +40,7 @@ func New(setters ...Option) *State {
} }
return &State{ return &State{
randomness: args.Randomness, randomness: args.Randomness,
committe: args.Committee, committee: args.Committee,
} }
} }
...@@ -56,14 +62,14 @@ func (s *State) Randomness() Randomness { ...@@ -56,14 +62,14 @@ func (s *State) Randomness() Randomness {
func (s *State) SetCommittee(c *Committee) { func (s *State) SetCommittee(c *Committee) {
s.mutex.Lock() s.mutex.Lock()
defer s.mutex.Unlock() defer s.mutex.Unlock()
s.committe = c s.committee = c
} }
func (s *State) Committee() Committee { func (s *State) Committee() Committee {
s.mutex.RLock() s.mutex.RLock()
defer s.mutex.RUnlock() defer s.mutex.RUnlock()
if s.committe == nil { if s.committee == nil {
return Committee{} return Committee{}
} }
return *s.committe return *s.committee
} }
...@@ -40,3 +40,12 @@ func TestState(t *testing.T) { ...@@ -40,3 +40,12 @@ func TestState(t *testing.T) {
stateTest.SetRandomness(newRandomness) stateTest.SetRandomness(newRandomness)
require.Equal(t, *newRandomness, stateTest.Randomness()) require.Equal(t, *newRandomness, stateTest.Randomness())
} }
func TestFloat64(t *testing.T) {
max := []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
r := &Randomness{1, max, time.Now()}
stateTest := New(SetRandomness(r))
require.Equal(t, 0.9999999999999999, stateTest.Randomness().Float64())
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment