// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Numerics.Hashing; using System.Runtime.CompilerServices; using System.Text; namespace Microsoft.Extensions.Primitives { /// /// Represents zero/null, one, or many strings in an efficient way. /// [DebuggerDisplay("{ToString()}")] [DebuggerTypeProxy(typeof(StringValuesDebugView))] public readonly struct StringValues : IList, IReadOnlyList, IEquatable, IEquatable, IEquatable { /// /// A readonly instance of the struct whose value is an empty string array. /// /// /// In application code, this field is most commonly used to safely represent a that has null string values. /// public static readonly StringValues Empty = new StringValues(Array.Empty()); private readonly object? _values; /// /// Initializes a new instance of the structure using the specified string. /// /// A string value or . public StringValues(string? value) { _values = value; } /// /// Initializes a new instance of the structure using the specified array of strings. /// /// A string array. public StringValues(string?[]? values) { _values = values; } /// /// Defines an implicit conversion of a given string to a . /// /// A string to implicitly convert. public static implicit operator StringValues(string? value) { return new StringValues(value); } /// /// Defines an implicit conversion of a given string array to a . /// /// A string array to implicitly convert. public static implicit operator StringValues(string?[]? values) { return new StringValues(values); } /// /// Defines an implicit conversion of a given to a string, with multiple values joined as a comma separated string. /// /// /// Returns where has been initialized from an empty string array or is . /// /// A to implicitly convert. public static implicit operator string?(StringValues values) { return values.GetStringValue(); } /// /// Defines an implicit conversion of a given to a string array. /// /// A to implicitly convert. public static implicit operator string?[]?(StringValues value) { return value.GetArrayValue(); } /// /// Gets the number of elements contained in this . /// public int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { // Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory object? value = _values; if (value is null) { return 0; } if (value is string) { return 1; } else { // Not string, not null, can only be string[] return Unsafe.As(value).Length; } } } bool ICollection.IsReadOnly => true; /// /// Gets the at the specified index. /// /// The string at the specified index. /// The zero-based index of the element to get. /// Set operations are not supported on readonly . string? IList.this[int index] { get => this[index]; set => throw new NotSupportedException(); } /// /// Gets the at the specified index. /// /// The string at the specified index. /// The zero-based index of the element to get. public string? this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { // Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory object? value = _values; if (value is string str) { if (index == 0) { return str; } } else if (value != null) { // Not string, not null, can only be string[] return Unsafe.As(value)[index]; // may throw } return OutOfBounds(); // throws } } [MethodImpl(MethodImplOptions.NoInlining)] private static string OutOfBounds() { return Array.Empty()[0]; // throws } /// /// Converts the value of the current object to its equivalent string representation, with multiple values joined as a comma separated string. /// /// A string representation of the value of the current object. public override string ToString() { return GetStringValue() ?? string.Empty; } private string? GetStringValue() { // Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory object? value = _values; if (value is string s) { return s; } else { return GetStringValueFromArray(value); } static string? GetStringValueFromArray(object? value) { if (value is null) { return null; } Debug.Assert(value is string[]); // value is not null or string, array, can only be string[] string?[] values = Unsafe.As(value); return values.Length switch { 0 => null, 1 => values[0], _ => GetJoinedStringValueFromArray(values), }; } static string GetJoinedStringValueFromArray(string?[] values) { // Calculate final length int length = 0; for (int i = 0; i < values.Length; i++) { string? value = values[i]; // Skip null and empty values if (value != null && value.Length > 0) { if (length > 0) { // Add separator length++; } length += value.Length; } } #if NET // Create the new string return string.Create(length, values, (span, strings) => { int offset = 0; // Skip null and empty values for (int i = 0; i < strings.Length; i++) { string? value = strings[i]; if (value != null && value.Length > 0) { if (offset > 0) { // Add separator span[offset] = ','; offset++; } value.AsSpan().CopyTo(span.Slice(offset)); offset += value.Length; } } }); #else var sb = new ValueStringBuilder(length); bool hasAdded = false; // Skip null and empty values for (int i = 0; i < values.Length; i++) { string? value = values[i]; if (value != null && value.Length > 0) { if (hasAdded) { // Add separator sb.Append(','); } sb.Append(value); hasAdded = true; } } return sb.ToString(); #endif } } /// /// Creates a string array from the current object. /// /// A string array represented by this instance. /// /// If the contains a single string internally, it is copied to a new array. /// If the contains an array internally it returns that array instance. /// public string?[] ToArray() { return GetArrayValue() ?? Array.Empty(); } private string?[]? GetArrayValue() { // Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory object? value = _values; if (value is string[] values) { return values; } else if (value != null) { // value not array, can only be string return new[] { Unsafe.As(value) }; } else { return null; } } /// /// Returns the zero-based index of the first occurrence of an item in the . /// /// The string to locate in the . /// The zero-based index of the first occurrence of within the , if found; otherwise, -1. int IList.IndexOf(string? item) { return IndexOf(item); } private int IndexOf(string? item) { // Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory object? value = _values; if (value is string[] values) { for (int i = 0; i < values.Length; i++) { if (string.Equals(values[i], item, StringComparison.Ordinal)) { return i; } } return -1; } if (value != null) { // value not array, can only be string return string.Equals(Unsafe.As(value), item, StringComparison.Ordinal) ? 0 : -1; } return -1; } /// Determines whether a string is in the . /// The to locate in the . /// if is found in the ; otherwise, . bool ICollection.Contains(string? item) { return IndexOf(item) >= 0; } /// /// Copies the entire to a string array, starting at the specified index of the target array. /// /// The one-dimensional that is the destination of the elements copied from. The must have zero-based indexing. /// The zero-based index in the destination array at which copying begins. /// is null. /// is less than 0. /// The number of elements in the source is greater than the available space from to the end of the destination . void ICollection.CopyTo(string?[] array, int arrayIndex) { CopyTo(array, arrayIndex); } private void CopyTo(string?[] array, int arrayIndex) { // Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory object? value = _values; if (value is string[] values) { Array.Copy(values, 0, array, arrayIndex, values.Length); return; } if (value != null) { ArgumentNullException.ThrowIfNull(array); if (arrayIndex < 0) { throw new ArgumentOutOfRangeException(nameof(arrayIndex)); } if (array.Length - arrayIndex < 1) { throw new ArgumentException( $"'{nameof(array)}' is not long enough to copy all the items in the collection. Check '{nameof(arrayIndex)}' and '{nameof(array)}' length."); } // value not array, can only be string array[arrayIndex] = Unsafe.As(value); } } void ICollection.Add(string? item) => throw new NotSupportedException(); void IList.Insert(int index, string? item) => throw new NotSupportedException(); bool ICollection.Remove(string? item) => throw new NotSupportedException(); void IList.RemoveAt(int index) => throw new NotSupportedException(); void ICollection.Clear() => throw new NotSupportedException(); /// Retrieves an object that can iterate through the individual strings in this . /// An enumerator that can be used to iterate through the . public Enumerator GetEnumerator() { return new Enumerator(_values); } /// IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// /// Indicates whether the specified contains no string values. /// /// The to test. /// if contains a single or empty string or an empty array; otherwise, . public static bool IsNullOrEmpty(StringValues value) { object? data = value._values; if (data is null) { return true; } if (data is string[] values) { return values.Length switch { 0 => true, 1 => string.IsNullOrEmpty(values[0]), _ => false, }; } else { // Not array, can only be string return string.IsNullOrEmpty(Unsafe.As(data)); } } /// /// Concatenates two specified instances of . /// /// The first to concatenate. /// The second to concatenate. /// The concatenation of and . public static StringValues Concat(StringValues values1, StringValues values2) { int count1 = values1.Count; int count2 = values2.Count; if (count1 == 0) { return values2; } if (count2 == 0) { return values1; } var combined = new string[count1 + count2]; values1.CopyTo(combined, 0); values2.CopyTo(combined, count1); return new StringValues(combined); } /// /// Concatenates specified instance of with specified . /// /// The to concatenate. /// The to concatenate. /// The concatenation of and . public static StringValues Concat(in StringValues values, string? value) { if (value == null) { return values; } int count = values.Count; if (count == 0) { return new StringValues(value); } var combined = new string[count + 1]; values.CopyTo(combined, 0); combined[count] = value; return new StringValues(combined); } /// /// Concatenates specified instance of with specified . /// /// The to concatenate. /// The to concatenate. /// The concatenation of and . public static StringValues Concat(string? value, in StringValues values) { if (value == null) { return values; } int count = values.Count; if (count == 0) { return new StringValues(value); } var combined = new string[count + 1]; combined[0] = value; values.CopyTo(combined, 1); return new StringValues(combined); } /// /// Determines whether two specified objects have the same values in the same order. /// /// The first to compare. /// The second to compare. /// if the value of is the same as the value of ; otherwise, . public static bool Equals(StringValues left, StringValues right) { int count = left.Count; if (count != right.Count) { return false; } for (int i = 0; i < count; i++) { if (left[i] != right[i]) { return false; } } return true; } /// /// Determines whether two specified have the same values. /// /// The first to compare. /// The second to compare. /// if the value of is the same as the value of ; otherwise, . public static bool operator ==(StringValues left, StringValues right) { return Equals(left, right); } /// /// Determines whether two specified have different values. /// /// The first to compare. /// The second to compare. /// if the value of is different to the value of ; otherwise, . public static bool operator !=(StringValues left, StringValues right) { return !Equals(left, right); } /// /// Determines whether this instance and another specified object have the same values. /// /// The string to compare to this instance. /// if the value of is the same as the value of this instance; otherwise, . public bool Equals(StringValues other) => Equals(this, other); /// /// Determines whether the specified and objects have the same values. /// /// The to compare. /// The to compare. /// if the value of is the same as the value of ; otherwise, . If is , the method returns . public static bool Equals(string? left, StringValues right) => Equals(new StringValues(left), right); /// /// Determines whether the specified and objects have the same values. /// /// The to compare. /// The to compare. /// if the value of is the same as the value of ; otherwise, . If is , the method returns . public static bool Equals(StringValues left, string? right) => Equals(left, new StringValues(right)); /// /// Determines whether this instance and a specified , have the same value. /// /// The to compare to this instance. /// if the value of is the same as this instance; otherwise, . If is , returns . public bool Equals(string? other) => Equals(this, new StringValues(other)); /// /// Determines whether the specified string array and objects have the same values. /// /// The string array to compare. /// The to compare. /// if the value of is the same as the value of ; otherwise, . public static bool Equals(string?[]? left, StringValues right) => Equals(new StringValues(left), right); /// /// Determines whether the specified and string array objects have the same values. /// /// The to compare. /// The string array to compare. /// if the value of is the same as the value of ; otherwise, . public static bool Equals(StringValues left, string?[]? right) => Equals(left, new StringValues(right)); /// /// Determines whether this instance and a specified string array have the same values. /// /// The string array to compare to this instance. /// if the value of is the same as this instance; otherwise, . public bool Equals(string?[]? other) => Equals(this, new StringValues(other)); /// public static bool operator ==(StringValues left, string? right) => Equals(left, new StringValues(right)); /// /// Determines whether the specified and objects have different values. /// /// The to compare. /// The to compare. /// if the value of is different to the value of ; otherwise, . public static bool operator !=(StringValues left, string? right) => !Equals(left, new StringValues(right)); /// public static bool operator ==(string? left, StringValues right) => Equals(new StringValues(left), right); /// /// Determines whether the specified and objects have different values. /// /// The to compare. /// The to compare. /// if the value of is different to the value of ; otherwise, . public static bool operator !=(string? left, StringValues right) => !Equals(new StringValues(left), right); /// public static bool operator ==(StringValues left, string?[]? right) => Equals(left, new StringValues(right)); /// /// Determines whether the specified and string array have different values. /// /// The to compare. /// The string array to compare. /// if the value of is different to the value of ; otherwise, . public static bool operator !=(StringValues left, string?[]? right) => !Equals(left, new StringValues(right)); /// public static bool operator ==(string?[]? left, StringValues right) => Equals(new StringValues(left), right); /// /// Determines whether the specified string array and have different values. /// /// The string array to compare. /// The to compare. /// if the value of is different to the value of ; otherwise, . public static bool operator !=(string?[]? left, StringValues right) => !Equals(new StringValues(left), right); /// /// Determines whether the specified and , which must be a /// , , or array of , have the same value. /// /// The to compare. /// The to compare. /// if the object is equal to the ; otherwise, . public static bool operator ==(StringValues left, object? right) => left.Equals(right); /// /// Determines whether the specified and , which must be a /// , , or array of , have different values. /// /// The to compare. /// The to compare. /// if the object is equal to the ; otherwise, . public static bool operator !=(StringValues left, object? right) => !left.Equals(right); /// /// Determines whether the specified , which must be a /// , , or array of , and specified , have the same value. /// /// The to compare. /// The to compare. /// if the object is equal to the ; otherwise, . public static bool operator ==(object? left, StringValues right) => right.Equals(left); /// /// Determines whether the specified and object have the same values. /// /// The to compare. /// The to compare. /// if the object is equal to the ; otherwise, . public static bool operator !=(object? left, StringValues right) => !right.Equals(left); /// /// Determines whether this instance and a specified object have the same value. /// /// An object to compare with this object. /// if the current object is equal to ; otherwise, . public override bool Equals(object? obj) { if (obj == null) { return Equals(this, StringValues.Empty); } if (obj is string str) { return Equals(this, str); } if (obj is string[] array) { return Equals(this, array); } if (obj is StringValues stringValues) { return Equals(this, stringValues); } return false; } /// /// Returns a hash code for this instance. /// /// /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// public override int GetHashCode() { object? value = _values; if (value is string[] values) { if (Count == 1) { return this[0]?.GetHashCode() ?? Count.GetHashCode(); } int hashCode = 0; for (int i = 0; i < values.Length; i++) { hashCode = HashHelpers.Combine(hashCode, values[i]?.GetHashCode() ?? 0); } return hashCode; } else { return Unsafe.As(value)?.GetHashCode() ?? Count.GetHashCode(); } } /// /// Enumerates the string values of a . /// public struct Enumerator : IEnumerator { private readonly string?[]? _values; private int _index; private string? _current; internal Enumerator(object? value) { if (value is string str) { _values = null; _current = str; } else { _current = null; _values = Unsafe.As(value); } _index = 0; } /// /// Instantiates an using a . /// /// The to enumerate. public Enumerator(ref StringValues values) : this(values._values) { } /// /// Advances the enumerator to the next element of the . /// /// if the enumerator was successfully advanced to the next element; if the enumerator has passed the end of the . public bool MoveNext() { int index = _index; if (index < 0) { return false; } string?[]? values = _values; if (values != null) { if ((uint)index < (uint)values.Length) { _index = index + 1; _current = values[index]; return true; } _index = -1; return false; } _index = -1; // sentinel value return _current != null; } /// /// Gets the element at the current position of the enumerator. /// public string? Current => _current; object? IEnumerator.Current => _current; void IEnumerator.Reset() { throw new NotSupportedException(); } /// /// Releases all resources used by the . /// public void Dispose() { } } private sealed class StringValuesDebugView(StringValues values) { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public string?[] Items => values.ToArray(); } } }