Source code for transit.read_handlers

## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
##      http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS-IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.

import transit_types
from constants import *
import uuid
import ctypes
import dateutil.parser
import datetime
import dateutil.tz
from helpers import pairs

## Read handlers are used by the decoder when parsing/reading in Transit
## data and returning Python objects

[docs]class DefaultHandler(object): @staticmethod
[docs] def from_rep(t, v): return transit_types.TaggedValue(t, v)
[docs]class NoneHandler(object): @staticmethod
[docs] def from_rep(_): return None
[docs]class KeywordHandler(object): @staticmethod
[docs] def from_rep(v): return transit_types.Keyword(v)
[docs]class SymbolHandler(object): @staticmethod
[docs] def from_rep(v): return transit_types.Symbol(v)
[docs]class BooleanHandler(object): @staticmethod
[docs] def from_rep(x): return x == "t"
[docs]class IntHandler(object): @staticmethod
[docs] def from_rep(v): return int(v)
[docs]class FloatHandler(object): @staticmethod
[docs] def from_rep(v): return float(v)
[docs]class UuidHandler(object): @staticmethod
[docs] def from_rep(u): """ Given a string, return a UUID object""" if isinstance(u, basestring): return uuid.UUID(u) # hack to remove signs a = ctypes.c_ulong(u[0]) b = ctypes.c_ulong(u[1]) combined = a.value << 64 | b.value return uuid.UUID(int=combined)
[docs]class UriHandler(object): @staticmethod
[docs] def from_rep(u): return transit_types.URI(u)
[docs]class DateHandler(object): @staticmethod
[docs] def from_rep(d): if isinstance(d, (long, int)): return DateHandler._convert_timestamp(d) if "T" in d: return dateutil.parser.parse(d) return DateHandler._convert_timestamp(long(d))
@staticmethod def _convert_timestamp(ms): """ Given a timestamp in ms, return a DateTime object""" return datetime.datetime.fromtimestamp(ms/1000.0, dateutil.tz.tzutc())
[docs]class BigIntegerHandler(object): @staticmethod
[docs] def from_rep(d): return long(d)
[docs]class LinkHandler(object): @staticmethod
[docs] def from_rep(l): return transit_types.Link(**l)
[docs]class ListHandler(object): @staticmethod
[docs] def from_rep(l): return l
[docs]class SetHandler(object): @staticmethod
[docs] def from_rep(s): return frozenset(s)
[docs]class CmapHandler(object): @staticmethod
[docs] def from_rep(cmap): return transit_types.frozendict(pairs(cmap))
[docs]class IdentityHandler(object): @staticmethod
[docs] def from_rep(i): return i