精易论坛

标题: Punycode编码/解码 纯js版 [打印本页]

作者: 观音    时间: 2024-3-23 00:38
标题: Punycode编码/解码 纯js版
起因是今天在问答区看到个问题,提到了中文域名 我访问了一下 中文域名变成了 xn--开头的地址,然后我就去问了 文心一言,才知道了 Punycode编码这个东西
[JavaScript] 纯文本查看 复制代码
测试.测试.cc //中文域名
xn--0zwm56d.xn--0zwm56d.cc //浏览器解析的域名


但是文心一言给出的js代码真的很烂,我都说了用不了还是不改正,果然现在AI的主流还是用Python,但是用Python的话很不方便,需要搭接口调用,没有办法,自己动手丰衣足食,找到参考资料,研究算法,好吧放弃

然后在万能的CSDN找到了js,当然是没法直接运行的,稍微一修改,完工。 CSDN参考链接(这个帖子也是别人转发的):https://blog.csdn.net/weixin_33913332/article/details/94701104

本来想把帖子发到精易模块功能建议里的,想想还是算了,现在精易论坛的压力确实很大,更新频率越来越少,上一个帖子也石沉大海了,而且我还要提一下,我提供了好几条命令精易模块都收录了,就是不给,拜托真的很想要

经过测试,浏览器环境、系统环境都是正常的,但是在V8环境下会不对,当然最好的肯定就是系统环境支持,V8只是附加项


调用函数

[JavaScript] 纯文本查看 复制代码
enPunycode('测试.测试.cc')//编码

dePunycode('xn--0zwm56d.xn--0zwm56d.cc')//解码



易语言例程


Punycode编码.e (957.64 KB, 下载次数: 33)

JS代码

[JavaScript] 纯文本查看 复制代码
(function() {
    var PunycodeModule = function () {

        function IdnMapping() {
            this.utf16 = {
                decode: function (input) {
                    var output = [], i = 0, len = input.length, value, extra;
                    while (i < len) {
                        value = input.charCodeAt(i++);
                        if ((value & 0xF800) === 0xD800) {
                            extra = input.charCodeAt(i++);
                            if (((value & 0xFC00) !== 0xD800) || ((extra & 0xFC00) !== 0xDC00)) {
                                throw new RangeError("UTF-16(decode): Illegal UTF-16 sequence");
                            }
                            value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
                        }
                        output.push(value);
                    }
                    return output;
                },
                encode: function (input) {
                    var output = [], i = 0, len = input.length, value;
                    while (i < len) {
                        value = input[i++];
                        if ((value & 0xF800) === 0xD800) {
                            throw new RangeError("UTF-16(encode): Illegal UTF-16 value");
                        }
                        if (value > 0xFFFF) {
                            value -= 0x10000;
                            output.push(String.fromCharCode(((value >>> 10) & 0x3FF) | 0xD800));
                            value = 0xDC00 | (value & 0x3FF);
                        }
                        output.push(String.fromCharCode(value));
                    }
                    return output.join("");
                }
            }

            var initial_n = 0x80;
            var initial_bias = 72;
            var delimiter = "\x2D";
            var base = 36;
            var damp = 700;
            var tmin = 1;
            var tmax = 26;
            var skew = 38;
            var maxint = 0x7FFFFFFF;

            function decode_digit(cp) {
                return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;
            }

            function encode_digit(d, flag) {
                return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);

            }
            function adapt(delta, numpoints, firsttime) {
                var k;
                delta = firsttime ? Math.floor(delta / damp) : (delta >> 1);
                delta += Math.floor(delta / numpoints);

                for (k = 0; delta > (((base - tmin) * tmax) >> 1) ; k += base) {
                    delta = Math.floor(delta / (base - tmin));
                }
                return Math.floor(k + (base - tmin + 1) * delta / (delta + skew));
            }


            function encode_basic(bcp, flag) {
                bcp -= (bcp - 97 < 26) << 5;
                return bcp + ((!flag && (bcp - 65 < 26)) << 5);
            }

            this.decode = function (input, preserveCase) {
                // Dont use utf16
                var output = [];
                var case_flags = [];
                var input_length = input.length;

                var n, out, i, bias, basic, j, ic, oldi, w, k, digit, t, len;

                // Initialize the state:

                n = initial_n;
                i = 0;
                bias = initial_bias;

                // Handle the basic code points: Let basic be the number of input code
                // points before the last delimiter, or 0 if there is none, then
                // copy the first basic code points to the output.

                basic = input.lastIndexOf(delimiter);
                if (basic < 0) basic = 0;

                for (j = 0; j < basic; ++j) {
                    if (preserveCase) case_flags[output.length] = (input.charCodeAt(j) - 65 < 26);
                    if (input.charCodeAt(j) >= 0x80) {
                        throw new RangeError("Illegal input >= 0x80");
                    }
                    output.push(input.charCodeAt(j));
                }

                // Main decoding loop: Start just after the last delimiter if any
                // basic code points were copied; start at the beginning otherwise.

                for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {

                    // ic is the index of the next character to be consumed,

                    // Decode a generalized variable-length integer into delta,
                    // which gets added to i. The overflow checking is easier
                    // if we increase i as we go, then subtract off its starting
                    // value at the end to obtain delta.
                    for (oldi = i, w = 1, k = base; ; k += base) {
                        if (ic >= input_length) {
                            throw RangeError("punycode_bad_input(1)");
                        }
                        digit = decode_digit(input.charCodeAt(ic++));

                        if (digit >= base) {
                            throw RangeError("punycode_bad_input(2)");
                        }
                        if (digit > Math.floor((maxint - i) / w)) {
                            throw RangeError("punycode_overflow(1)");
                        }
                        i += digit * w;
                        t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;
                        if (digit < t) { break; }
                        if (w > Math.floor(maxint / (base - t))) {
                            throw RangeError("punycode_overflow(2)");
                        }
                        w *= (base - t);
                    }

                    out = output.length + 1;
                    bias = adapt(i - oldi, out, oldi === 0);

                    // i was supposed to wrap around from out to 0,
                    // incrementing n each time, so we'll fix that now:
                    if (Math.floor(i / out) > maxint - n) {
                        throw RangeError("punycode_overflow(3)");
                    }
                    n += Math.floor(i / out);
                    i %= out;

                    // Insert n at position i of the output:
                    // Case of last character determines uppercase flag:
                    if (preserveCase) { case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26); }

                    output.splice(i, 0, n);
                    i++;
                }
                if (preserveCase) {
                    for (i = 0, len = output.length; i < len; i++) {
                        if (case_flags) {
                            output = (String.fromCharCode(output).toUpperCase()).charCodeAt(0);
                        }
                    }
                }
                return this.utf16.encode(output);
            };


            this.encode = function (input, preserveCase) {
                //** Bias adaptation function **

                var n, delta, h, b, bias, j, m, q, k, t, ijv, case_flags;

                if (preserveCase) {
                    // Preserve case, step1 of 2: Get a list of the unaltered string
                    case_flags = this.utf16.decode(input);
                }
                // Converts the input in UTF-16 to Unicode
                input = this.utf16.decode(input.toLowerCase());

                var input_length = input.length; // Cache the length

                if (preserveCase) {
                    // Preserve case, step2 of 2: Modify the list to true/false
                    for (j = 0; j < input_length; j++) {
                        case_flags[j] = input[j] != case_flags[j];
                    }
                }

                var output = [];


                // Initialize the state:
                n = initial_n;
                delta = 0;
                bias = initial_bias;

                // Handle the basic code points:
                for (j = 0; j < input_length; ++j) {
                    if (input[j] < 0x80) {
                        output.push(
                            String.fromCharCode(
                                case_flags ? encode_basic(input[j], case_flags[j]) : input[j]
                            )
                        );
                    }
                }

                h = b = output.length;

                // h is the number of code points that have been handled, b is the
                // number of basic code points

                if (b > 0) output.push(delimiter);

                // Main encoding loop:
                //
                while (h < input_length) {
                    // All non-basic code points < n have been
                    // handled already. Find the next larger one:

                    for (m = maxint, j = 0; j < input_length; ++j) {
                        ijv = input[j];
                        if (ijv >= n && ijv < m) m = ijv;
                    }

                    // Increase delta enough to advance the decoder's
                    // <n,i> state to <m,0>, but guard against overflow:

                    if (m - n > Math.floor((maxint - delta) / (h + 1))) {
                        throw RangeError("punycode_overflow (1)");
                    }
                    delta += (m - n) * (h + 1);
                    n = m;

                    for (j = 0; j < input_length; ++j) {
                        ijv = input[j];

                        if (ijv < n) {
                            if (++delta > maxint) return Error("punycode_overflow(2)");
                        }

                        if (ijv == n) {
                            // Represent delta as a generalized variable-length integer:
                            for (q = delta, k = base; ; k += base) {
                                t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;
                                if (q < t) break;
                                output.push(String.fromCharCode(encode_digit(t + (q - t) % (base - t), 0)));
                                q = Math.floor((q - t) / (base - t));
                            }
                            output.push(String.fromCharCode(encode_digit(q, preserveCase && case_flags[j] ? 1 : 0)));
                            bias = adapt(delta, h + 1, h == b);
                            delta = 0;
                            ++h;
                        }
                    }

                    ++delta, ++n;
                }
                return output.join("");
            }
        }

        this.toASCII = function (domain) {
            var idn = new IdnMapping();
            var domainarray = domain.split(".");
            var out = [];
            for (var i = 0; i < domainarray.length; ++i) {
                var s = domainarray;
                out.push(
                    s.match(/[^A-Za-z0-9-]/) ?
                        "xn--" + idn.encode(s) :
                        s
                );
            }
            return out.join(".");
        }

        this.toUnicode = function (domain) {
            var idn = new IdnMapping();
            var domainarray = domain.split(".");
            var out = [];
            for (var i = 0; i < domainarray.length; ++i) {
                var s = domainarray;
                out.push(
                    s.match(/^xn--/) ?
                    idn.decode(s.slice(4)) :
                        s
                );
            }
            return out.join(".");
        }
    }

    idnMapping =  PunycodeModule;
})()

function enPunycode (domainName){
    var idn = new idnMapping();
    var str = idn.toASCII(domainName);
    return str;
}
function dePunycode (domainName){
    var idn = new idnMapping();
    var str = idn.toUnicode(domainName);
    return str;
}




作者: 447485268    时间: 2024-3-23 00:43
支持开源~!感谢分享
作者: ZHuanR    时间: 2024-3-23 02:30
新技能已get√
作者: hetao    时间: 2024-3-23 03:19
支持开源.感谢分享
作者: 查过    时间: 2024-3-23 07:56
感谢楼主分享!
作者: 豆豆灰常开心    时间: 2024-3-23 08:01
已经顶贴,感谢您对论坛的支持!
作者: 小虎来了    时间: 2024-3-23 09:24
感谢分享,很给力!~
作者: 一指温柔    时间: 2024-3-23 09:25
感谢分享,很给力!~
作者: qqmqqg    时间: 2024-3-23 09:28
6666666666666666666666
作者: 易神    时间: 2024-3-23 10:20
感谢分享,很给力!~
作者: quary    时间: 2024-3-23 16:03
感谢 又长姿势了
作者: 亿万    时间: 2024-3-23 20:54
感谢分享,很给力!~
作者: renjianhong48we    时间: 2024-3-23 20:56
感谢分享
作者: 深圳梦    时间: 2024-3-23 21:35
感谢分享,很给力!~
作者: 灵猫作者    时间: 2024-3-23 22:12
        感谢分享,很给力!~
作者: 艾玛克138    时间: 2024-3-23 22:17
感谢老大的无私奉献!!!
作者: 光影魔术    时间: 2024-3-24 00:37
感谢分享
作者: 查过    时间: 2024-3-24 07:07
感谢楼主分享!
作者: 豆豆灰常开心    时间: 2024-3-24 07:12
全都是大佬~
作者: 无敌灰灰    时间: 2024-3-24 08:14
好多年前易论坛有过这代码,还有纯易实现的代码。。。可惜了。。。
作者: bianyuan456    时间: 2024-3-24 23:28
已经顶贴,感谢您对论坛的支持!
作者: JYYeah    时间: 2024-3-25 00:17
新技能已get√
作者: 396384183    时间: 2024-3-26 09:22
感谢分享,很给力!~
作者: fengyyun    时间: 2024-3-26 10:35
感谢分享,很给力!~

作者: lm88818    时间: 2024-4-1 09:23
感谢分享,很给力!~
作者: tpwlyz    时间: 2024-4-8 18:03

作者: 515667395    时间: 2024-9-21 16:44
多谢分享~~~!




欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4