This repository has been archived by the owner on May 25, 2021. It is now read-only.
/
CassandraObjectConverter.cs
75 lines (59 loc) · 1.82 KB
/
CassandraObjectConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Linq;
using System.ComponentModel;
namespace FluentCassandra.Types
{
internal abstract class CassandraObjectConverter<T>
{
public abstract bool CanConvertFrom(Type sourceType);
public abstract bool CanConvertTo(Type destinationType);
public abstract T ConvertFromInternal(object value);
public abstract object ConvertToInternal(T value, Type destinationType);
public TDestination ConvertTo<TDestination>(T value)
{
return (TDestination)ConvertTo(value, typeof(TDestination));
}
public object ConvertTo(T value, Type destinationType)
{
if (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
var nc = new NullableConverter(destinationType);
destinationType = nc.UnderlyingType;
}
if (!CanConvertTo(destinationType))
throw new InvalidCastException(String.Format("{0} cannot be cast to {1}", typeof(T), destinationType));
return ConvertToInternal(value, destinationType);
}
public T ConvertFrom(object obj)
{
if (obj is CassandraObject)
return ((CassandraObject)obj).GetValue<T>();
if (!CanConvertFrom(obj.GetType()))
throw new InvalidCastException(String.Format("{0} cannot be cast to {1}", obj.GetType(), typeof(T)));
return ConvertFromInternal(obj);
}
public virtual byte[] ToBigEndian(T value)
{
var bytes = ConvertTo<byte[]>(value);
return ConvertEndian(bytes);
}
public virtual T FromBigEndian(byte[] value)
{
if (value == null)
return default(T);
var bytes = ConvertEndian(value);
var obj = ConvertFromInternal(bytes);
return obj;
}
protected byte[] ConvertEndian(byte[] value)
{
if (System.BitConverter.IsLittleEndian)
{
var buffer = (byte[])value.Clone();
Array.Reverse(buffer);
return buffer;
}
return value;
}
}
}