| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | |
| | | 7 | | namespace System.Net.Http.Headers |
| | | 8 | | { |
| | | 9 | | // Don't derive from BaseHeaderParser since parsing is delegated to DateTimeOffset.TryParseExact() |
| | | 10 | | // which will remove leading, trailing, and whitespace in the middle of the string. |
| | | 11 | | internal sealed class DateHeaderParser : HttpHeaderParser |
| | | 12 | | { |
| | 1 | 13 | | internal static readonly DateHeaderParser Parser = new DateHeaderParser(); |
| | | 14 | | |
| | | 15 | | private DateHeaderParser() |
| | 1 | 16 | | : base(false) |
| | 1 | 17 | | { |
| | 1 | 18 | | } |
| | | 19 | | |
| | | 20 | | public override string ToString(object value) |
| | 0 | 21 | | { |
| | 0 | 22 | | Debug.Assert(value is DateTimeOffset); |
| | | 23 | | |
| | 0 | 24 | | return ((DateTimeOffset)value).ToString("r"); |
| | 0 | 25 | | } |
| | | 26 | | |
| | | 27 | | public override bool TryParseValue([NotNullWhen(true)] string? value, object? storeValue, ref int index, [NotNul |
| | 42 | 28 | | { |
| | 42 | 29 | | parsedValue = null; |
| | | 30 | | |
| | | 31 | | // Some headers support empty/null values. This one doesn't. |
| | 42 | 32 | | if (string.IsNullOrEmpty(value) || (index == value.Length)) |
| | 26 | 33 | | { |
| | 26 | 34 | | return false; |
| | | 35 | | } |
| | | 36 | | |
| | 16 | 37 | | ReadOnlySpan<char> dateString = value; |
| | 16 | 38 | | if (index > 0) |
| | 0 | 39 | | { |
| | 0 | 40 | | dateString = value.AsSpan(index); |
| | 0 | 41 | | } |
| | | 42 | | |
| | | 43 | | DateTimeOffset date; |
| | 16 | 44 | | if (!HttpDateParser.TryParse(dateString, out date)) |
| | 16 | 45 | | { |
| | 16 | 46 | | return false; |
| | | 47 | | } |
| | | 48 | | |
| | 0 | 49 | | index = value.Length; |
| | 0 | 50 | | parsedValue = date; |
| | 0 | 51 | | return true; |
| | 42 | 52 | | } |
| | | 53 | | } |
| | | 54 | | } |