Debian Codegraph @

closure-library/closure/goog/proto2/objectserializer.js

raw
1 // Copyright 2008 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 2 Serializer which serializes messages
17 * into anonymous, simplified JSON objects.
18 *
19 */
20
21 goog.provide('goog.proto2.ObjectSerializer');
22
23 goog.require('goog.asserts');
24 goog.require('goog.proto2.FieldDescriptor');
25 goog.require('goog.proto2.Serializer');
26 goog.require('goog.string');
27
28
29
30 /**
31 * ObjectSerializer, a serializer which turns Messages into simplified
32 * ECMAScript objects.
33 *
34 * @param {goog.proto2.ObjectSerializer.KeyOption=} opt_keyOption If specified,
35 * which key option to use when serializing/deserializing.
36 * @param {boolean=} opt_serializeBooleanAsNumber If specified and true, the
37 * serializer will convert boolean values to 0/1 representation.
38 * @constructor
39 * @extends {goog.proto2.Serializer}
40 */
41 goog.proto2.ObjectSerializer = function(
42 opt_keyOption, opt_serializeBooleanAsNumber) {
43 this.keyOption_ = opt_keyOption;
44 this.serializeBooleanAsNumber_ = opt_serializeBooleanAsNumber;
45 };
46 goog.inherits(goog.proto2.ObjectSerializer, goog.proto2.Serializer);
47
48
49 /**
50 * An enumeration of the options for how to emit the keys in
51 * the generated simplified object.
52 *
53 * For serialization, the option specifies the keys to use in the serialized
54 * object.
55 *
56 * For deserialization, the option specifies which keys are allowed; an object
57 * serialized by TAG may be deserialized by TAG or by NAME or by
58 * CAMEL_CASE_NAME, but an object serialized by NAME cannot be deserialized by
59 * TAG. An object serialized with any option can be deserialized by
60 * CAMEL_CASE_NAME.
61 *
62 * @enum {number}
63 */
64 goog.proto2.ObjectSerializer.KeyOption = {
65 /**
66 * Use the tag of the field as the key (default)
67 */
68 TAG: 0,
69
70 /**
71 * Use the name of the field as the key. Unknown fields
72 * will still use their tags as keys.
73 */
74 NAME: 1,
75
76 /**
77 * Use the camel cased name of the field as the key.
78 * Unknown fields will still use their tags as keys.
79 */
80 CAMEL_CASE_NAME: 2
81 };
82
83
84 /**
85 * Serializes a message to an object.
86 *
87 * @param {goog.proto2.Message} message The message to be serialized.
88 * @return {!Object} The serialized form of the message.
89 * @override
90 */
91 goog.proto2.ObjectSerializer.prototype.serialize = function(message) {
92 var descriptor = message.getDescriptor();
93 var fields = descriptor.getFields();
94
95 var objectValue = {};
96
97 // Add the defined fields, recursively.
98 for (var i = 0; i < fields.length; i++) {
99 var field = fields[i];
100
101 var key = field.getTag();
102 switch (this.keyOption_) {
103 case goog.proto2.ObjectSerializer.KeyOption.TAG:
104 // no action necessary, key already has the correct value.
105 break;
106 case goog.proto2.ObjectSerializer.KeyOption.NAME:
107 key = field.getName();
108 break;
109 case goog.proto2.ObjectSerializer.KeyOption.CAMEL_CASE_NAME:
110 key = goog.string.toCamelCase(
111 field
112 .getName()
113 // goog.string.toCamelCase expects a hyphen delimited string but
114 // proto fields are usually underscore delimited
115 // (go/proto-style-guide); the following regex converts from
116 // underscore delimited form to hyphen delimited form.
117 .replace(/_/g, '-'));
118 break;
119 default:
120 // Default should never be reached unless keyOption is outside the valid
121 // domain.
122 goog.asserts.assert(
123 this.keyOption_ !== goog.proto2.ObjectSerializer.KeyOption.TAG &&
124 this.keyOption_ !==
125 goog.proto2.ObjectSerializer.KeyOption.NAME &&
126 this.keyOption_ !==
127 goog.proto2.ObjectSerializer.KeyOption.CAMEL_CASE_NAME,
128 'keyOption should be one of TAG, NAME, or CAMEL_CASE_NAME');
129 }
130
131 if (message.has(field)) {
132 if (field.isRepeated()) {
133 var array = [];
134 objectValue[key] = array;
135
136 for (var j = 0; j < message.countOf(field); j++) {
137 array.push(this.getSerializedValue(field, message.get(field, j)));
138 }
139
140 } else {
141 objectValue[key] = this.getSerializedValue(field, message.get(field));
142 }
143 }
144 }
145
146 // Add the unknown fields, if any.
147 message.forEachUnknown(function(tag, value) { objectValue[tag] = value; });
148
149 return objectValue;
150 };
151
152
153 /** @override */
154 goog.proto2.ObjectSerializer.prototype.getSerializedValue = function(
155 field, value) {
156
157 // Handle the case where a boolean should be serialized as 0/1.
158 // Some deserialization libraries, such as GWT, can use this notation.
159 if (this.serializeBooleanAsNumber_ &&
160 field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.BOOL &&
161 goog.isBoolean(value)) {
162 return value ? 1 : 0;
163 }
164
165 return goog.proto2.ObjectSerializer.base(
166 this, 'getSerializedValue', field, value);
167 };
168
169
170 /** @override */
171 goog.proto2.ObjectSerializer.prototype.getDeserializedValue = function(
172 field, value) {
173
174 // Gracefully handle the case where a boolean is represented by 0/1.
175 // Some serialization libraries, such as GWT, can use this notation.
176 if (field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.BOOL &&
177 goog.isNumber(value)) {
178 return Boolean(value);
179 }
180
181 return goog.proto2.ObjectSerializer.base(
182 this, 'getDeserializedValue', field, value);
183 };
184
185
186 /**
187 * Deserializes a message from an object and places the
188 * data in the message.
189 *
190 * @param {goog.proto2.Message} message The message in which to
191 * place the information.
192 * @param {*} data The data of the message.
193 * @override
194 */
195 goog.proto2.ObjectSerializer.prototype.deserializeTo = function(message, data) {
196 var descriptor = message.getDescriptor();
197
198 for (var key in data) {
199 var field;
200 var value = data[key];
201
202 var isNumeric = goog.string.isNumeric(key);
203
204 if (isNumeric) {
205 field = descriptor.findFieldByTag(key);
206 } else {
207 // We must not be in Key == TAG mode to lookup by name.
208 goog.asserts.assert(
209 this.keyOption_ == goog.proto2.ObjectSerializer.KeyOption.NAME ||
210 this.keyOption_ ==
211 goog.proto2.ObjectSerializer.KeyOption.CAMEL_CASE_NAME,
212 'Key mode ' + this.keyOption_ + 'for key ' + key + ' is not ' +
213 goog.proto2.ObjectSerializer.KeyOption.NAME + ' nor ' +
214 goog.proto2.ObjectSerializer.KeyOption.CAMEL_CASE_NAME);
215
216 if (this.keyOption_ ==
217 goog.proto2.ObjectSerializer.KeyOption.CAMEL_CASE_NAME) {
218 key = goog.string
219 .toSelectorCase(key)
220 // goog.string.toSelectorCase returns a hyphen delimited form
221 // of the name but protos usually use an underscore delimited
222 // form (go/proto-style-guide); the following regex converts
223 // from hyphens to underscores.
224 .replace(/\-/g, '_');
225 }
226 field = descriptor.findFieldByName(key);
227 }
228
229 if (field) {
230 if (field.isRepeated()) {
231 goog.asserts.assert(
232 goog.isArray(value),
233 'Value for repeated field ' + field + ' must be an array.');
234
235 for (var j = 0; j < value.length; j++) {
236 message.add(field, this.getDeserializedValue(field, value[j]));
237 }
238 } else {
239 goog.asserts.assert(
240 !goog.isArray(value),
241 'Value for non-repeated field ' + field + ' must not be an array.');
242 message.set(field, this.getDeserializedValue(field, value));
243 }
244 } else {
245 if (isNumeric) {
246 // We have an unknown field.
247 message.setUnknown(Number(key), value);
248 } else {
249 // Named fields must be present.
250 goog.asserts.fail('Failed to find field: ' + key);
251 }
252 }
253 }
254 };