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.
learn_mqtt_go/clock/clock.go

63 lines
1.9 KiB
Go

package clock
// VectorClock type is used for determining the partial ordering of events in a distributed system.
type VectorClock struct {
clock []int
}
// 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() []int {
clock := make([]int, len(vc.clock))
copy(clock, vc.clock)
return clock
}
// 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 int) *VectorClock {
return &VectorClock{
clock: make([]int, 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 []int: 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 []int) *VectorClock {
vc := &VectorClock{
clock: make([]int, len(a)),
}
copy(vc.clock, a)
return vc
}