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