File: char.go

package info (click to toggle)
golang-github-poy-onpar 0.3.3-1.1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 456 kB
  • sloc: makefile: 3
file content (305 lines) | stat: -rw-r--r-- 6,908 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package str

import (
	"context"
	"sync"
)

func greaterBaseCost(a, b []rune) float64 {
	if len(a) > len(b) {
		return float64(len(a))
	}
	return float64(len(b))
}

type charDiff struct {
	baseCost    float64
	perCharCost float64

	cost     float64
	sections []DiffSection
}

func (d *charDiff) calculate() {
	d.cost = 0
	for _, s := range d.sections {
		if s.Type == TypeMatch {
			continue
		}
		d.cost += d.baseCost + d.perCharCost*greaterBaseCost(s.Actual, s.Expected)
	}
}

func (d *charDiff) Cost() float64 {
	return d.cost
}

func (d *charDiff) Sections() []DiffSection {
	return d.sections
}

// broadcast is a type which can broadcast new diffs to multiple subscribers.
type broadcast struct {
	mu sync.Mutex

	closed bool
	curr   Diff
	subs   []chan Diff
}

// subscribe subscribes to an existing broadcast, returning a channel to listen
// for changes on. The current value will be sent on the channel immediately.
func (b *broadcast) subscribe() chan Diff {
	ch := make(chan Diff, 1)
	b.mu.Lock()
	defer b.mu.Unlock()
	b.subs = append(b.subs, ch)

	if b.curr != nil {
		ch <- b.curr
	}
	if b.closed {
		close(ch)
	}
	return ch
}

// send sends d to all subscribers and updates the current value for new
// subscribers.
func (b *broadcast) send(ctx context.Context, d Diff) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.curr = d

	for _, s := range b.subs {
		select {
		case s <- d:
		case <-ctx.Done():
			return
		}
	}
}

// done signals that b has exhausted all possibilities and all subscribers
// should be closed.
func (b *broadcast) done() {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.closed = true
	for _, s := range b.subs {
		close(s)
	}
}

type diffIdx struct {
	aStart, eStart int
}

// CharDiffOpt is an option function for changing the behavior of the
// NewCharDiff constructor.
type CharDiffOpt func(CharDiff) CharDiff

// CharDiffBaseCost is a CharDiff option to set the base cost per diff section.
// Increasing this will reduce the number of diff sections in the output at the
// cost of larger diff sections.
//
// Default is 0.
func CharDiffBaseCost(cost float64) CharDiffOpt {
	return func(d CharDiff) CharDiff {
		d.baseCost = cost
		return d
	}
}

// CharDiffPerCharCost is a CharDiff option to set the cost-per-character of any
// differences returned. Increasing this cost will reduce the size of diff
// sections at the cost of more diff sections.
//
// Default is 1
func CharDiffPerCharCost(cost float64) CharDiffOpt {
	return func(d CharDiff) CharDiff {
		d.perCharCost = cost
		return d
	}
}

// CharDiff is a per-character diff algorithm, meaning that it makes no distinctions
// about word or line boundaries when generating a diff.
type CharDiff struct {
	baseCost    float64
	perCharCost float64
}

func NewCharDiff(opts ...CharDiffOpt) *CharDiff {
	d := CharDiff{
		baseCost:    0,
		perCharCost: 1,
	}
	for _, o := range opts {
		d = o(d)
	}
	return &d
}

func (c *CharDiff) Diffs(ctx context.Context, actual, expected []rune) <-chan Diff {
	ch := make(chan Diff)
	var m sync.Map
	go c.sendDiffs(ctx, ch, &m, actual, expected, 0, 0)
	return ch
}

func (c *CharDiff) sendBestResults(ctx context.Context, ch chan<- Diff, bcast *broadcast, baseSections []DiffSection) {
	defer close(ch)

	subCh := bcast.subscribe()
	var cheapest *charDiff
	for {
		select {
		case subDiff, ok := <-subCh:
			if !ok {
				return
			}
			diff := &charDiff{
				baseCost:    c.baseCost,
				perCharCost: c.perCharCost,
				sections:    append([]DiffSection(nil), baseSections...),
			}
			diff.sections = append(diff.sections, subDiff.Sections()...)
			diff.calculate()
			if cheapest == nil || cheapest.Cost() > diff.Cost() {
				cheapest = diff
				select {
				case ch <- cheapest:
				case <-ctx.Done():
					return
				}
			}
		case <-ctx.Done():
			return
		}
	}
}

func (c *CharDiff) runBroadcast(ctx context.Context, bcast *broadcast, ch <-chan Diff, actual, expected []rune, actualStart, expectedStart int) {
	defer bcast.done()

	base := &charDiff{
		baseCost:    c.baseCost,
		perCharCost: c.perCharCost,
		sections: []DiffSection{
			{Type: TypeReplace, Actual: actual[actualStart:], Expected: expected[expectedStart:]},
		},
	}
	base.calculate()
	shortest := Diff(base)
	bcast.send(ctx, shortest)

	if ctx.Err() != nil {
		return
	}

	for diff := range ch {
		if ctx.Err() != nil {
			return
		}
		if diff.Cost() >= shortest.Cost() {
			continue
		}
		shortest = diff
		bcast.send(ctx, shortest)
	}
}

func (c *CharDiff) sendSubDiffs(ctx context.Context, wg *sync.WaitGroup, subCh <-chan Diff, results chan<- Diff, section DiffSection) {
	defer wg.Done()

	for {
		select {
		case subDiff, ok := <-subCh:
			if !ok {
				return
			}
			diff := &charDiff{
				baseCost:    c.baseCost,
				perCharCost: c.perCharCost,
				sections:    append([]DiffSection{section}, subDiff.Sections()...),
			}
			diff.calculate()
			select {
			case results <- diff:
			case <-ctx.Done():
				return
			}
		case <-ctx.Done():
			return
		}
	}
}

func (c *CharDiff) sendDiffs(ctx context.Context, ch chan<- Diff, cache *sync.Map, actual, expected []rune, actualStart, expectedStart int) {
	actualEnd, expectedEnd := actualStart, expectedStart
	for actualEnd < len(actual) && expectedEnd < len(expected) && actual[actualEnd] == expected[expectedEnd] {
		actualEnd++
		expectedEnd++
	}
	if actualEnd == len(actual) && expectedEnd == len(expected) {
		if actualEnd-actualStart > 0 || expectedEnd-expectedStart > 0 {
			diff := &charDiff{
				baseCost:    c.baseCost,
				perCharCost: c.perCharCost,
				sections:    []DiffSection{{Type: TypeMatch, Actual: actual[actualStart:actualEnd], Expected: expected[expectedStart:expectedEnd]}},
			}
			select {
			case ch <- diff:
			case <-ctx.Done():
			}
		}
		close(ch)
		return
	}
	bcast := &broadcast{}
	cached, running := cache.LoadOrStore(diffIdx{aStart: actualEnd, eStart: expectedEnd}, bcast)
	bcast = cached.(*broadcast)

	var baseSections []DiffSection
	if actualEnd-actualStart > 0 || expectedEnd-expectedStart > 0 {
		baseSections = []DiffSection{
			{Type: TypeMatch, Actual: actual[actualStart:actualEnd], Expected: expected[expectedStart:expectedEnd]},
		}
	}
	go c.sendBestResults(ctx, ch, bcast, baseSections)

	if running {
		return
	}

	subCh := make(chan Diff)
	go c.runBroadcast(ctx, bcast, subCh, actual, expected, actualEnd, expectedEnd)

	var wg sync.WaitGroup
	for i := actualEnd; i < len(actual); i++ {
		for j := expectedEnd; j < len(expected); j++ {
			if ctx.Err() != nil {
				return
			}
			if actual[i] != expected[j] {
				continue
			}
			subSubCh := make(chan Diff)
			wg.Add(1)
			go c.sendSubDiffs(ctx, &wg, subSubCh, subCh, DiffSection{
				Type:     TypeReplace,
				Actual:   actual[actualEnd:i],
				Expected: expected[expectedEnd:j],
			})
			c.sendDiffs(ctx, subSubCh, cache, actual, expected, i, j)
		}
	}

	go closeAfter(subCh, &wg)
}

func closeAfter(ch chan<- Diff, wg *sync.WaitGroup) {
	wg.Wait()
	close(ch)
}