| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | namespace IceRpc.Internal; |
| | 4 | |
|
| | 5 | | internal readonly partial record struct Identity |
| | 6 | | { |
| | 7 | | /// <summary>Gets the null identity.</summary> |
| 2680 | 8 | | internal static Identity Empty { get; } = new("", ""); |
| | 9 | |
|
| 0 | 10 | | public override string ToString() => ToPath(); |
| | 11 | |
|
| | 12 | | /// <summary>Parses a path into an identity, including the null/empty identity.</summary> |
| | 13 | | /// <param name="path">The path (percent escaped).</param> |
| | 14 | | /// <returns>The corresponding identity.</returns> |
| | 15 | | internal static Identity Parse(string path) |
| 2792 | 16 | | { |
| 2792 | 17 | | if (path.Length == 0 || path[0] != '/') |
| 2 | 18 | | { |
| 2 | 19 | | throw new ArgumentException("path must start with a /", nameof(path)); |
| | 20 | | } |
| | 21 | |
|
| 2790 | 22 | | string workingPath = path[1..]; // removes leading /. |
| | 23 | |
|
| 2790 | 24 | | int firstSlash = workingPath.IndexOf('/', StringComparison.Ordinal); |
| | 25 | |
|
| | 26 | | string name; |
| 2790 | 27 | | string category = ""; |
| | 28 | |
|
| 2790 | 29 | | if (firstSlash == -1) |
| 2778 | 30 | | { |
| | 31 | | // Name only |
| 2778 | 32 | | name = Uri.UnescapeDataString(workingPath); |
| 2778 | 33 | | } |
| | 34 | | else |
| 12 | 35 | | { |
| 12 | 36 | | if (firstSlash != workingPath.LastIndexOf('/')) |
| 1 | 37 | | { |
| 1 | 38 | | throw new FormatException($"Too many slashes in path '{path}'."); |
| | 39 | | } |
| | 40 | |
|
| 11 | 41 | | name = Uri.UnescapeDataString(workingPath[(firstSlash + 1)..]); |
| 11 | 42 | | category = Uri.UnescapeDataString(workingPath[0..firstSlash]); |
| 11 | 43 | | } |
| | 44 | |
|
| 2789 | 45 | | return name.Length == 0 ? Empty : new(name, category); |
| 2789 | 46 | | } |
| | 47 | |
|
| | 48 | | /// <summary>Converts this identity into a path.</summary> |
| | 49 | | internal string ToPath() |
| 2785 | 50 | | { |
| 2785 | 51 | | if (Name.Length == 0) |
| 2663 | 52 | | { |
| 2663 | 53 | | return "/"; |
| | 54 | | } |
| | 55 | |
|
| 122 | 56 | | return Category.Length > 0 ? |
| 122 | 57 | | $"/{Uri.EscapeDataString(Category)}/{Uri.EscapeDataString(Name)}" : |
| 122 | 58 | | $"/{Uri.EscapeDataString(Name)}"; |
| 2785 | 59 | | } |
| | 60 | | } |