1 /* Copyright 2002-2025 CS GROUP
2 * Licensed to CS GROUP (CS) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * CS licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.orekit.gnss.metric.parser;
18
19 import org.hipparchus.util.FastMath;
20 import org.orekit.errors.OrekitException;
21 import org.orekit.errors.OrekitMessages;
22
23 /** Encoded messages as a sequence of bytes.
24 * <p>
25 * Note that only full bytes are supported. This means that for example
26 * the 300 bits message from GPS sub-frames must be completed with 4 zero
27 * bits to reach 304 bits = 38 bytes, even if only the first 300 bits
28 * will be decoded and the 4 extra bits in the last byte will be ignored.
29 * </p>
30 * @author Luc Maisonobe
31 * @since 11.0
32 */
33 public abstract class AbstractEncodedMessage implements EncodedMessage {
34
35 /** Current byte (as an int). */
36 private int current;
37
38 /** Remaining bits in current byte. */
39 private int remaining;
40
41 /** Empty constructor.
42 * <p>
43 * This constructor is not strictly necessary, but it prevents spurious
44 * javadoc warnings with JDK 18 and later.
45 * </p>
46 * @since 12.0
47 */
48 public AbstractEncodedMessage() {
49 // nothing to do
50 }
51
52 /** {@inheritDoc} */
53 @Override
54 public void start() {
55 this.remaining = 0;
56 }
57
58 /** Fetch the next byte from the message.
59 * @return next byte from the message, as a primitive integer,
60 * or -1 if end of data has been reached
61 */
62 protected abstract int fetchByte();
63
64 /** {@inheritDoc} */
65 @Override
66 public long extractBits(final int n) {
67
68 // safety check
69 if (n > 63) {
70 throw new OrekitException(OrekitMessages.TOO_LARGE_DATA_TYPE, n);
71 }
72
73 // initialization
74 long value = 0l;
75
76 // bits gathering loop
77 int needed = n;
78 while (needed > 0) {
79
80 if (remaining == 0) {
81 // we need to fetch one more byte
82 final int read = fetchByte();
83 if (read == -1) {
84 // end was unexpected
85 throw new OrekitException(OrekitMessages.END_OF_ENCODED_MESSAGE);
86 }
87 current = read & 0xFF;
88 remaining = 8;
89 }
90
91 final int nbBits = FastMath.min(remaining, needed);
92 value = (value << nbBits) | (current >>> (8 - nbBits));
93 current = (current << nbBits) & 0xFF;
94 remaining -= nbBits;
95 needed -= nbBits;
96
97 }
98
99 return value;
100
101 }
102
103 }