|
| 1 | +function ConvertFrom-YamlTagUriEscape { |
| 2 | + <# |
| 3 | + .SYNOPSIS |
| 4 | + Decodes YAML tag URI %xx escapes as UTF-8. |
| 5 | + #> |
| 6 | + [CmdletBinding()] |
| 7 | + [OutputType([string])] |
| 8 | + param ( |
| 9 | + [Parameter(Mandatory)] |
| 10 | + [string] $Text, |
| 11 | + |
| 12 | + [Parameter(Mandatory)] |
| 13 | + [pscustomobject] $Mark, |
| 14 | + |
| 15 | + [Parameter(Mandatory)] |
| 16 | + [string] $Token |
| 17 | + ) |
| 18 | + |
| 19 | + function Get-YamlHexNibble { |
| 20 | + param ([char] $Character) |
| 21 | + if ($Character -notmatch '^[0-9A-Fa-f]$') { |
| 22 | + return -1 |
| 23 | + } |
| 24 | + [System.Convert]::ToInt32([string] $Character, 16) |
| 25 | + } |
| 26 | + |
| 27 | + $builder = [System.Text.StringBuilder]::new() |
| 28 | + $escapedBytes = [System.Collections.Generic.List[byte]]::new() |
| 29 | + $utf8 = [System.Text.UTF8Encoding]::new($false, $true) |
| 30 | + |
| 31 | + for ($index = 0; $index -lt $Text.Length; $index++) { |
| 32 | + $character = $Text[$index] |
| 33 | + if ($character -ne '%') { |
| 34 | + if ($escapedBytes.Count -gt 0) { |
| 35 | + try { |
| 36 | + [void] $builder.Append($utf8.GetString($escapedBytes.ToArray())) |
| 37 | + } catch [System.Text.DecoderFallbackException] { |
| 38 | + throw (New-YamlException -Start $Mark -End $Mark -ErrorId 'YamlInvalidTag' -Message ( |
| 39 | + "The tag token '$Token' contains an invalid UTF-8 escape sequence." |
| 40 | + )) |
| 41 | + } |
| 42 | + $escapedBytes.Clear() |
| 43 | + } |
| 44 | + [void] $builder.Append($character) |
| 45 | + continue |
| 46 | + } |
| 47 | + |
| 48 | + if ($index + 2 -ge $Text.Length) { |
| 49 | + throw (New-YamlException -Start $Mark -End $Mark -ErrorId 'YamlInvalidTag' -Message ( |
| 50 | + "The tag token '$Token' contains a malformed percent escape." |
| 51 | + )) |
| 52 | + } |
| 53 | + $high = Get-YamlHexNibble -Character $Text[$index + 1] |
| 54 | + $low = Get-YamlHexNibble -Character $Text[$index + 2] |
| 55 | + if ($high -lt 0 -or $low -lt 0) { |
| 56 | + throw (New-YamlException -Start $Mark -End $Mark -ErrorId 'YamlInvalidTag' -Message ( |
| 57 | + "The tag token '$Token' contains a malformed percent escape." |
| 58 | + )) |
| 59 | + } |
| 60 | + $escapedBytes.Add([byte](($high * 16) + $low)) |
| 61 | + $index += 2 |
| 62 | + } |
| 63 | + |
| 64 | + if ($escapedBytes.Count -gt 0) { |
| 65 | + try { |
| 66 | + [void] $builder.Append($utf8.GetString($escapedBytes.ToArray())) |
| 67 | + } catch [System.Text.DecoderFallbackException] { |
| 68 | + throw (New-YamlException -Start $Mark -End $Mark -ErrorId 'YamlInvalidTag' -Message ( |
| 69 | + "The tag token '$Token' contains an invalid UTF-8 escape sequence." |
| 70 | + )) |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + $builder.ToString() |
| 75 | +} |
0 commit comments