serializer.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. * @fileoverview Protocol buffer serializer.
  16. * @author arv@google.com (Erik Arvidsson)
  17. */
  18. // TODO(arv): Serialize booleans as 0 and 1
  19. goog.provide('goog.proto.Serializer');
  20. goog.require('goog.json.Serializer');
  21. goog.require('goog.string');
  22. /**
  23. * Object that can serialize objects or values to a protocol buffer string.
  24. * @constructor
  25. * @extends {goog.json.Serializer}
  26. * @final
  27. */
  28. goog.proto.Serializer = function() {
  29. goog.json.Serializer.call(this);
  30. };
  31. goog.inherits(goog.proto.Serializer, goog.json.Serializer);
  32. /**
  33. * Serializes an array to a protocol buffer string. This overrides the JSON
  34. * method to don't output trailing null or undefined.
  35. * @param {Array<*>} arr The array to serialize.
  36. * @param {Array<string>} sb Array used as a string builder.
  37. * @override
  38. */
  39. goog.proto.Serializer.prototype.serializeArray = function(arr, sb) {
  40. var l = arr.length;
  41. sb.push('[');
  42. var emptySlots = 0;
  43. var sep = '';
  44. for (var i = 0; i < l; i++) {
  45. if (arr[i] == null) { // catches undefined as well
  46. emptySlots++;
  47. } else {
  48. sb.push(sep);
  49. if (emptySlots > 0) {
  50. sb.push(goog.string.repeat('null,', emptySlots));
  51. emptySlots = 0;
  52. }
  53. this.serializeInternal(arr[i], sb);
  54. sep = ',';
  55. }
  56. }
  57. sb.push(']');
  58. };