--[[
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
*     string and the start of the second string.
* @private
--]]

local function _diff_commonOverlap(text1: string, text2: string): number
	-- Cache the text lengths to prevent multiple calls.
	local text1_length = #text1
	local text2_length = #text2
	-- Eliminate the null case.
	if text1_length == 0 or text2_length == 0 then
		return 0
	end
	-- Truncate the longer string.
	if text1_length > text2_length then
		text1 = strsub(text1, text1_length - text2_length + 1)
	elseif text1_length < text2_length then
		text2 = strsub(text2, 1, text1_length)
	end
	local text_length = min(text1_length, text2_length)
	-- Quick check for the worst case.
	if text1 == text2 then
		return text_length
	end

	-- Start by looking for a single character match
	-- and increase length until no match is found.
	-- Performance analysis: https://neil.fraser.name/news/2010/11/04/
	local best = 0
	local length = 1
	while true do
		local pattern = strsub(text1, text_length - length + 1)
		local found = strfind(text2, pattern, 1, true)
		if found == nil then
			return best
		end
		-- ROBLOX FIXME Luau: narrowing/type state should make this cast unnecessary
		length += (found :: number - 1)
		if found == 1 or strsub(text1, text_length - length + 1) == strsub(text2, 1, length) then
			best = length
			length += 1
		end
	end
	return best
end
