Uploaded image for project: 'Apache Cassandra'
  1. Apache Cassandra
  2. CASSANDRA-16218

Simplify the almost duplicated code for calculating serialization size and serialization

    XMLWordPrintableJSON

Details

    • Code Clarity
    • Normal
    • All
    • None

    Description

      The current pattern of counting the serialization size and the actual serialization in the codebase is error-prone and hard to maintain. Those 2 code paths have almost the same code repeated. 
       
      The pattern can be found in org.apache.cassandra.net.Message#Serializer and numerous locations that use org.apache.cassandra.transport.CBCodec
       
      I am proposing a new approach that lets both methods share the same code path. The code basically looks like the below (in the case of org.apache.cassandra.net.Message#Serializer).

      // A fake DataOutputPlus that simply increment the size when invoking write* methods
      public class SizeCountingDataOutput implements DataOutputPlus
      {
       private int size = 0;
      
       public int getSize()
       {
         return size;
       }
      
       public void write(int b)
       {
         size += 1;
       }
      
       public void write(byte[] b)
       {
         size += b.length;
       }
       ...
      }
      

      Therefore, in the size calculation, we can supply the fake data output and call serialize to get the size.

      private <T> int serializedSize(Message<T> message, int version)
      {
       SizeCountingDataOutput out = new SizeCountingDataOutput();
       try
       {
         serialize(message, out, version);
       }
       catch (IOException exception)
       {
         throw new AssertionError("It should not happen!", exception);
       }
       return out.getSize();
      // The original implementation
      // return version >= VERSION_40 ? serializedSizePost40(message, version) : serializedSizePre40(message, version);
      }
      

      Attachments

        Issue Links

          Activity

            People

              yifanc Yifan Cai
              yifanc Yifan Cai
              Yifan Cai
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: