You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.3 KiB
Go
89 lines
2.3 KiB
Go
package clock
|
|
|
|
import (
|
|
"errors"
|
|
)
|
|
|
|
func max(x, y uint) uint {
|
|
if x >= y {
|
|
return x
|
|
} else {
|
|
return y
|
|
}
|
|
}
|
|
|
|
// VectorClock type is used for determining the partial ordering of events in a distributed system.
|
|
type VectorClock struct {
|
|
clock []uint
|
|
}
|
|
|
|
// GetClock returns a copy of the internal vector clock.
|
|
//
|
|
// This method provides a snapshot of the current state of the vector clock
|
|
// without exposing the internal slice directly. By returning a copy, it ensures
|
|
// that the original vector clock remains immutable and prevents unintended
|
|
// modifications to the internal state.
|
|
//
|
|
// Returns:
|
|
//
|
|
// []int: A copy of the internal vector clock slice, where each element
|
|
// represents the logical time for a corresponding process.
|
|
func (vc *VectorClock) GetClock() []uint {
|
|
clock := make([]uint, len(vc.clock))
|
|
copy(clock, vc.clock)
|
|
return clock
|
|
}
|
|
|
|
func (vc *VectorClock) Sync(v VectorClock) ([]uint, error) {
|
|
compClock := v.GetClock()
|
|
|
|
if len(vc.clock) != len(compClock) {
|
|
return nil, errors.New("VectorClocks are of different lengths.")
|
|
}
|
|
|
|
for i := range vc.clock {
|
|
vc.clock[i] = max(vc.clock[i], compClock[i])
|
|
}
|
|
|
|
return vc.GetClock(), nil
|
|
}
|
|
|
|
// NewVectorClock creates a new VectorClock initialized to zero.
|
|
//
|
|
// Parameters:
|
|
//
|
|
// size (int): The number of entries in the vector clock, typically
|
|
// corresponding to the number of processes or nodes.
|
|
//
|
|
// Returns:
|
|
//
|
|
// *VectorClock: A pointer to the newly created VectorClock instance, with all
|
|
// elements of the clock initialized to zero.
|
|
func NewVectorClock(size uint) *VectorClock {
|
|
return &VectorClock{
|
|
clock: make([]uint, size),
|
|
}
|
|
}
|
|
|
|
// ArrayToVectorClock converts an integer array into a VectorClock instance.
|
|
//
|
|
// This function creates a new VectorClock where the internal clock is initialized
|
|
// by copying the values from the provided array. The input array's values are
|
|
// treated as the logical times for each process in the vector clock.
|
|
//
|
|
// Parameters:
|
|
//
|
|
// a []uint: An array of integers representing logical times for each process.
|
|
//
|
|
// Returns:
|
|
//
|
|
// *VectorClock: A pointer to a newly created VectorClock instance where the
|
|
// internal clock is a copy of the provided array.
|
|
func ArrayToVectorClock(a []uint) *VectorClock {
|
|
vc := &VectorClock{
|
|
clock: make([]uint, len(a)),
|
|
}
|
|
copy(vc.clock, a)
|
|
return vc
|
|
}
|