6 * The bulk of this software is derived from Plan 9 and is thus distributed
7 * under the Lucent Public License, Version 1.02, reproduced below.
9 * ===================================================================
11 * Lucent Public License Version 1.02
13 * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS PUBLIC
14 * LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE
15 * PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
19 * "Contribution" means:
21 * a. in the case of Lucent Technologies Inc. ("LUCENT"), the Original
23 * b. in the case of each Contributor,
25 * i. changes to the Program, and
26 * ii. additions to the Program;
28 * where such changes and/or additions to the Program were added to the
29 * Program by such Contributor itself or anyone acting on such
30 * Contributor's behalf, and the Contributor explicitly consents, in
31 * accordance with Section 3C, to characterization of the changes and/or
32 * additions as Contributions.
34 * "Contributor" means LUCENT and any other entity that has Contributed a
35 * Contribution to the Program.
37 * "Distributor" means a Recipient that distributes the Program,
38 * modifications to the Program, or any part thereof.
40 * "Licensed Patents" mean patent claims licensable by a Contributor
41 * which are necessarily infringed by the use or sale of its Contribution
42 * alone or when combined with the Program.
44 * "Original Program" means the original version of the software
45 * accompanying this Agreement as released by LUCENT, including source
46 * code, object code and documentation, if any.
48 * "Program" means the Original Program and Contributions or any part
51 * "Recipient" means anyone who receives the Program under this
52 * Agreement, including all Contributors.
56 * a. Subject to the terms of this Agreement, each Contributor hereby
57 * grants Recipient a non-exclusive, worldwide, royalty-free copyright
58 * license to reproduce, prepare derivative works of, publicly display,
59 * publicly perform, distribute and sublicense the Contribution of such
60 * Contributor, if any, and such derivative works, in source code and
63 * b. Subject to the terms of this Agreement, each Contributor hereby
64 * grants Recipient a non-exclusive, worldwide, royalty-free patent
65 * license under Licensed Patents to make, use, sell, offer to sell,
66 * import and otherwise transfer the Contribution of such Contributor, if
67 * any, in source code and object code form. The patent license granted
68 * by a Contributor shall also apply to the combination of the
69 * Contribution of that Contributor and the Program if, at the time the
70 * Contribution is added by the Contributor, such addition of the
71 * Contribution causes such combination to be covered by the Licensed
72 * Patents. The patent license granted by a Contributor shall not apply
73 * to (i) any other combinations which include the Contribution, nor to
74 * (ii) Contributions of other Contributors. No hardware per se is
77 * c. Recipient understands that although each Contributor grants the
78 * licenses to its Contributions set forth herein, no assurances are
79 * provided by any Contributor that the Program does not infringe the
80 * patent or other intellectual property rights of any other entity. Each
81 * Contributor disclaims any liability to Recipient for claims brought by
82 * any other entity based on infringement of intellectual property rights
83 * or otherwise. As a condition to exercising the rights and licenses
84 * granted hereunder, each Recipient hereby assumes sole responsibility
85 * to secure any other intellectual property rights needed, if any. For
86 * example, if a third party patent license is required to allow
87 * Recipient to distribute the Program, it is Recipient's responsibility
88 * to acquire that license before distributing the Program.
90 * d. Each Contributor represents that to its knowledge it has sufficient
91 * copyright rights in its Contribution, if any, to grant the copyright
92 * license set forth in this Agreement.
96 * A. Distributor may choose to distribute the Program in any form under
97 * this Agreement or under its own license agreement, provided that:
99 * a. it complies with the terms and conditions of this Agreement;
101 * b. if the Program is distributed in source code or other tangible
102 * form, a copy of this Agreement or Distributor's own license agreement
103 * is included with each copy of the Program; and
105 * c. if distributed under Distributor's own license agreement, such
108 * i. effectively disclaims on behalf of all Contributors all warranties
109 * and conditions, express and implied, including warranties or
110 * conditions of title and non-infringement, and implied warranties or
111 * conditions of merchantability and fitness for a particular purpose;
112 * ii. effectively excludes on behalf of all Contributors all liability
113 * for damages, including direct, indirect, special, incidental and
114 * consequential damages, such as lost profits; and
115 * iii. states that any provisions which differ from this Agreement are
116 * offered by that Contributor alone and not by any other party.
118 * B. Each Distributor must include the following in a conspicuous
119 * location in the Program:
121 * Copyright (C) 2003, Lucent Technologies Inc. and others. All Rights
124 * C. In addition, each Contributor must identify itself as the
125 * originator of its Contribution in a manner that reasonably allows
126 * subsequent Recipients to identify the originator of the Contribution.
127 * Also, each Contributor must agree that the additions and/or changes
128 * are intended to be a Contribution. Once a Contribution is contributed,
129 * it may not thereafter be revoked.
131 * 4. COMMERCIAL DISTRIBUTION
133 * Commercial distributors of software may accept certain
134 * responsibilities with respect to end users, business partners and the
135 * like. While this license is intended to facilitate the commercial use
136 * of the Program, the Distributor who includes the Program in a
137 * commercial product offering should do so in a manner which does not
138 * create potential liability for Contributors. Therefore, if a
139 * Distributor includes the Program in a commercial product offering,
140 * such Distributor ("Commercial Distributor") hereby agrees to defend
141 * and indemnify every Contributor ("Indemnified Contributor") against
142 * any losses, damages and costs (collectively"Losses") arising from
143 * claims, lawsuits and other legal actions brought by a third party
144 * against the Indemnified Contributor to the extent caused by the acts
145 * or omissions of such Commercial Distributor in connection with its
146 * distribution of the Program in a commercial product offering. The
147 * obligations in this section do not apply to any claims or Losses
148 * relating to any actual or alleged intellectual property infringement.
149 * In order to qualify, an Indemnified Contributor must: a) promptly
150 * notify the Commercial Distributor in writing of such claim, and b)
151 * allow the Commercial Distributor to control, and cooperate with the
152 * Commercial Distributor in, the defense and any related settlement
153 * negotiations. The Indemnified Contributor may participate in any such
154 * claim at its own expense.
156 * For example, a Distributor might include the Program in a commercial
157 * product offering, Product X. That Distributor is then a Commercial
158 * Distributor. If that Commercial Distributor then makes performance
159 * claims, or offers warranties related to Product X, those performance
160 * claims and warranties are such Commercial Distributor's responsibility
161 * alone. Under this section, the Commercial Distributor would have to
162 * defend claims against the Contributors related to those performance
163 * claims and warranties, and if a court requires any Contributor to pay
164 * any damages as a result, the Commercial Distributor must pay those
169 * EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
170 * PROVIDED ON AN"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
171 * KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
172 * WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
173 * OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
174 * responsible for determining the appropriateness of using and
175 * distributing the Program and assumes all risks associated with its
176 * exercise of rights under this Agreement, including but not limited to
177 * the risks and costs of program errors, compliance with applicable
178 * laws, damage to or loss of data, programs or equipment, and
179 * unavailability or interruption of operations.
181 * 6. DISCLAIMER OF LIABILITY
183 * EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR
184 * ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
185 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
186 * WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
187 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
188 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
189 * DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
190 * HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
194 * Recipient agrees that Recipient alone is responsible for compliance
195 * with the United States export administration regulations (and the
196 * export control laws and regulation of any other countries).
200 * If any provision of this Agreement is invalid or unenforceable under
201 * applicable law, it shall not affect the validity or enforceability of
202 * the remainder of the terms of this Agreement, and without further
203 * action by the parties hereto, such provision shall be reformed to the
204 * minimum extent necessary to make such provision valid and enforceable.
206 * If Recipient institutes patent litigation against a Contributor with
207 * respect to a patent applicable to software (including a cross-claim or
208 * counterclaim in a lawsuit), then any patent licenses granted by that
209 * Contributor to such Recipient under this Agreement shall terminate as
210 * of the date such litigation is filed. In addition, if Recipient
211 * institutes patent litigation against any entity (including a
212 * cross-claim or counterclaim in a lawsuit) alleging that the Program
213 * itself (excluding combinations of the Program with other software or
214 * hardware) infringes such Recipient's patent(s), then such Recipient's
215 * rights granted under Section 2(b) shall terminate as of the date such
216 * litigation is filed.
218 * All Recipient's rights under this Agreement shall terminate if it
219 * fails to comply with any of the material terms or conditions of this
220 * Agreement and does not cure such failure in a reasonable period of
221 * time after becoming aware of such noncompliance. If all Recipient's
222 * rights under this Agreement terminate, Recipient agrees to cease use
223 * and distribution of the Program as soon as reasonably practicable.
224 * However, Recipient's obligations under this Agreement and any licenses
225 * granted by Recipient relating to the Program shall continue and
228 * LUCENT may publish new versions (including revisions) of this
229 * Agreement from time to time. Each new version of the Agreement will be
230 * given a distinguishing version number. The Program (including
231 * Contributions) may always be distributed subject to the version of the
232 * Agreement under which it was received. In addition, after a new
233 * version of the Agreement is published, Contributor may elect to
234 * distribute the Program (including its Contributions) under the new
235 * version. No one other than LUCENT has the right to modify this
236 * Agreement. Except as expressly stated in Sections 2(a) and 2(b) above,
237 * Recipient receives no rights or licenses to the intellectual property
238 * of any Contributor under this Agreement, whether expressly, by
239 * implication, estoppel or otherwise. All rights in the Program not
240 * expressly granted under this Agreement are reserved.
242 * This Agreement is governed by the laws of the State of New York and
243 * the intellectual property laws of the United States of America. No
244 * party to this Agreement will bring a legal action under this Agreement
245 * more than one year after the cause of action arose. Each party waives
246 * its rights to a jury trial in any resulting litigation.
266 struct line *file[2];
267 struct line *sfile[2]; // shortened by pruning common prefix and suffix
269 int pref, suff; // length of prefix and suffix
270 int *class; // will be overlaid on file[0]
271 int *member; // will be overlaid on file[1]
272 int *klist; // will be overlaid on file[0] after class
273 struct cand *clist; // merely a free storage pot for candidates
275 int *J; // will be overlaid on class
278 #define low(x) (x&((1L<<HALFLONG)-1))
279 #define high(x) (x>>HALFLONG)
282 * Returns a computed hash for a given string.
283 * Hashing has the effect of arranging line in 7-bit bytes and then summing 1-s
284 * complement in 16-bit hunks.
285 * @param line The line of a buffer to hash.
287 static int hash(char *line) {
298 sum += (long)*p++ << (shift &= (HALFLONG-1));
301 sum = low(sum) + high(sum);
302 return ((short)low(sum) + (short)high(sum));
306 * Hashes each line in the given string buffer and stores it internally.
307 * @param i 0 for diff 'from', 1 for diff 'to'.
308 * @param buf The string buffer to prepare from.
310 void prepare(int i, const char *buf) {
313 char bufcpy[strlen(buf)];
316 p = malloc(3*sizeof(struct line));
318 strncpy(bufcpy, buf, strlen(buf));
319 bufcpy[strlen(buf)] = 0;
320 l = strtok(bufcpy, "\n");
322 p = realloc(p, (++j+3)*sizeof(struct line));
323 p[j].value = hash(l);
324 l = strtok(NULL, "\n");
331 * Adds to the count of lines added and removed for this diff.
332 * Diff 'from' chunks are counted as lines removed and diff 'to' chunks are
333 * counted as lines added.
334 * @param a The diff 'from' chunk's beginning line number.
335 * @param b The diff 'from' chunk's ending line number.
336 * @param c The diff 'to' chunk's beginning line number.
337 * @param d The diff 'to' chunk's ending line number.
338 * @param added Int pointer to the running number of lines added for this diff.
339 * @param removed Int pointer to the running number of lines removed for this
342 void change(int a, int b, int c, int d, int *added, int *removed) {
351 *removed += b - a + 1;
362 * diff - differential file comparison
364 * Uses an algorithm due to Harold Stone, which finds
365 * a pair of longest identical subsequences in the two
368 * The major goal is to generate the match vector J.
369 * J[i] is the index of the line in file1 corresponding
370 * to line i file0. J[i] = 0 if there is no
371 * such line in file1.
373 * Lines are hashed so as to work in core. All potential
374 * matches are located by sorting the lines of each file
375 * on the hash (called value). In particular, this
376 * collects the equivalence classes in file1 together.
377 * Subroutine equiv replaces the value of each line in
378 * file0 by the index of the first element of its
379 * matching equivalence in (the reordered) file1.
380 * To save space equiv squeezes file1 into a single
381 * array member in which the equivalence classes
382 * are simply concatenated, except that their first
383 * members are flagged by changing sign.
385 * Next the indices that point into member are unsorted into
386 * array class according to the original order of file0.
388 * The cleverness lies in routine stone. This marches
389 * through the lines of file0, developing a vector klist
390 * of "k-candidates". At step i a k-candidate is a matched
391 * pair of lines x,y (x in file0 y in file1) such that
392 * there is a common subsequence of lenght k
393 * between the first i lines of file0 and the first y
394 * lines of file1, but there is no such subsequence for
395 * any smaller y. x is the earliest possible mate to y
396 * that occurs in such a subsequence.
398 * Whenever any of the members of the equivalence class of
399 * lines in file1 matable to a line in file0 has serial number
400 * less than the y of some k-candidate, that k-candidate
401 * with the smallest such y is replaced. The new
402 * k-candidate is chained (via pred) to the current
403 * k-1 candidate so that the actual subsequence can
404 * be recovered. When a member has serial number greater
405 * that the y of all k-candidates, the klist is extended.
406 * At the end, the longest subsequence is pulled out
407 * and placed in the array J by unravel.
409 * With J in hand, the matches there recorded are
410 * check'ed against reality to assure that no spurious
411 * matches have crept in due to hashing. If they have,
412 * they are broken, and "jackpot " is recorded--a harmless
413 * matter except that a true match for a spuriously
414 * mated line may now be unnecessarily reported as a change.
416 * Much of the complexity of the program comes simply
417 * from trying to minimize core utilization and
418 * maximize the range of doable problems by dynamically
419 * allocating what is needed and reusing what is not.
420 * The core requirements for problems larger than somewhat
421 * are (in words) 2*length(file0) + length(file1) +
422 * 3*(number of k-candidates installed), typically about
423 * 6n words for files of length n.
426 static void sort(struct line *a, int n) { /*shellsort CACM #201*/
428 struct line *ai, *aim, *j, *k;
433 for (i = 1; i <= n; i *= 2)
435 for (m /= 2; m != 0; m /= 2) {
437 for (j = a+1; j <= k; j++) {
441 if (aim->value > ai->value ||
442 aim->value == ai->value &&
443 aim->serial > ai->serial)
451 } while (ai > a && aim >= ai);
456 static void unsort(struct line *f, int l, int *b) {
460 a = malloc((l+1)*sizeof(int));
462 a[f[i].serial] = f[i].value;
468 static void prune(void) {
471 for(pref=0;pref<len[0]&&pref<len[1]&&
472 file[0][pref+1].value==file[1][pref+1].value;
474 for(suff=0;suff<len[0]-pref&&suff<len[1]-pref&&
475 file[0][len[0]-suff].value==file[1][len[1]-suff].value;
478 sfile[j] = file[j]+pref;
479 slen[j] = len[j]-pref-suff;
480 for(i=0;i<=slen[j];i++)
481 sfile[j][i].serial = i;
485 static void equiv(struct line *a, int n, struct line *b, int m, int *c) {
489 while(i<=n && j<=m) {
490 if(a[i].value < b[j].value)
492 else if(a[i].value == b[j].value)
503 while(b[j+1].value == b[j].value) {
511 static int newcand(int x, int y, int pred) {
514 clist = realloc(clist, (clen+1)*sizeof(struct cand));
522 static int search(int *c, int k, int y) {
526 if(clist[c[k]].y < y) /*quick look for typical case*/
530 while((l=(i+j)/2) > i) {
542 static int stone(int *a, int n, int *b, int *c) {
549 c[0] = newcand(0,0,0);
550 for(i=1; i<=n; i++) {
558 if(y <= clist[oldc].y)
564 if(clist[c[l]].y <= y)
567 c[l] = newcand(i,y,oldc);
571 c[l] = newcand(i,y,oldc);
575 } while((y=b[++j]) > 0);
580 static void unravel(int p) {
584 for(i=0; i<=len[0]; i++) {
587 else if (i > len[0]-suff)
588 J[i] = i+len[1]-len[0];
592 for(q=clist+p;q->y!=0;q=clist+q->pred)
593 J[q->x+pref] = q->y+pref;
596 static void output(int *added, int *removed) {
597 int m, i0, i1, j0, j1;
602 for (i0 = 1; i0 <= m; i0 = i1+1) {
603 while (i0 <= m && J[i0] == J[i0-1]+1)
607 while (i1 < m && J[i1+1] == 0)
611 change(i0, i1, j0, j1, added, removed);
614 change(1, 0, 1, len[1], added, removed);
617 // create and return the path of a tmp_file filled with buf
618 // caller must delete file if that's desired
619 char *tmp_file_from_buf(const char *buf) {
620 char *template = "/tmp/ohcount_diff_XXXXXXX";
621 char *path = strdup(template);
623 int fd = mkstemp(path);
624 write(fd, buf, strlen(buf));
633 void ohcount_calc_diff_with_disk(
638 *added = *removed = 0;
639 char *from_tmp = tmp_file_from_buf(from);
640 char *to_tmp = tmp_file_from_buf(to);
643 sprintf(command, "diff -d --normal --suppress-common-lines --new-file '%s' '%s'", from_tmp, to_tmp);
644 FILE *f = popen(command, "r");
647 while(fgets(line, sizeof(line), f)) {
655 if (unlink(from_tmp)) {
656 printf("error unlinking %s: %d", from_tmp, errno);
658 if (unlink(to_tmp)) {
659 printf("error unlinking %s: %d", from_tmp, errno);
663 #define USE_DISK_IF_LARGER 100000
664 void ohcount_calc_diff(const char *from,
665 const char *to, int *added, int *removed) {
668 if (strlen(from) > USE_DISK_IF_LARGER || strlen(to) > USE_DISK_IF_LARGER)
669 return ohcount_calc_diff_with_disk(from, to, added, removed);
675 sort(sfile[0], slen[0]);
676 sort(sfile[1], slen[1]);
678 member = (int *)file[1];
679 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
680 member = realloc(member, (slen[1]+2)*sizeof(int));
682 class = (int *)file[0];
683 unsort(sfile[0], slen[0], class);
684 class = realloc(class, (slen[0]+2)*sizeof(int));
686 klist = malloc((slen[0]+2)*sizeof(int));
687 clist = malloc(sizeof(struct cand));
688 k = stone(class, slen[0], member, klist);
692 J = malloc((len[0]+2)*sizeof(int));
697 *added = *removed = 0;
698 output(added, removed);