summaryrefslogtreecommitdiff
path: root/lib/diff/lcs.rb
blob: 8ae85be4b523b46394f0b85912e99c6ce897fa8d (plain)
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
# -*- ruby encoding: utf-8 -*-

module Diff
  # = Diff::LCS 1.1.3
  # Computes "intelligent" differences between two sequenced Enumerables.
  # This is an implementation of the McIlroy-Hunt "diff" algorithm for
  # Enumerable objects that include Diffable.
  #
  # Based on Mario I. Wolczko's Smalltalk version (1.2, 1993) and Ned Konz's
  # Perl version (Algorithm::Diff 1.15).
  #
  # == Synopsis
  #   require 'diff/lcs'
  #
  #   seq1 = %w(a b c e h j l m n p)
  #   seq2 = %w(b c d e f j k l m r s t)
  #
  #   lcs = Diff::LCS.LCS(seq1, seq2)
  #   diffs = Diff::LCS.diff(seq1, seq2)
  #   sdiff = Diff::LCS.sdiff(seq1, seq2)
  #   seq = Diff::LCS.traverse_sequences(seq1, seq2, callback_obj)
  #   bal = Diff::LCS.traverse_balanced(seq1, seq2, callback_obj)
  #   seq2 == Diff::LCS.patch(seq1, diffs)
  #   seq2 == Diff::LCS.patch!(seq1, diffs)
  #   seq1 == Diff::LCS.unpatch(seq2, diffs)
  #   seq1 == Diff::LCS.unpatch!(seq2, diffs)
  #   seq2 == Diff::LCS.patch(seq1, sdiff)
  #   seq2 == Diff::LCS.patch!(seq1, sdiff)
  #   seq1 == Diff::LCS.unpatch(seq2, sdiff)
  #   seq1 == Diff::LCS.unpatch!(seq2, sdiff)
  #
  # Alternatively, objects can be extended with Diff::LCS:
  #
  #   seq1.extend(Diff::LCS)
  #   lcs = seq1.lcs(seq2)
  #   diffs = seq1.diff(seq2)
  #   sdiff = seq1.sdiff(seq2)
  #   seq = seq1.traverse_sequences(seq2, callback_obj)
  #   bal = seq1.traverse_balanced(seq2, callback_obj)
  #   seq2 == seq1.patch(diffs)
  #   seq2 == seq1.patch!(diffs)
  #   seq1 == seq2.unpatch(diffs)
  #   seq1 == seq2.unpatch!(diffs)
  #   seq2 == seq1.patch(sdiff)
  #   seq2 == seq1.patch!(sdiff)
  #   seq1 == seq2.unpatch(sdiff)
  #   seq1 == seq2.unpatch!(sdiff)
  #
  # Default extensions are provided for Array and String objects through the
  # use of 'diff/lcs/array' and 'diff/lcs/string'.
  #
  # == Introduction (by Mark-Jason Dominus)
  #
  # <em>The following text is from the Perl documentation. The only changes
  # have been to make the text appear better in Rdoc</em>.
  #
  # I once read an article written by the authors of +diff+; they said that
  # they hard worked very hard on the algorithm until they found the right
  # one.
  #
  # I think what they ended up using (and I hope someone will correct me,
  # because I am not very confident about this) was the `longest common
  # subsequence' method. In the LCS problem, you have two sequences of
  # items:
  #
  #    a b c d f g h j q z
  #    a b c d e f g i j k r x y z
  #
  # and you want to find the longest sequence of items that is present in
  # both original sequences in the same order. That is, you want to find a
  # new sequence *S* which can be obtained from the first sequence by
  # deleting some items, and from the second sequence by deleting other
  # items. You also want *S* to be as long as possible. In this case *S* is:
  #
  #    a b c d f g j z
  #
  # From there it's only a small step to get diff-like output:
  #
  #    e   h i   k   q r x y
  #    +   - +   +   - + + +
  #
  # This module solves the LCS problem. It also includes a canned function
  # to generate +diff+-like output.
  #
  # It might seem from the example above that the LCS of two sequences is
  # always pretty obvious, but that's not always the case, especially when
  # the two sequences have many repeated elements. For example, consider
  #
  #    a x b y c z p d q
  #    a b c a x b y c z
  #
  # A naive approach might start by matching up the +a+ and +b+ that appear
  # at the beginning of each sequence, like this:
  #
  #    a x b y c         z p d q
  #    a   b   c a b y c z
  #
  # This finds the common subsequence +a b c z+. But actually, the LCS is
  # +a x b y c z+:
  #
  #          a x b y c z p d q
  #    a b c a x b y c z
  #
  # == Author
  # This version is by Austin Ziegler <austin@rubyforge.org>.
  #
  # It is based on the Perl Algorithm::Diff (1.15) by Ned Konz , copyright
  # &copy; 2000&ndash;2002 and the Smalltalk diff version by Mario I.
  # Wolczko, copyright &copy; 1993. Documentation includes work by
  # Mark-Jason Dominus.
  #
  # == Licence
  # Copyright &copy; 2004 Austin Ziegler
  # This program is free software; you can redistribute it and/or modify it
  # under the same terms as Ruby, or alternatively under the Perl Artistic
  # licence.
  #
  # == Credits
  # Much of the documentation is taken directly from the Perl
  # Algorithm::Diff implementation and was written originally by Mark-Jason
  # Dominus and later by Ned Konz. The basic Ruby implementation was
  # re-ported from the Smalltalk implementation, available at
  # ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st
  #
  # #sdiff and #traverse_balanced were written for the Perl version by Mike
  # Schilli <m@perlmeister.com>.
  #
  # "The algorithm is described in <em>A Fast Algorithm for Computing
  # Longest Common Subsequences</em>, CACM, vol.20, no.5, pp.350-353, May
  # 1977, with a few minor improvements to improve the speed."
  module LCS
    VERSION = '1.1.3'
  end
end

require 'diff/lcs/callbacks'
require 'diff/lcs/internals'

module Diff::LCS
  # Returns an Array containing the longest common subsequence(s) between
  # +self+ and +other+. See Diff::LCS#LCS.
  #
  #   lcs = seq1.lcs(seq2)
  def lcs(other, &block) #:yields self[ii] if there are matched subsequences:
    Diff::LCS.LCS(self, other, &block)
  end

  # Returns the difference set between +self+ and +other+. See
  # Diff::LCS#diff.
  def diff(other, callbacks = nil, &block)
    Diff::LCS.diff(self, other, callbacks, &block)
  end

  # Returns the balanced ("side-by-side") difference set between +self+ and
  # +other+. See Diff::LCS#sdiff.
  def sdiff(other, callbacks = nil, &block)
    Diff::LCS.sdiff(self, other, callbacks, &block)
  end

  # Traverses the discovered longest common subsequences between +self+ and
  # +other+. See Diff::LCS#traverse_sequences.
  def traverse_sequences(other, callbacks = nil, &block)
    traverse_sequences(self, other, callbacks ||
                       Diff::LCS.YieldingCallbacks, &block)
  end

  # Traverses the discovered longest common subsequences between +self+ and
  # +other+ using the alternate, balanced algorithm. See
  # Diff::LCS#traverse_balanced.
  def traverse_balanced(other, callbacks = nil, &block)
    traverse_balanced(self, other, callbacks ||
                      Diff::LCS.YieldingCallbacks, &block)
  end

  # Attempts to patch a copy of +self+ with the provided +patchset+. See
  # Diff::LCS#patch.
  def patch(patchset)
    Diff::LCS.patch(self.dup, patchset)
  end

  # Attempts to unpatch a copy of +self+ with the provided +patchset+. See
  # Diff::LCS#patch.
  def unpatch(patchset)
    Diff::LCS.unpatch(self.dup, patchset)
  end

  # Attempts to patch +self+ with the provided +patchset+. See
  # Diff::LCS#patch!. Does no autodiscovery.
  def patch!(patchset)
    Diff::LCS.patch!(self, patchset)
  end

  # Attempts to unpatch +self+ with the provided +patchset+. See
  # Diff::LCS#unpatch. Does no autodiscovery.
  def unpatch!(patchset)
    Diff::LCS.unpatch!(self, patchset)
  end
end

module Diff::LCS
  class << self
    # Given two sequenced Enumerables, LCS returns an Array containing their
    # longest common subsequences.
    #
    #   lcs = Diff::LCS.LCS(seq1, seq2)
    #
    # This array whose contents is such that:
    #
    #   lcs.each_with_index do |ee, ii|
    #     assert(ee.nil? || (seq1[ii] == seq2[ee]))
    #   end
    #
    # If a block is provided, the matching subsequences will be yielded from
    # +seq1+ in turn and may be modified before they are placed into the
    # returned Array of subsequences.
    def LCS(seq1, seq2, &block) #:yields seq1[ii] for each matched:
      matches = Diff::LCS::Internals.lcs(seq1, seq2)
      ret = []
      matches.each_with_index do |ee, ii|
        unless matches[ii].nil?
          if block_given?
            ret << (yield seq1[ii])
          else
            ret << seq1[ii]
          end
        end
      end
      ret
    end

    # Diff::LCS.diff computes the smallest set of additions and deletions
    # necessary to turn the first sequence into the second, and returns a
    # description of these changes.
    #
    # See Diff::LCS::DiffCallbacks for the default behaviour. An alternate
    # behaviour may be implemented with Diff::LCS::ContextDiffCallbacks. If
    # a Class argument is provided for +callbacks+, #diff will attempt to
    # initialise it. If the +callbacks+ object (possibly initialised)
    # responds to #finish, it will be called.
    def diff(seq1, seq2, callbacks = nil, &block) # :yields diff changes:
      callbacks ||= Diff::LCS::DiffCallbacks
      if callbacks.kind_of?(Class)
        cb = callbacks.new rescue callbacks
        callbacks = cb
      end
      traverse_sequences(seq1, seq2, callbacks)
      callbacks.finish if callbacks.respond_to?(:finish)

      if block_given?
        res = callbacks.diffs.map do |hunk|
          if hunk.kind_of?(Array)
            hunk = hunk.map { |hunk_block| yield hunk_block }
          else
            yield hunk
          end
        end
        res
      else
        callbacks.diffs
      end
    end

    # Diff::LCS.sdiff computes all necessary components to show two sequences
    # and their minimized differences side by side, just like the Unix
    # utility <em>sdiff</em> does:
    #
    #     old        <     -
    #     same             same
    #     before     |     after
    #     -          >     new
    #
    # See Diff::LCS::SDiffCallbacks for the default behaviour. An alternate
    # behaviour may be implemented with Diff::LCS::ContextDiffCallbacks. If
    # a Class argument is provided for +callbacks+, #diff will attempt to
    # initialise it. If the +callbacks+ object (possibly initialised)
    # responds to #finish, it will be called.
    def sdiff(seq1, seq2, callbacks = nil, &block) #:yields diff changes:
      callbacks ||= Diff::LCS::SDiffCallbacks
      if callbacks.kind_of?(Class)
        cb = callbacks.new rescue callbacks
        callbacks = cb
      end
      traverse_balanced(seq1, seq2, callbacks)
      callbacks.finish if callbacks.respond_to?(:finish)

      if block_given?
        res = callbacks.diffs.map do |hunk|
          if hunk.kind_of?(Array)
            hunk = hunk.map { |hunk_block| yield hunk_block }
          else
            yield hunk
          end
        end
        res
      else
        callbacks.diffs
      end
    end

    # Diff::LCS.traverse_sequences is the most general facility provided by this
    # module; +diff+ and +LCS+ are implemented as calls to it.
    #
    # The arguments to #traverse_sequences are the two sequences to
    # traverse, and a callback object, like this:
    #
    #   traverse_sequences(seq1, seq2, Diff::LCS::ContextDiffCallbacks.new)
    #
    # #diff is implemented with #traverse_sequences.
    #
    # == Callback Methods
    # Optional callback methods are <em>emphasized</em>.
    #
    # callbacks#match::               Called when +a+ and +b+ are pointing
    #                                 to common elements in +A+ and +B+.
    # callbacks#discard_a::           Called when +a+ is pointing to an
    #                                 element not in +B+.
    # callbacks#discard_b::           Called when +b+ is pointing to an
    #                                 element not in +A+.
    # <em>callbacks#finished_a</em>:: Called when +a+ has reached the end of
    #                                 sequence +A+.
    # <em>callbacks#finished_b</em>:: Called when +b+ has reached the end of
    #                                 sequence +B+.
    #
    # == Algorithm
    #       a---+
    #           v
    #       A = a b c e h j l m n p
    #       B = b c d e f j k l m r s t
    #           ^
    #       b---+
    #
    # If there are two arrows (+a+ and +b+) pointing to elements of
    # sequences +A+ and +B+, the arrows will initially point to the first
    # elements of their respective sequences. #traverse_sequences will
    # advance the arrows through the sequences one element at a time,
    # calling a method on the user-specified callback object before each
    # advance. It will advance the arrows in such a way that if there are
    # elements <tt>A[ii]</tt> and <tt>B[jj]</tt> which are both equal and
    # part of the longest common subsequence, there will be some moment
    # during the execution of #traverse_sequences when arrow +a+ is pointing
    # to <tt>A[ii]</tt> and arrow +b+ is pointing to <tt>B[jj]</tt>. When
    # this happens, #traverse_sequences will call <tt>callbacks#match</tt>
    # and then it will advance both arrows.
    #
    # Otherwise, one of the arrows is pointing to an element of its sequence
    # that is not part of the longest common subsequence.
    # #traverse_sequences will advance that arrow and will call
    # <tt>callbacks#discard_a</tt> or <tt>callbacks#discard_b</tt>, depending
    # on which arrow it advanced. If both arrows point to elements that are
    # not part of the longest common subsequence, then #traverse_sequences
    # will advance one of them and call the appropriate callback, but it is
    # not specified which it will call.
    #
    # The methods for <tt>callbacks#match</tt>, <tt>callbacks#discard_a</tt>,
    # and <tt>callbacks#discard_b</tt> are invoked with an event comprising
    # the action ("=", "+", or "-", respectively), the indicies +ii+ and
    # +jj+, and the elements <tt>A[ii]</tt> and <tt>B[jj]</tt>. Return
    # values are discarded by #traverse_sequences.
    #
    # === End of Sequences
    # If arrow +a+ reaches the end of its sequence before arrow +b+ does,
    # #traverse_sequence will try to call <tt>callbacks#finished_a</tt> with
    # the last index and element of +A+ (<tt>A[-1]</tt>) and the current
    # index and element of +B+ (<tt>B[jj]</tt>). If
    # <tt>callbacks#finished_a</tt> does not exist, then
    # <tt>callbacks#discard_b</tt> will be called on each element of +B+
    # until the end of the sequence is reached (the call
    # will be done with <tt>A[-1]</tt> and <tt>B[jj]</tt> for each element).
    #
    # If +b+ reaches the end of +B+ before +a+ reaches the end of +A+,
    # <tt>callbacks#finished_b</tt> will be called with the current index
    # and element of +A+ (<tt>A[ii]</tt>) and the last index and element of
    # +B+ (<tt>A[-1]</tt>). Again, if <tt>callbacks#finished_b</tt> does not
    # exist on the callback object, then <tt>callbacks#discard_a</tt> will
    # be called on each element of +A+ until the end of the sequence is
    # reached (<tt>A[ii]</tt> and <tt>B[-1]</tt>).
    #
    # There is a chance that one additional <tt>callbacks#discard_a</tt> or
    # <tt>callbacks#discard_b</tt> will be called after the end of the
    # sequence is reached, if +a+ has not yet reached the end of +A+ or +b+
    # has not yet reached the end of +B+.
    def traverse_sequences(seq1, seq2, callbacks = Diff::LCS::SequenceCallbacks, &block) #:yields change events:
      matches = Diff::LCS::Internals.lcs(seq1, seq2)

      run_finished_a = run_finished_b = false
      string = seq1.kind_of?(String)

      a_size = seq1.size
      b_size = seq2.size
      ai = bj = 0

      (0 .. matches.size).each do |ii|
        b_line = matches[ii]

        ax = string ? seq1[ii, 1] : seq1[ii]
        bx = string ? seq2[bj, 1] : seq2[bj]

        if b_line.nil?
          unless ax.nil? or (string and ax.empty?)
            event = Diff::LCS::ContextChange.new('-', ii, ax, bj, bx)
            event = yield event if block_given?
            callbacks.discard_a(event)
          end
        else
          loop do
            break unless bj < b_line
            bx = string ? seq2[bj, 1] : seq2[bj]
            event = Diff::LCS::ContextChange.new('+', ii, ax, bj, bx)
            event = yield event if block_given?
            callbacks.discard_b(event)
            bj += 1
          end
          bx = string ? seq2[bj, 1] : seq2[bj]
          event = Diff::LCS::ContextChange.new('=', ii, ax, bj, bx)
          event = yield event if block_given?
          callbacks.match(event)
          bj += 1
        end
        ai = ii
      end
      ai += 1

      # The last entry (if any) processed was a match. +ai+ and +bj+ point
      # just past the last matching lines in their sequences.
      while (ai < a_size) or (bj < b_size)
        # last A?
        if ai == a_size and bj < b_size
          if callbacks.respond_to?(:finished_a) and not run_finished_a
            ax = string ? seq1[-1, 1] : seq1[-1]
            bx = string ? seq2[bj, 1] : seq2[bj]
            event = Diff::LCS::ContextChange.new('>', (a_size - 1), ax, bj, bx)
            event = yield event if block_given?
            callbacks.finished_a(event)
            run_finished_a = true
          else
            ax = string ? seq1[ai, 1] : seq1[ai]
            loop do
              bx = string ? seq2[bj, 1] : seq2[bj]
              event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
              event = yield event if block_given?
              callbacks.discard_b(event)
              bj += 1
              break unless bj < b_size
            end
          end
        end

        # last B?
        if bj == b_size and ai < a_size
          if callbacks.respond_to?(:finished_b) and not run_finished_b
            ax = string ? seq1[ai, 1] : seq1[ai]
            bx = string ? seq2[-1, 1] : seq2[-1]
            event = Diff::LCS::ContextChange.new('<', ai, ax, (b_size - 1), bx)
            event = yield event if block_given?
            callbacks.finished_b(event)
            run_finished_b = true
          else
            bx = string ? seq2[bj, 1] : seq2[bj]
            loop do
              ax = string ? seq1[ai, 1] : seq1[ai]
              event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
              event = yield event if block_given?
              callbacks.discard_a(event)
              ai += 1
              break unless bj < b_size
            end
          end
        end

        if ai < a_size
          ax = string ? seq1[ai, 1] : seq1[ai]
          bx = string ? seq2[bj, 1] : seq2[bj]
          event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
          event = yield event if block_given?
          callbacks.discard_a(event)
          ai += 1
        end

        if bj < b_size
          ax = string ? seq1[ai, 1] : seq1[ai]
          bx = string ? seq2[bj, 1] : seq2[bj]
          event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
          event = yield event if block_given?
          callbacks.discard_b(event)
          bj += 1
        end
      end
    end

    # #traverse_balanced is an alternative to #traverse_sequences. It
    # uses a different algorithm to iterate through the entries in the
    # computed longest common subsequence. Instead of viewing the changes as
    # insertions or deletions from one of the sequences, #traverse_balanced
    # will report <em>changes</em> between the sequences. To represent a
    #
    # The arguments to #traverse_balanced are the two sequences to traverse
    # and a callback object, like this:
    #
    #   traverse_balanced(seq1, seq2, Diff::LCS::ContextDiffCallbacks.new)
    #
    # #sdiff is implemented with #traverse_balanced.
    #
    # == Callback Methods
    # Optional callback methods are <em>emphasized</em>.
    #
    # callbacks#match::               Called when +a+ and +b+ are pointing
    #                                 to common elements in +A+ and +B+.
    # callbacks#discard_a::           Called when +a+ is pointing to an
    #                                 element not in +B+.
    # callbacks#discard_b::           Called when +b+ is pointing to an
    #                                 element not in +A+.
    # <em>callbacks#change</em>::     Called when +a+ and +b+ are pointing
    #                                 to the same relative position, but
    #                                 <tt>A[a]</tt> and <tt>B[b]</tt> are
    #                                 not the same; a <em>change</em> has
    #                                 occurred.
    #
    # #traverse_balanced might be a bit slower than #traverse_sequences,
    # noticable only while processing huge amounts of data.
    #
    # The +sdiff+ function of this module is implemented as call to
    # #traverse_balanced.
    #
    # == Algorithm
    #       a---+
    #           v
    #       A = a b c e h j l m n p
    #       B = b c d e f j k l m r s t
    #           ^
    #       b---+
    #
    # === Matches
    # If there are two arrows (+a+ and +b+) pointing to elements of
    # sequences +A+ and +B+, the arrows will initially point to the first
    # elements of their respective sequences. #traverse_sequences will
    # advance the arrows through the sequences one element at a time,
    # calling a method on the user-specified callback object before each
    # advance. It will advance the arrows in such a way that if there are
    # elements <tt>A[ii]</tt> and <tt>B[jj]</tt> which are both equal and
    # part of the longest common subsequence, there will be some moment
    # during the execution of #traverse_sequences when arrow +a+ is pointing
    # to <tt>A[ii]</tt> and arrow +b+ is pointing to <tt>B[jj]</tt>. When
    # this happens, #traverse_sequences will call <tt>callbacks#match</tt>
    # and then it will advance both arrows.
    #
    # === Discards
    # Otherwise, one of the arrows is pointing to an element of its sequence
    # that is not part of the longest common subsequence.
    # #traverse_sequences will advance that arrow and will call
    # <tt>callbacks#discard_a</tt> or <tt>callbacks#discard_b</tt>,
    # depending on which arrow it advanced.
    #
    # === Changes
    # If both +a+ and +b+ point to elements that are not part of the longest
    # common subsequence, then #traverse_sequences will try to call
    # <tt>callbacks#change</tt> and advance both arrows. If
    # <tt>callbacks#change</tt> is not implemented, then
    # <tt>callbacks#discard_a</tt> and <tt>callbacks#discard_b</tt> will be
    # called in turn.
    #
    # The methods for <tt>callbacks#match</tt>, <tt>callbacks#discard_a</tt>,
    # <tt>callbacks#discard_b</tt>, and <tt>callbacks#change</tt> are
    # invoked with an event comprising the action ("=", "+", "-", or "!",
    # respectively), the indicies +ii+ and +jj+, and the elements
    # <tt>A[ii]</tt> and <tt>B[jj]</tt>. Return values are discarded by
    # #traverse_balanced.
    #
    # === Context
    # Note that +ii+ and +jj+ may not be the same index position, even if
    # +a+ and +b+ are considered to be pointing to matching or changed
    # elements.
    def traverse_balanced(seq1, seq2, callbacks = Diff::LCS::BalancedCallbacks)
      matches = Diff::LCS::Internals.lcs(seq1, seq2)
      a_size = seq1.size
      b_size = seq2.size
      ai = bj = mb = 0
      ma = -1
      string = seq1.kind_of?(String)

        # Process all the lines in the match vector.
      loop do
          # Find next match indices +ma+ and +mb+
        loop do
          ma += 1
          break unless ma < matches.size and matches[ma].nil?
        end

        break if ma >= matches.size # end of matches?
        mb = matches[ma]

          # Change(seq2)
        while (ai < ma) or (bj < mb)
          ax = string ? seq1[ai, 1] : seq1[ai]
          bx = string ? seq2[bj, 1] : seq2[bj]

          case [(ai < ma), (bj < mb)]
          when [true, true]
            if callbacks.respond_to?(:change)
              event = Diff::LCS::ContextChange.new('!', ai, ax, bj, bx)
              event = yield event if block_given?
              callbacks.change(event)
              ai += 1
              bj += 1
            else
              event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
              event = yield event if block_given?
              callbacks.discard_a(event)
              ai += 1
              ax = string ? seq1[ai, 1] : seq1[ai]
              event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
              event = yield event if block_given?
              callbacks.discard_b(event)
              bj += 1
            end
          when [true, false]
            event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
            event = yield event if block_given?
            callbacks.discard_a(event)
            ai += 1
          when [false, true]
            event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
            event = yield event if block_given?
            callbacks.discard_b(event)
            bj += 1
          end
        end

        # Match
        ax = string ? seq1[ai, 1] : seq1[ai]
        bx = string ? seq2[bj, 1] : seq2[bj]
        event = Diff::LCS::ContextChange.new('=', ai, ax, bj, bx)
        event = yield event if block_given?
        callbacks.match(event)
        ai += 1
        bj += 1
      end

      while (ai < a_size) or (bj < b_size)
        ax = string ? seq1[ai, 1] : seq1[ai]
        bx = string ? seq2[bj, 1] : seq2[bj]

        case [(ai < a_size), (bj < b_size)]
        when [true, true]
          if callbacks.respond_to?(:change)
            event = Diff::LCS::ContextChange.new('!', ai, ax, bj, bx)
            event = yield event if block_given?
            callbacks.change(event)
            ai += 1
            bj += 1
          else
            event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
            event = yield event if block_given?
            callbacks.discard_a(event)
            ai += 1
            ax = string ? seq1[ai, 1] : seq1[ai]
            event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
            event = yield event if block_given?
            callbacks.discard_b(event)
            bj += 1
          end
        when [true, false]
          event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
          event = yield event if block_given?
          callbacks.discard_a(event)
          ai += 1
        when [false, true]
          event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
          event = yield event if block_given?
          callbacks.discard_b(event)
          bj += 1
        end
      end
    end

    PATCH_MAP = { #:nodoc:
      :patch => { '+' => '+', '-' => '-', '!' => '!', '=' => '=' },
      :unpatch => { '+' => '-', '-' => '+', '!' => '!', '=' => '=' }
    }

    # Applies a +patchset+ to the sequence +src+ according to the
    # +direction+ (<tt>:patch</tt> or <tt>:unpatch</tt>).
    #
    # If the +direction+ is not specified, Diff::LCS::patch will attempt to
    # discover the direction of the +patchset+.
    #
    # A +patchset+ can be considered to apply forward (<tt>:patch</tt>) if
    # the following expression is true:
    #
    #     patch(s1, diff(s1, s2)) -> s2
    #
    # A +patchset+ can be considered to apply backward (<tt>:unpatch</tt>)
    # if the following expression is true:
    #
    #     patch(s2, diff(s1, s2)) -> s1
    #
    # If the +patchset+ contains no changes, the +src+ value will be
    # returned as either <tt>src.dup</tt> or +src+. A +patchset+ can be
    # deemed as having no changes if the following predicate returns true:
    #
    #     patchset.empty? or
    #       patchset.flatten.all? { |change| change.unchanged? }
    #
    # === Patchsets
    # A +patchset+ is always an enumerable sequence of changes, hunks of
    # changes, or a mix of the two. A hunk of changes is an enumerable
    # sequence of changes:
    #
    #     [ # patchset
    #       # change
    #       [ # hunk
    #         # change
    #       ]
    #     ]
    #
    # The +patch+ method accepts <tt>patchset</tt>s that are enumerable
    # sequences containing either Diff::LCS::Change objects (or a subclass)
    # or the array representations of those objects. Prior to application,
    # array representations of Diff::LCS::Change objects will be reified.
    def patch(src, patchset, direction = nil)
      # Normalize the patchset.
      has_changes, patchset = Diff::LCS::Internals.analyze_patchset(patchset)

      if not has_changes
        return src.dup if src.respond_to? :dup
        return src
      end

      string = src.kind_of?(String)
      # Start with a new empty type of the source's class
      res = src.class.new

      direction ||= Diff::LCS::Internals.diff_direction(src, patchset)

      ai = bj = 0

      patch_map = PATCH_MAP[direction]

      patchset.flatten.each do |change|
        # Both Change and ContextChange support #action
        action = patch_map[change.action]

        case change
        when Diff::LCS::ContextChange
          case direction
          when :patch
            el = change.new_element
            op = change.old_position
            np = change.new_position
          when :unpatch
            el = change.old_element
            op = change.new_position
            np = change.old_position
          end

          case action
          when '-' # Remove details from the old string
            while ai < op
              res << (string ? src[ai, 1] : src[ai])
              ai += 1
              bj += 1
            end
            ai += 1
          when '+'
            while bj < np
              res << (string ? src[ai, 1] : src[ai])
              ai += 1
              bj += 1
            end

          res << el
          bj += 1
          when '='
            # This only appears in sdiff output with the SDiff callback.
            # Therefore, we only need to worry about dealing with a single
            # element.
            res << el

            ai += 1
            bj += 1
          when '!'
            while ai < op
              res << (string ? src[ai, 1] : src[ai])
              ai += 1
              bj += 1
            end

          bj += 1
          ai += 1

          res << el
          end
        when Diff::LCS::Change
          case action
          when '-'
            while ai < change.position
              res << (string ? src[ai, 1] : src[ai])
              ai += 1
              bj += 1
            end
            ai += 1
          when '+'
            while bj < change.position
              res << (string ? src[ai, 1] : src[ai])
              ai += 1
              bj += 1
            end

            bj += 1

            res << change.element
          end
        end
      end

      while ai < src.size
        res << (string ? src[ai, 1] : src[ai])
        ai += 1
        bj += 1
      end

      res
    end

    # Given a set of patchset, convert the current version to the prior
    # version. Does no auto-discovery.
    def unpatch!(src, patchset)
      Diff::LCS.patch(src, patchset, :unpatch)
    end

    # Given a set of patchset, convert the current version to the next
    # version. Does no auto-discovery.
    def patch!(src, patchset)
      Diff::LCS.patch(src, patchset, :patch)
    end
  end
end

# vim: ft=ruby