|
| 1 | +// Copyright 2020 ONIXLabs |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +using System; |
| 16 | +using System.Diagnostics.CodeAnalysis; |
| 17 | + |
| 18 | +namespace OnixLabs.Security.Cryptography; |
| 19 | + |
| 20 | +public readonly partial record struct NamedHash |
| 21 | +{ |
| 22 | + public static NamedHash Parse(string value, IFormatProvider? provider = null) => Parse(value.AsSpan(), provider); |
| 23 | + |
| 24 | + public static NamedHash Parse(ReadOnlySpan<char> value, IFormatProvider? provider = null) |
| 25 | + { |
| 26 | + if (TryParse(value, provider, out NamedHash result)) return result; |
| 27 | + throw new FormatException($"The input string '{value}' was not in a correct format."); |
| 28 | + } |
| 29 | + |
| 30 | + public static bool TryParse([NotNullWhen(true)] string? value, IFormatProvider? provider, out NamedHash result) => TryParse(value.AsSpan(), provider, out result); |
| 31 | + |
| 32 | + public static bool TryParse(ReadOnlySpan<char> value, IFormatProvider? provider, out NamedHash result) |
| 33 | + { |
| 34 | + result = default; |
| 35 | + |
| 36 | + int index = value.IndexOf(Separator); |
| 37 | + |
| 38 | + if (index < 0) return false; |
| 39 | + |
| 40 | + ReadOnlySpan<char> name = value[..index]; |
| 41 | + ReadOnlySpan<char> data = value[(index + 1)..]; |
| 42 | + |
| 43 | + if (name.IsEmpty || data.IsEmpty) return false; |
| 44 | + |
| 45 | + bool isDecoded = Hash.TryParse(data, provider, out Hash hash); |
| 46 | + |
| 47 | + result = new NamedHash(hash, name.ToString()); |
| 48 | + |
| 49 | + return isDecoded; |
| 50 | + } |
| 51 | +} |
0 commit comments