OLD | NEW |
1 # Protocol Buffers - Google's data interchange format | 1 # Protocol Buffers - Google's data interchange format |
2 # Copyright 2008 Google Inc. All rights reserved. | 2 # Copyright 2008 Google Inc. All rights reserved. |
3 # https://developers.google.com/protocol-buffers/ | 3 # https://developers.google.com/protocol-buffers/ |
4 # | 4 # |
5 # Redistribution and use in source and binary forms, with or without | 5 # Redistribution and use in source and binary forms, with or without |
6 # modification, are permitted provided that the following conditions are | 6 # modification, are permitted provided that the following conditions are |
7 # met: | 7 # met: |
8 # | 8 # |
9 # * Redistributions of source code must retain the above copyright | 9 # * Redistributions of source code must retain the above copyright |
10 # notice, this list of conditions and the following disclaimer. | 10 # notice, this list of conditions and the following disclaimer. |
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
46 | 46 |
47 from google.protobuf.descriptor import FieldDescriptor | 47 from google.protobuf.descriptor import FieldDescriptor |
48 | 48 |
49 _TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S' | 49 _TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S' |
50 _NANOS_PER_SECOND = 1000000000 | 50 _NANOS_PER_SECOND = 1000000000 |
51 _NANOS_PER_MILLISECOND = 1000000 | 51 _NANOS_PER_MILLISECOND = 1000000 |
52 _NANOS_PER_MICROSECOND = 1000 | 52 _NANOS_PER_MICROSECOND = 1000 |
53 _MILLIS_PER_SECOND = 1000 | 53 _MILLIS_PER_SECOND = 1000 |
54 _MICROS_PER_SECOND = 1000000 | 54 _MICROS_PER_SECOND = 1000000 |
55 _SECONDS_PER_DAY = 24 * 3600 | 55 _SECONDS_PER_DAY = 24 * 3600 |
| 56 _DURATION_SECONDS_MAX = 315576000000 |
56 | 57 |
57 | 58 |
58 class Error(Exception): | 59 class Error(Exception): |
59 """Top-level module error.""" | 60 """Top-level module error.""" |
60 | 61 |
61 | 62 |
62 class ParseError(Error): | 63 class ParseError(Error): |
63 """Thrown in case of parsing error.""" | 64 """Thrown in case of parsing error.""" |
64 | 65 |
65 | 66 |
(...skipping 174 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
240 | 241 |
241 def ToJsonString(self): | 242 def ToJsonString(self): |
242 """Converts Duration to string format. | 243 """Converts Duration to string format. |
243 | 244 |
244 Returns: | 245 Returns: |
245 A string converted from self. The string format will contains | 246 A string converted from self. The string format will contains |
246 3, 6, or 9 fractional digits depending on the precision required to | 247 3, 6, or 9 fractional digits depending on the precision required to |
247 represent the exact Duration value. For example: "1s", "1.010s", | 248 represent the exact Duration value. For example: "1s", "1.010s", |
248 "1.000000100s", "-3.100s" | 249 "1.000000100s", "-3.100s" |
249 """ | 250 """ |
| 251 _CheckDurationValid(self.seconds, self.nanos) |
250 if self.seconds < 0 or self.nanos < 0: | 252 if self.seconds < 0 or self.nanos < 0: |
251 result = '-' | 253 result = '-' |
252 seconds = - self.seconds + int((0 - self.nanos) // 1e9) | 254 seconds = - self.seconds + int((0 - self.nanos) // 1e9) |
253 nanos = (0 - self.nanos) % 1e9 | 255 nanos = (0 - self.nanos) % 1e9 |
254 else: | 256 else: |
255 result = '' | 257 result = '' |
256 seconds = self.seconds + int(self.nanos // 1e9) | 258 seconds = self.seconds + int(self.nanos // 1e9) |
257 nanos = self.nanos % 1e9 | 259 nanos = self.nanos % 1e9 |
258 result += '%d' % seconds | 260 result += '%d' % seconds |
259 if (nanos % 1e9) == 0: | 261 if (nanos % 1e9) == 0: |
(...skipping 19 matching lines...) Expand all Loading... |
279 | 281 |
280 Raises: | 282 Raises: |
281 ParseError: On parsing problems. | 283 ParseError: On parsing problems. |
282 """ | 284 """ |
283 if len(value) < 1 or value[-1] != 's': | 285 if len(value) < 1 or value[-1] != 's': |
284 raise ParseError( | 286 raise ParseError( |
285 'Duration must end with letter "s": {0}.'.format(value)) | 287 'Duration must end with letter "s": {0}.'.format(value)) |
286 try: | 288 try: |
287 pos = value.find('.') | 289 pos = value.find('.') |
288 if pos == -1: | 290 if pos == -1: |
289 self.seconds = int(value[:-1]) | 291 seconds = int(value[:-1]) |
290 self.nanos = 0 | 292 nanos = 0 |
291 else: | 293 else: |
292 self.seconds = int(value[:pos]) | 294 seconds = int(value[:pos]) |
293 if value[0] == '-': | 295 if value[0] == '-': |
294 self.nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9)) | 296 nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9)) |
295 else: | 297 else: |
296 self.nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9)) | 298 nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9)) |
| 299 _CheckDurationValid(seconds, nanos) |
| 300 self.seconds = seconds |
| 301 self.nanos = nanos |
297 except ValueError: | 302 except ValueError: |
298 raise ParseError( | 303 raise ParseError( |
299 'Couldn\'t parse duration: {0}.'.format(value)) | 304 'Couldn\'t parse duration: {0}.'.format(value)) |
300 | 305 |
301 def ToNanoseconds(self): | 306 def ToNanoseconds(self): |
302 """Converts a Duration to nanoseconds.""" | 307 """Converts a Duration to nanoseconds.""" |
303 return self.seconds * _NANOS_PER_SECOND + self.nanos | 308 return self.seconds * _NANOS_PER_SECOND + self.nanos |
304 | 309 |
305 def ToMicroseconds(self): | 310 def ToMicroseconds(self): |
306 """Converts a Duration to microseconds.""" | 311 """Converts a Duration to microseconds.""" |
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
352 def _NormalizeDuration(self, seconds, nanos): | 357 def _NormalizeDuration(self, seconds, nanos): |
353 """Set Duration by seconds and nonas.""" | 358 """Set Duration by seconds and nonas.""" |
354 # Force nanos to be negative if the duration is negative. | 359 # Force nanos to be negative if the duration is negative. |
355 if seconds < 0 and nanos > 0: | 360 if seconds < 0 and nanos > 0: |
356 seconds += 1 | 361 seconds += 1 |
357 nanos -= _NANOS_PER_SECOND | 362 nanos -= _NANOS_PER_SECOND |
358 self.seconds = seconds | 363 self.seconds = seconds |
359 self.nanos = nanos | 364 self.nanos = nanos |
360 | 365 |
361 | 366 |
| 367 def _CheckDurationValid(seconds, nanos): |
| 368 if seconds < -_DURATION_SECONDS_MAX or seconds > _DURATION_SECONDS_MAX: |
| 369 raise Error( |
| 370 'Duration is not valid: Seconds {0} must be in range ' |
| 371 '[-315576000000, 315576000000].'.format(seconds)) |
| 372 if nanos <= -_NANOS_PER_SECOND or nanos >= _NANOS_PER_SECOND: |
| 373 raise Error( |
| 374 'Duration is not valid: Nanos {0} must be in range ' |
| 375 '[-999999999, 999999999].'.format(nanos)) |
| 376 |
| 377 |
362 def _RoundTowardZero(value, divider): | 378 def _RoundTowardZero(value, divider): |
363 """Truncates the remainder part after division.""" | 379 """Truncates the remainder part after division.""" |
364 # For some languanges, the sign of the remainder is implementation | 380 # For some languanges, the sign of the remainder is implementation |
365 # dependent if any of the operands is negative. Here we enforce | 381 # dependent if any of the operands is negative. Here we enforce |
366 # "rounded toward zero" semantics. For example, for (-5) / 2 an | 382 # "rounded toward zero" semantics. For example, for (-5) / 2 an |
367 # implementation may give -3 as the result with the remainder being | 383 # implementation may give -3 as the result with the remainder being |
368 # 1. This function ensures we always return -2 (closer to zero). | 384 # 1. This function ensures we always return -2 (closer to zero). |
369 result = value // divider | 385 result = value // divider |
370 remainder = value % divider | 386 remainder = value % divider |
371 if result < 0 and remainder > 0: | 387 if result < 0 and remainder > 0: |
372 return result + 1 | 388 return result + 1 |
373 else: | 389 else: |
374 return result | 390 return result |
375 | 391 |
376 | 392 |
377 class FieldMask(object): | 393 class FieldMask(object): |
378 """Class for FieldMask message type.""" | 394 """Class for FieldMask message type.""" |
379 | 395 |
380 def ToJsonString(self): | 396 def ToJsonString(self): |
381 """Converts FieldMask to string according to proto3 JSON spec.""" | 397 """Converts FieldMask to string according to proto3 JSON spec.""" |
382 return ','.join(self.paths) | 398 camelcase_paths = [] |
| 399 for path in self.paths: |
| 400 camelcase_paths.append(_SnakeCaseToCamelCase(path)) |
| 401 return ','.join(camelcase_paths) |
383 | 402 |
384 def FromJsonString(self, value): | 403 def FromJsonString(self, value): |
385 """Converts string to FieldMask according to proto3 JSON spec.""" | 404 """Converts string to FieldMask according to proto3 JSON spec.""" |
386 self.Clear() | 405 self.Clear() |
387 for path in value.split(','): | 406 for path in value.split(','): |
388 self.paths.append(path) | 407 self.paths.append(_CamelCaseToSnakeCase(path)) |
389 | 408 |
390 def IsValidForDescriptor(self, message_descriptor): | 409 def IsValidForDescriptor(self, message_descriptor): |
391 """Checks whether the FieldMask is valid for Message Descriptor.""" | 410 """Checks whether the FieldMask is valid for Message Descriptor.""" |
392 for path in self.paths: | 411 for path in self.paths: |
393 if not _IsValidPath(message_descriptor, path): | 412 if not _IsValidPath(message_descriptor, path): |
394 return False | 413 return False |
395 return True | 414 return True |
396 | 415 |
397 def AllFieldsFromDescriptor(self, message_descriptor): | 416 def AllFieldsFromDescriptor(self, message_descriptor): |
398 """Gets all direct fields of Message Descriptor to FieldMask.""" | 417 """Gets all direct fields of Message Descriptor to FieldMask.""" |
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
465 | 484 |
466 def _CheckFieldMaskMessage(message): | 485 def _CheckFieldMaskMessage(message): |
467 """Raises ValueError if message is not a FieldMask.""" | 486 """Raises ValueError if message is not a FieldMask.""" |
468 message_descriptor = message.DESCRIPTOR | 487 message_descriptor = message.DESCRIPTOR |
469 if (message_descriptor.name != 'FieldMask' or | 488 if (message_descriptor.name != 'FieldMask' or |
470 message_descriptor.file.name != 'google/protobuf/field_mask.proto'): | 489 message_descriptor.file.name != 'google/protobuf/field_mask.proto'): |
471 raise ValueError('Message {0} is not a FieldMask.'.format( | 490 raise ValueError('Message {0} is not a FieldMask.'.format( |
472 message_descriptor.full_name)) | 491 message_descriptor.full_name)) |
473 | 492 |
474 | 493 |
| 494 def _SnakeCaseToCamelCase(path_name): |
| 495 """Converts a path name from snake_case to camelCase.""" |
| 496 result = [] |
| 497 after_underscore = False |
| 498 for c in path_name: |
| 499 if c.isupper(): |
| 500 raise Error('Fail to print FieldMask to Json string: Path name ' |
| 501 '{0} must not contain uppercase letters.'.format(path_name)) |
| 502 if after_underscore: |
| 503 if c.islower(): |
| 504 result.append(c.upper()) |
| 505 after_underscore = False |
| 506 else: |
| 507 raise Error('Fail to print FieldMask to Json string: The ' |
| 508 'character after a "_" must be a lowercase letter ' |
| 509 'in path name {0}.'.format(path_name)) |
| 510 elif c == '_': |
| 511 after_underscore = True |
| 512 else: |
| 513 result += c |
| 514 |
| 515 if after_underscore: |
| 516 raise Error('Fail to print FieldMask to Json string: Trailing "_" ' |
| 517 'in path name {0}.'.format(path_name)) |
| 518 return ''.join(result) |
| 519 |
| 520 |
| 521 def _CamelCaseToSnakeCase(path_name): |
| 522 """Converts a field name from camelCase to snake_case.""" |
| 523 result = [] |
| 524 for c in path_name: |
| 525 if c == '_': |
| 526 raise ParseError('Fail to parse FieldMask: Path name ' |
| 527 '{0} must not contain "_"s.'.format(path_name)) |
| 528 if c.isupper(): |
| 529 result += '_' |
| 530 result += c.lower() |
| 531 else: |
| 532 result += c |
| 533 return ''.join(result) |
| 534 |
| 535 |
475 class _FieldMaskTree(object): | 536 class _FieldMaskTree(object): |
476 """Represents a FieldMask in a tree structure. | 537 """Represents a FieldMask in a tree structure. |
477 | 538 |
478 For example, given a FieldMask "foo.bar,foo.baz,bar.baz", | 539 For example, given a FieldMask "foo.bar,foo.baz,bar.baz", |
479 the FieldMaskTree will be: | 540 the FieldMaskTree will be: |
480 [_root] -+- foo -+- bar | 541 [_root] -+- foo -+- bar |
481 | | | 542 | | |
482 | +- baz | 543 | +- baz |
483 | | 544 | |
484 +- bar --- baz | 545 +- bar --- baz |
(...skipping 230 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
715 | 776 |
716 | 777 |
717 WKTBASES = { | 778 WKTBASES = { |
718 'google.protobuf.Any': Any, | 779 'google.protobuf.Any': Any, |
719 'google.protobuf.Duration': Duration, | 780 'google.protobuf.Duration': Duration, |
720 'google.protobuf.FieldMask': FieldMask, | 781 'google.protobuf.FieldMask': FieldMask, |
721 'google.protobuf.ListValue': ListValue, | 782 'google.protobuf.ListValue': ListValue, |
722 'google.protobuf.Struct': Struct, | 783 'google.protobuf.Struct': Struct, |
723 'google.protobuf.Timestamp': Timestamp, | 784 'google.protobuf.Timestamp': Timestamp, |
724 } | 785 } |
OLD | NEW |