View Javadoc
1   /*
2    * Copyright 2021 TiKV Project Authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   */
17  
18  package org.tikv.common.codec;
19  
20  import com.google.common.primitives.Longs;
21  
22  public class CodecDataOutputLittleEndian extends CodecDataOutput {
23    public CodecDataOutputLittleEndian() {
24      super();
25    }
26  
27    public CodecDataOutputLittleEndian(int size) {
28      super(size);
29    }
30  
31    @Override
32    public void writeShort(int v) {
33      try {
34        s.write(v & 0xff);
35        s.write((v >> 8) & 0xff);
36      } catch (Exception e) {
37        throw new RuntimeException(e);
38      }
39    }
40  
41    @Override
42    public void writeChar(int v) {
43      writeShort(v);
44    }
45  
46    @Override
47    public void writeInt(int v) {
48      try {
49        s.write(v & 0xff);
50        s.write((v >> 8) & 0xff);
51        s.write((v >> 16) & 0xff);
52        s.write((v >> 24) & 0xff);
53      } catch (Exception e) {
54        throw new RuntimeException(e);
55      }
56    }
57  
58    @Override
59    public void writeLong(long v) {
60      byte[] bytes = Longs.toByteArray(Long.reverseBytes(v));
61      write(bytes, 0, bytes.length);
62    }
63  
64    @Override
65    public void writeFloat(float v) {
66      writeInt(Float.floatToIntBits(v));
67    }
68  
69    @Override
70    public void writeDouble(double v) {
71      writeLong(Double.doubleToLongBits(v));
72    }
73  }