Allow convertion from string consisting of single code point to `System.Text.Rune` · Issue #27596 · PowerShell/PowerShell · GitHub
Skip to content

Allow convertion from string consisting of single code point to System.Text.Rune #27596

Description

@tats-u

Summary of the new feature / enhancement

PS> [char]"A"
A

PS> [char]"😀"
InvalidArgument: Cannot convert value "😀" to type "System.Char". Error: "String must be exactly one character long."

PS> [Text.Rune]"A"
InvalidArgument: Cannot convert the "A" value of type "System.String" to type "System.Text.Rune".

System.Text.Rune can represent supplementary characters outside BMP like "😀" but it can't be directly converted by string like char. Instead, you're required to take the following complex and inefficient way:

PS> "😀".EnumerateRunes()[0]

IsAscii             : False
IsBmp               : False
Plane               : 1
Utf16SequenceLength : 2
Utf8SequenceLength  : 4
Value               : 128512

Proposed technical implementation details (optional)

Permits only strings that consist of a single BMP Unicode scalar value (not a surrogate code unit) or a single surrogate pair (a high surrogate code unit + a low surrogate code unit).

PS> [Text.Rune]"AA"
InvalidArgument: Cannot convert value "AA" to type "System.Text.Rune". Error: "String must be exactly one character long."

PS> [Text.Rune]"👨🏼‍💻"
InvalidArgument: Cannot convert value "👨🏼‍💻" to type "System.Text.Rune". Error: "String must be exactly one character long."

PS> [Text.Rune]"`u{d800}"
InvalidArgument: Cannot convert value "�" to type "System.Text.Rune". Error: "Surrogate code unit cannot be converted to Rune."

Use the constructor of Rune to create its instance from the code point:

PS> [Text.Rune]::new(0x41)

IsAscii             : True
IsBmp               : True
Plane               : 0
Utf16SequenceLength : 1
Utf8SequenceLength  : 1
Value               : 65

PS> [Text.Rune]::new(0x1F600)

IsAscii             : False
IsBmp               : False
Plane               : 1
Utf16SequenceLength : 2
Utf8SequenceLength  : 4
Value               : 128512

PS> [Text.Rune]::new(0xd800)
MethodInvocationException: Exception calling ".ctor" with "1" argument(s): "Specified argument was out of the range of valid values. (Parameter 'value')"

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugNeeds-TriageThe issue is new and needs to be triaged by a work group.WG-Enginecore PowerShell engine, interpreter, and runtimeWG-NeedsReviewNeeds a review by the labeled Working Group

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions