refactor(parser/diff): better compare strings performance
This commit is contained in:
		
							parent
							
								
									b8c233b1bb
								
							
						
					
					
						commit
						be1d697fdb
					
				|  | @ -5,7 +5,6 @@ import ( | ||||||
| 	"log/slog" | 	"log/slog" | ||||||
| 	"os" | 	"os" | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"unicode" |  | ||||||
| 
 | 
 | ||||||
| 	"github.com/joint-online-judge/JOJ3/internal/stage" | 	"github.com/joint-online-judge/JOJ3/internal/stage" | ||||||
| ) | ) | ||||||
|  | @ -111,22 +110,47 @@ func (*Diff) Run(results []stage.ExecutorResult, confAny any) ( | ||||||
| 
 | 
 | ||||||
| // compareStrings compares two strings character by character, optionally ignoring whitespace.
 | // compareStrings compares two strings character by character, optionally ignoring whitespace.
 | ||||||
| func compareStrings(str1, str2 string, compareSpace bool) bool { | func compareStrings(str1, str2 string, compareSpace bool) bool { | ||||||
| 	if !compareSpace { | 	if compareSpace { | ||||||
| 		str1 = removeSpace(str1) |  | ||||||
| 		str2 = removeSpace(str2) |  | ||||||
| 	} |  | ||||||
| 		return str1 == str2 | 		return str1 == str2 | ||||||
| 	} | 	} | ||||||
|  | 	var i, j int | ||||||
|  | 	l1 := len(str1) | ||||||
|  | 	l2 := len(str2) | ||||||
|  | 	for i < l1 && j < l2 { | ||||||
|  | 		for i < l1 && isWhitespace(str1[i]) { | ||||||
|  | 			i++ | ||||||
|  | 		} | ||||||
|  | 		for j < l2 && isWhitespace(str2[j]) { | ||||||
|  | 			j++ | ||||||
|  | 		} | ||||||
|  | 		if i < l1 && j < l2 && str1[i] != str2[j] { | ||||||
|  | 			return false | ||||||
|  | 		} | ||||||
|  | 		if i < l1 { | ||||||
|  | 			i++ | ||||||
|  | 		} | ||||||
|  | 		if j < l2 { | ||||||
|  | 			j++ | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | 	for i < l1 && isWhitespace(str1[i]) { | ||||||
|  | 		i++ | ||||||
|  | 	} | ||||||
|  | 	for j < l2 && isWhitespace(str2[j]) { | ||||||
|  | 		j++ | ||||||
|  | 	} | ||||||
|  | 	return i == l1 && j == l2 | ||||||
|  | } | ||||||
| 
 | 
 | ||||||
| // removeSpace removes all whitespace characters from the string.
 | func isWhitespace(b byte) bool { | ||||||
| func removeSpace(s string) string { | 	return b == ' ' || | ||||||
| 	var b strings.Builder | 		b == '\t' || | ||||||
| 	for _, r := range s { | 		b == '\n' || | ||||||
| 		if !unicode.IsSpace(r) { | 		b == '\r' || | ||||||
| 			b.WriteRune(r) | 		b == '\v' || | ||||||
| 		} | 		b == '\f' || | ||||||
| 	} | 		b == 0x85 || | ||||||
| 	return b.String() | 		b == 0xA0 | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| // myersDiff computes the Myers' diff between two slices of strings.
 | // myersDiff computes the Myers' diff between two slices of strings.
 | ||||||
|  |  | ||||||
		Loading…
	
		Reference in New Issue
	
	Block a user