|
| 1 | +using System; |
| 2 | + |
| 3 | +namespace WebApiClientCore |
| 4 | +{ |
| 5 | + /// <summary> |
| 6 | + /// 提供媒体类型比较 |
| 7 | + /// </summary> |
| 8 | + static class MediaType |
| 9 | + { |
| 10 | + /// <summary> |
| 11 | + /// 是否与目标匹配 |
| 12 | + /// </summary> |
| 13 | + /// <param name="source"></param> |
| 14 | + /// <param name="target"></param> |
| 15 | + /// <returns></returns> |
| 16 | + public static bool IsMatch(string? source, string? target) |
| 17 | + { |
| 18 | + return IsMatch(source.AsSpan(), target.AsSpan()); |
| 19 | + } |
| 20 | + |
| 21 | + /// <summary> |
| 22 | + /// 是否与目标匹配 |
| 23 | + /// </summary> |
| 24 | + /// <param name="source"></param> |
| 25 | + /// <param name="target"></param> |
| 26 | + /// <returns></returns> |
| 27 | + private static bool IsMatch(ReadOnlySpan<char> source, ReadOnlySpan<char> target) |
| 28 | + { |
| 29 | + var index = source.IndexOf('/'); |
| 30 | + var sourceMain = index >= 0 ? source.Slice(0, index) : source; |
| 31 | + var sourceSub = index >= 0 ? source.Slice(index + 1) : ReadOnlySpan<char>.Empty; |
| 32 | + |
| 33 | + index = target.IndexOf('/'); |
| 34 | + var targetMain = index >= 0 ? target.Slice(0, index) : target; |
| 35 | + var targetSub = index >= 0 ? target.Slice(index + 1) : ReadOnlySpan<char>.Empty; |
| 36 | + |
| 37 | + return MediaTypeMatch(sourceMain, targetMain) && MediaTypeMatch(sourceSub, targetSub); |
| 38 | + } |
| 39 | + |
| 40 | + |
| 41 | + /// <summary> |
| 42 | + /// MediaType是否匹配 |
| 43 | + /// </summary> |
| 44 | + /// <param name="source"></param> |
| 45 | + /// <param name="target"></param> |
| 46 | + /// <returns></returns> |
| 47 | + private static bool MediaTypeMatch(ReadOnlySpan<char> source, ReadOnlySpan<char> target) |
| 48 | + { |
| 49 | + if (source.Length == 1 && source[0] == '*') |
| 50 | + { |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + if (target.Length == 1 && target[0] == '*') |
| 55 | + { |
| 56 | + return true; |
| 57 | + } |
| 58 | + |
| 59 | + if (source.Length != target.Length) |
| 60 | + { |
| 61 | + return false; |
| 62 | + } |
| 63 | + |
| 64 | + for (var i = 0; i < source.Length; i++) |
| 65 | + { |
| 66 | + var s = source[i]; |
| 67 | + var t = target[i]; |
| 68 | + if (char.IsUpper(s)) |
| 69 | + { |
| 70 | + s = char.ToLowerInvariant(s); |
| 71 | + } |
| 72 | + if (char.IsUpper(t)) |
| 73 | + { |
| 74 | + t = char.ToLowerInvariant(t); |
| 75 | + } |
| 76 | + |
| 77 | + if (s.Equals(t) == false) |
| 78 | + { |
| 79 | + return false; |
| 80 | + } |
| 81 | + } |
| 82 | + return true; |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments