summaryrefslogtreecommitdiff
path: root/src/corefx/System.Globalization.Native/idna.cpp
blob: 4820d2c3f2e186f740ec383998006b209db1e416 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//

#include <stdint.h>
#include <unicode/uidna.h>

const uint32_t AllowUnassigned = 0x1;
const uint32_t UseStd3AsciiRules = 0x2;

uint32_t GetOptions(uint32_t flags)
{
    // Using Nontransitional to Unicode and Check ContextJ to match the current behavior of .NET on Windows
    uint32_t options = UIDNA_NONTRANSITIONAL_TO_UNICODE | UIDNA_CHECK_CONTEXTJ;

    if ((flags & AllowUnassigned) == AllowUnassigned)
    {
        options |= UIDNA_ALLOW_UNASSIGNED;
    }

    if ((flags & UseStd3AsciiRules) == UseStd3AsciiRules)
    {
        options |= UIDNA_USE_STD3_RULES;
    }

    return options;
}

/*
Function:
ToASCII

Used by System.Globalization.IdnMapping.GetAsciiCore to convert an Unicode
domain name to ASCII

Return values:
0: internal error during conversion.
>0: the length of the converted string (not including the null terminator).
*/
extern "C" int32_t GlobalizationNative_ToAscii(
    uint32_t flags, const UChar* lpSrc, int32_t cwSrcLength, UChar* lpDst, int32_t cwDstLength)
{
    UErrorCode err = U_ZERO_ERROR;
    UIDNAInfo info = UIDNA_INFO_INITIALIZER;

    UIDNA* pIdna = uidna_openUTS46(GetOptions(flags), &err);

    int32_t asciiStrLen = uidna_nameToASCII(pIdna, lpSrc, cwSrcLength, lpDst, cwDstLength, &info, &err);

    uidna_close(pIdna);

    return ((U_SUCCESS(err) || (err == U_BUFFER_OVERFLOW_ERROR)) && (info.errors == 0)) ? asciiStrLen : 0;
}

/*
Function:
ToUnicode

Used by System.Globalization.IdnMapping.GetUnicodeCore to convert an ASCII name
to Unicode

Return values:
0: internal error during conversion.
>0: the length of the converted string (not including the null terminator).
*/
extern "C" int32_t GlobalizationNative_ToUnicode(
    int32_t flags, const UChar* lpSrc, int32_t cwSrcLength, UChar* lpDst, int32_t cwDstLength)
{
    UErrorCode err = U_ZERO_ERROR;
    UIDNAInfo info = UIDNA_INFO_INITIALIZER;

    UIDNA* pIdna = uidna_openUTS46(GetOptions(flags), &err);

    int32_t unicodeStrLen = uidna_nameToUnicode(pIdna, lpSrc, cwSrcLength, lpDst, cwDstLength, &info, &err);

    uidna_close(pIdna);

    return ((U_SUCCESS(err) || (err == U_BUFFER_OVERFLOW_ERROR)) && (info.errors == 0)) ? unicodeStrLen : 0;
}