|
| 1 | +using MessagePack; |
| 2 | +using MessagePack.Resolvers; |
| 3 | +using Microsoft.Extensions.Options; |
| 4 | +using Newtonsoft.Json.Bson; |
| 5 | +using Newtonsoft.Json.Linq; |
| 6 | +using System; |
| 7 | +using System.Collections; |
| 8 | +using System.Collections.Generic; |
| 9 | +using System.Collections.Immutable; |
| 10 | +using System.IO; |
| 11 | +using System.Reflection; |
| 12 | +using System.Runtime.CompilerServices; |
| 13 | +using System.Text; |
| 14 | + |
| 15 | +namespace Enyim.Caching.Memcached.Transcoders |
| 16 | +{ |
| 17 | + public class MessagePackTranscoder : DefaultTranscoder |
| 18 | + { |
| 19 | + private readonly MessagePackSerializerOptions _options; |
| 20 | + |
| 21 | + public MessagePackTranscoder() : this(CreateDefaultOptions()) |
| 22 | + { |
| 23 | + } |
| 24 | + |
| 25 | + public MessagePackTranscoder(MessagePackSerializerOptions options) |
| 26 | + { |
| 27 | + _options = options ?? CreateDefaultOptions(); |
| 28 | + } |
| 29 | + |
| 30 | + protected override ArraySegment<byte> SerializeObject(object value) |
| 31 | + { |
| 32 | + var bytes = MessagePackSerializer.Serialize(value, _options); |
| 33 | + return new ArraySegment<byte>(bytes, 0, bytes.Length); |
| 34 | + } |
| 35 | + |
| 36 | + protected override object DeserializeObject(ArraySegment<byte> value) |
| 37 | + { |
| 38 | + throw new NotSupportedException("Does not support typeless deserialization. Please use generic api."); |
| 39 | + } |
| 40 | + |
| 41 | + public override T Deserialize<T>(CacheItem item) |
| 42 | + { |
| 43 | + if (typeof(T).GetTypeCode() != TypeCode.Object || typeof(T) == typeof(byte[])) |
| 44 | + { |
| 45 | + var value = Deserialize(item); |
| 46 | + if (value != null) |
| 47 | + { |
| 48 | + if (typeof(T) == typeof(Guid)) |
| 49 | + { |
| 50 | + return (T)(object)new Guid((string)value); |
| 51 | + } |
| 52 | + else |
| 53 | + { |
| 54 | + return (T)value; |
| 55 | + } |
| 56 | + } |
| 57 | + else |
| 58 | + { |
| 59 | + return default; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return MessagePackSerializer.Deserialize<T>(item.Data, _options); |
| 64 | + } |
| 65 | + |
| 66 | + private static MessagePackSerializerOptions CreateDefaultOptions() |
| 67 | + { |
| 68 | + var resolver = CompositeResolver.Create( |
| 69 | + NativeDateTimeResolver.Instance, |
| 70 | + NativeGuidResolver.Instance, |
| 71 | + NativeDecimalResolver.Instance, |
| 72 | + ContractlessStandardResolverAllowPrivate.Instance, |
| 73 | + ContractlessStandardResolver.Instance); |
| 74 | + return MessagePackSerializerOptions.Standard.WithResolver(resolver); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments