| 1 |
// Copyright 2007 The Closure Library Authors. All Rights Reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS-IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
/** |
| 16 |
* @fileoverview Protocol buffer serializer. |
| 17 |
* @author [email protected] (Erik Arvidsson) |
| 18 |
*/ |
| 19 |
|
| 20 |
|
| 21 |
// TODO(arv): Serialize booleans as 0 and 1 |
| 22 |
|
| 23 |
|
| 24 |
goog.provide('goog.proto.Serializer'); |
| 25 |
|
| 26 |
|
| 27 |
goog.require('goog.json.Serializer'); |
| 28 |
goog.require('goog.string'); |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
/** |
| 33 |
* Object that can serialize objects or values to a protocol buffer string. |
| 34 |
* @constructor |
| 35 |
* @extends {goog.json.Serializer} |
| 36 |
* @final |
| 37 |
*/ |
| 38 |
goog.proto.Serializer = function() { |
| 39 |
goog.json.Serializer.call(this); |
| 40 |
}; |
| 41 |
goog.inherits(goog.proto.Serializer, goog.json.Serializer); |
| 42 |
|
| 43 |
|
| 44 |
/** |
| 45 |
* Serializes an array to a protocol buffer string. This overrides the JSON |
| 46 |
* method to don't output trailing null or undefined. |
| 47 |
* @param {Array<*>} arr The array to serialize. |
| 48 |
* @param {Array<string>} sb Array used as a string builder. |
| 49 |
* @override |
| 50 |
*/ |
| 51 |
goog.proto.Serializer.prototype.serializeArray = function(arr, sb) { |
| 52 |
var l = arr.length; |
| 53 |
sb.push('['); |
| 54 |
var emptySlots = 0; |
| 55 |
var sep = ''; |
| 56 |
for (var i = 0; i < l; i++) { |
| 57 |
if (arr[i] == null) { // catches undefined as well |
| 58 |
emptySlots++; |
| 59 |
} else { |
| 60 |
sb.push(sep); |
| 61 |
if (emptySlots > 0) { |
| 62 |
sb.push(goog.string.repeat('null,', emptySlots)); |
| 63 |
emptySlots = 0; |
| 64 |
} |
| 65 |
this.serializeInternal(arr[i], sb); |
| 66 |
sep = ','; |
| 67 |
} |
| 68 |
} |
| 69 |
sb.push(']'); |
| 70 |
}; |