package lattice // TritPath packs up to 16 trits, two bits each; trit 0 is the branch selector. // iskradb/lattice/coord.mx TritPath, which is the 16-wide form the storage // layer uses. iskra/branch.mx redeclares a second TritPath with the same name // but an 8-trit depth in the same package; the two cannot both be ported. type TritPath uint32 // TritEnd is the terminator trit value. const TritEnd = 0 // Trit returns the trit at position i. func (p TritPath) Trit(i int) uint8 { return uint8((p >> (uint(i) * 2)) & 0x3) } // Depth is the number of assigned trits before the first TritEnd. func (p TritPath) Depth() int { for i := 0; i < 16; i++ { if p.Trit(i) == TritEnd { return i } } return 16 } // Branch returns the branch selector trit. func (p TritPath) Branch() uint8 { return p.Trit(0) } // MakeTritPath builds a TritPath from trit values 0-3. func MakeTritPath(trits ...uint8) TritPath { var p TritPath for i, t := range trits { if i >= 16 { break } p |= TritPath(t&0x3) << (uint(i) * 2) } return p } // BranchTritPath returns a path holding only the branch selector. func BranchTritPath(b Branch) TritPath { return TritPath(b) + 1 } // Parent drops the last trit of a path. func Parent(p TritPath) TritPath { d := p.Depth() if d <= 1 { return 0 } return p &^ (TritPath(0x3) << (uint(d-1) * 2)) } // Child appends a trit to a path. func Child(p TritPath, dir uint8) TritPath { d := p.Depth() if d >= 16 { return p } return p | TritPath(dir&0x3)<<(uint(d)*2) } // LCA returns the longest common prefix of two paths. func LCA(a, b TritPath) TritPath { shared := sharedPrefix(a, b) if shared == 0 { return 0 } return a & TritPath((1<<(uint(shared)*2))-1) } // Distance is the hop count between two paths through their common prefix. // Returns -1 when either path is unassigned (depth 0). func Distance(a, b TritPath) int { da, db := a.Depth(), b.Depth() if da == 0 || db == 0 { return -1 } shared := sharedPrefix(a, b) return (da - shared) + (db - shared) } // Resolve replicates every trit after the branch selector mult times. func Resolve(p TritPath, mult uint8) TritPath { if mult <= 1 { return p } d := p.Depth() if d <= 1 { return p } out := TritPath(p.Trit(0)) pos := 1 for i := 1; i < d; i++ { t := p.Trit(i) for j := uint8(0); j < mult && pos < 16; j++ { out |= TritPath(t&0x3) << (uint(pos) * 2) pos++ } } return out } func sharedPrefix(a, b TritPath) int { da, db := a.Depth(), b.Depth() limit := da if db < limit { limit = db } shared := 0 for i := 0; i < limit; i++ { if a.Trit(i) != b.Trit(i) { break } shared++ } return shared } // Code-lattice branch constants. iskra/branch.mx. const ( BranchType = 1 BranchFunc = 2 BranchData = 3 SubField = 1 SubMethod = 2 SubEmbed = 3 SubStatement = 1 SubExpression = 2 SubControl = 3 SubConst = 1 SubVar = 2 SubImport = 3 )