>  기사  >  웹 프론트엔드  >  protobuf.js 및 Long.js 사용에 대한 자세한 설명

protobuf.js 및 Long.js 사용에 대한 자세한 설명

php中世界最好的语言
php中世界最好的语言원래의
2018-03-16 10:58:414780검색

이번에는 protobuf.js와 Long.js의 사용법에 대해 자세히 설명을 들고 왔습니다. protobuf.js와 Long.js를 급히 사용할 때 주의사항은 무엇인가요? 실제 사례를 살펴보겠습니다.

protobuf.js의 구조는 로드 후 webpack의 구조와 매우 유사합니다. 이런 모듈러 조합은 좋은 구조적 방법입니다. 하나는 다양한 로딩 방법에 적용되며 두 모듈은 직접적으로 독립적입니다. webpack이 더 기능적입니다. 하지만 js 라이브러리를 직접 캡슐화하면 이것으로 충분합니다. 또한 모듈에는 통합 외부 인터페이스 module.exports가 있습니다. 이는 노드와 매우 유사합니다.

(function(global, undefined) {    "use strict";
    (function prelude(modules, cache, entries) {        function $require(name) {            var $module = cache[name];            //没有就去加载
            if (!$module)
                modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);            return $module.exports;
        }        //曝光成全局
        var proto = global.proto = $require(entries[0]);        // AMD
        if (typeof define === "function" && define.amd) {
            define(["long"], function(Long) {                if (Long && Long.isLong) {
                    proto.util.Long = Long;
                    proto.configure();
                }
            });            return proto;
        }        //CommonJS
        if (typeof module === "object" && module && module.exports)
            module.exports = proto;
    })    //传参    ({        1: [function (require, module, exports) {            function first() {
                console.log("first");
            }
            module.exports = first;
        }, {}],        2: [function(require, module, exports) {            function second() {
                console.log("second");
            }
            module.exports = second;
        }],        3: [function (require, module, exports) {            var proto = {};
            proto.first = require(1);
            proto.second = require(2);
            proto.build = "full";
            module.exports = proto;
        }]
      }, {}, [3]);
})(typeof window==="object"&&window||typeof self==="object"&&self||this)
16비트를 초과하는 도형을 다룰 때는 Long.js를 사용해야 합니다. 주로 fromString과 toString입니다.

  function fromString(str, unsigned, radix) {        if (str.length === 0)            throw Error('empty string');        if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")            return ZERO;        if (typeof unsigned === 'number') {            // For goog.math.long compatibility
            radix = unsigned,
            unsigned = false;
        } else {
            unsigned = !!unsigned;
        }
        radix = radix || 10;        if (radix < 2 || 36 < radix)            throw RangeError(&#39;radix&#39;);        var p;        if ((p = str.indexOf(&#39;-&#39;)) > 0)            throw Error('interior hyphen');        else if (p === 0) {            return fromString(str.substring(1), unsigned, radix).neg();
        }        // Do several (8) digits each time through the loop, so as to
        // minimize the calls to the very expensive emulated p.
        var radixToPower = fromNumber(pow_dbl(radix, 8));        var result = ZERO;        for (var i = 0; i < str.length; i += 8) {            var size = Math.min(8, str.length - i),                value = parseInt(str.substring(i, i + size), radix);            if (size < 8) {                var power = fromNumber(pow_dbl(radix, size));
                result = result.mul(power).add(fromNumber(value));
            } else {                result = result.mul(radixToPower);
                result = result.add(fromNumber(value));
            }
        }
        result.unsigned = unsigned;        return result;
    }

fromstring의 아이디어는

string8자리를 하나씩 가로채는 것입니다. 그런 다음 Long 유형(상위 비트, 위치, 부호 비트)으로 변환하여 추가합니다. 마지막은 용의 형상이다. 4294967296은 2의 32제곱입니다. 각 연산 전에 기수 연산 mul(radixToPower) 또는 mul(power)이 있으며 둘 다 결과의 자릿수가 올바른지 확인합니다.

예를 들어, {low:123}과 {low:1}을 더하기 전에 먼저 {low:123}에 10을 곱하여 {low:1230}을 얻은 다음 {low:1}로 비트 연산을 수행합니다. 첫 번째는 높은 위치이므로 직접 추가할 수 없습니다.

function fromBits(lowBits, highBits, unsigned) {        return new Long(lowBits, highBits, unsigned);
    }

fromBits는 Long

object로 변환됩니다. value%4294967296은 낮은 비트를 가져옵니다. /취해. 결과는 변위로 결합됩니다. mul은 비트의 곱이고 add는 비트의 추가입니다. 원칙은 64비트 파일을 4개의 세그먼트로 분할하는 것입니다. 각각 16비트. this.low를 왼쪽으로 16비트만큼 이동하여 32-17비트의 low를 얻습니다. 그런 다음 add 개체를 사용하여 동일한 위치를 추가합니다.

최종 병합은 | 작업을 통해 이루어집니다. 변위 후 복원하는 것은 정말 영리합니다. 나는 한동안 그 말을 이해하지 못한 것 같았다.

 LongPrototype.add = function add(addend) {        if (!isLong(addend))
            addend = fromValue(addend);        // pide each number into 4 chunks of 16 bits, and then sum the chunks.
        var a48 = this.high >>> 16;        var a32 = this.high & 0xFFFF;        var a16 = this.low >>> 16;        var a00 = this.low & 0xFFFF;        var b48 = addend.high >>> 16;        var b32 = addend.high & 0xFFFF;        var b16 = addend.low >>> 16;        var b00 = addend.low & 0xFFFF;        var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
        c00 += a00 + b00;
        c16 += c00 >>> 16;
        c00 &= 0xFFFF;
        c16 += a16 + b16;
        c32 += c16 >>> 16;
        c16 &= 0xFFFF;
        c32 += a32 + b32;
        c48 += c32 >>> 16;
        c32 &= 0xFFFF;
        c48 += a48 + b48;
        c48 &= 0xFFFF;        return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
    };

>>>의 차이점은 무엇인가요? ? .

toString

LongPrototype.toString = function toString(radix) {
        radix = radix || 10;        if (radix < 2 || 36 < radix)            throw RangeError(&#39;radix&#39;);        if (this.isZero())            return &#39;0&#39;;        if (this.isNegative()) { // Unsigned Longs are never negative
            if (this.eq(MIN_VALUE)) {                // We need to change the Long value before it can be negated, so we remove
                // the bottom-most digit in this base and then recurse to do the rest.
                var radixLong = fromNumber(radix),
                    p = this.p(radixLong),
                    rem1 = p.mul(radixLong).sub(this);                return p.toString(radix) + rem1.toInt().toString(radix);
            } else
                return &#39;-&#39; + this.neg().toString(radix);
        }        // Do several (6) digits each time through the loop, so as to
        // minimize the calls to the very expensive emulated p.
        var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
            rem = this;        var result = &#39;&#39;;        while (true) {            var remp = rem.p(radixToPower),
                intval = rem.sub(remp.mul(radixToPower)).toInt() >>> 0,
                digits = intval.toString(radix);
            rem = remp;            if (rem.isZero())                return digits + result;            else {                while (digits.length < 6)
                    digits = '0' + digits;
                result = '' + digits + result;
            }
        }
    };
은 sub 뒤에도 표기됩니다. 즉, fromstring의 반대 연산입니다.

이 기사의 사례를 읽은 후 방법을 마스터했다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

추천 도서:

흥미로운 UglifyJS

JS가 자동으로 proto Js와 일치하도록 만드는 방법

위 내용은 protobuf.js 및 Long.js 사용에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:흥미로운 UglifyJS다음 기사:흥미로운 UglifyJS