Home Web Front-end JS Tutorial Detailed explanation of the use of protobuf.js and Long.js

Detailed explanation of the use of protobuf.js and Long.js

Mar 16, 2018 am 10:58 AM
javascript

This time I bring you a detailed explanation of the use of protobuf.js and Long.js. What are the precautions when using protobuf.js and Long.js urgently? Here are practical cases. Let’s take a look. .

The structure of protobuf.js is very similar to the structure of webpack after loading. This modular combination is a good structural method. One is adapted to different loading methods, and the two modules are directly independent. webpack is more functional. But if you encapsulate the js library yourself, this is enough. Moreover, the module has a unified external interfacemodule.exports. This is very similar to node.

(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)
Copy after login
You have to use Long.js when processing integers exceeding 16 bits. Mainly fromString and toString. The idea of ​​

  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;
    }
Copy after login

fromstring is to intercept

string8 digits one by one. Then convert it to Long type (high bit, position, sign bit) and add it up. The last one is a dragon. 4294967296 is 2 raised to the 32nd power. Before each operation, there will be a radix operation mul(radixToPower) or mul(power), both of which ensure that the number of digits in the result is correct.

For example, before adding {low:123} and {low:1}, first multiply {low:123} by 10 to get {low:1230} and then perform bit operations with {low:1} . Because the first one is a high position, it cannot be added directly.

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

fromBits is converted to Long

object. value%4294967296 gets the low bit. /get high position. The results are combined by displacement. mul is the multiplication of bits, and add is the addition of bits. The principle is to split a 64-bit file into four segments. 16 bits respectively. Shift this.low left by 16 bits to get the 32-17 bits of low. Then add it to the same position of the addend object

The final merger is through the | operation. It's really clever to restore it after displacement. I didn't seem to understand it for a while.

 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);
    };
Copy after login

>>> What is the difference between >>? ? .

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;
            }
        }
    };
Copy after login
is also spelled out after sub. That is, the reverse operation of fromstring.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Interesting UglifyJS

How to let JS automatically match proto Js

The above is the detailed content of Detailed explanation of the use of protobuf.js and Long.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles