using System.Globalization;
using System.Text;
namespace Titano.Data;
///
/// key=value;… connection strings. Keys are case- and space-insensitive (SslMode = Ssl Mode);
/// values may be single- or double-quoted, with the quote doubled inside.
///
internal sealed class ConnectionString
{
private readonly Dictionary _values = new(StringComparer.Ordinal);
private readonly HashSet _used = new(StringComparer.Ordinal);
public ConnectionString(string text)
{
var i = 0;
while (i < text.Length)
{
var eq = text.IndexOf('=', i);
if (eq < 0)
{
if (text.AsSpan(i).Trim().Trim(';').IsEmpty) break;
throw new FormatException($"Connection string segment '{text[i..].Trim()}' has no '='.");
}
var key = Normalize(text.AsSpan(i, eq - i).Trim().TrimStart(';'));
i = eq + 1;
while (i < text.Length && char.IsWhiteSpace(text[i])) i++;
string value;
if (i < text.Length && text[i] is '"' or '\'')
{
var quote = text[i++];
var sb = new StringBuilder();
while (true)
{
if (i >= text.Length) throw new FormatException("Unterminated quoted value in connection string.");
if (text[i] == quote)
{
if (i + 1 < text.Length && text[i + 1] == quote)
{
sb.Append(quote);
i += 2;
continue;
}
i++;
break;
}
sb.Append(text[i++]);
}
value = sb.ToString();
while (i < text.Length && char.IsWhiteSpace(text[i])) i++;
if (i < text.Length && text[i] != ';') throw new FormatException("Unexpected text after a quoted connection string value.");
}
else
{
var end = text.IndexOf(';', i);
if (end < 0) end = text.Length;
value = text[i..end].Trim();
i = end;
}
if (key.Length == 0) throw new FormatException("Empty key in connection string.");
_values[key] = value;
if (i < text.Length && text[i] == ';') i++;
}
}
/// First present key among (synonyms), or null.
public string? Get(params string[] keys)
{
foreach (var key in keys)
{
var normalized = Normalize(key);
if (_values.TryGetValue(normalized, out var value))
{
_used.Add(normalized);
return value;
}
}
return null;
}
public int GetInt(int defaultValue, params string[] keys)
{
var text = Get(keys);
if (text is null) return defaultValue;
return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)
? value
: throw new FormatException($"Connection string value '{keys[0]}' must be an integer.");
}
public bool Contains(string key) => _values.ContainsKey(Normalize(key));
/// Rejects keys that no call consumed, so typos do not pass silently.
public void ThrowOnUnknownKeys()
{
foreach (var key in _values.Keys)
{
if (!_used.Contains(key)) throw new FormatException($"Unknown connection string key '{key}'.");
}
}
private static string Normalize(ReadOnlySpan key)
{
var sb = new StringBuilder(key.Length);
foreach (var c in key)
{
if (!char.IsWhiteSpace(c)) sb.Append(char.ToLowerInvariant(c));
}
return sb.ToString();
}
}