View Javadoc

1   package com.atlassian.vcache.marshallers;
2   
3   import com.atlassian.annotations.Internal;
4   import com.atlassian.vcache.Marshaller;
5   import com.atlassian.vcache.MarshallerException;
6   
7   import java.util.Arrays;
8   import java.util.Optional;
9   
10  import static java.util.Objects.requireNonNull;
11  
12  /**
13   * Implementation for the {@link Optional} class.
14   * @param <T> the type held in the Optional.
15   *
16   * @since 1.3.0
17   * @deprecated since 1.5.0. Use the Atlassian Marshalling API and implementations instead.
18   */
19  @Internal
20  @Deprecated
21  class OptionalMarshaller<T> implements Marshaller<Optional<T>> {
22  
23      private final Marshaller<T> valueMarshaller;
24  
25      OptionalMarshaller(Marshaller<T> valueMarshaller) {
26          this.valueMarshaller = requireNonNull(valueMarshaller);
27      }
28  
29      @Override
30      public byte[] marshall(Optional<T> obj) throws MarshallerException {
31          if (!obj.isPresent()) {
32              return new byte[] {0};
33          }
34  
35          final byte[] valueBytes = valueMarshaller.marshall(obj.get());
36          final byte[] resultBytes = new byte[valueBytes.length + 1];
37          resultBytes[0] = 1;
38          System.arraycopy(valueBytes, 0, resultBytes, 1, valueBytes.length);
39          return resultBytes;
40      }
41  
42      @Override
43      public Optional<T> unmarshall(byte[] raw) throws MarshallerException {
44          if (raw[0] == 0) {
45              return Optional.empty();
46          }
47  
48          final byte[] valueBytes = Arrays.copyOfRange(raw, 1, raw.length);
49  
50          return Optional.of(valueMarshaller.unmarshall(valueBytes));
51      }
52  }