Line data Source code
1 : /********************************************************************************
2 : * Copyright (c) 2026 Accenture
3 : *
4 : * This program and the accompanying materials are made available under the
5 : * terms of the Apache License Version 2.0 which is available at
6 : * https://www.apache.org/licenses/LICENSE-2.0
7 : *
8 : * SPDX-License-Identifier: Apache-2.0
9 : ********************************************************************************/
10 :
11 : #pragma once
12 :
13 : #include "someip/SomeIpParser.h"
14 : #include "someip/SomeIpSerializer.h"
15 :
16 : #include <etl/span.h>
17 : #include <etl/unaligned_type.h>
18 :
19 : namespace someip
20 : {
21 : template<class LENGTH_TYPE>
22 : class LengthSerializerHelper
23 : {
24 : public:
25 12 : explicit LengthSerializerHelper(SomeIpSerializer& serializer)
26 12 : : serializer(serializer)
27 12 : , lengthBuffer(serializer.skipBytes(sizeof(LENGTH_TYPE)))
28 12 : , writingStartPos(serializer.getCurrentPosition())
29 :
30 12 : {}
31 :
32 12 : ~LengthSerializerHelper()
33 : {
34 12 : if (lengthBuffer.size() == sizeof(LENGTH_TYPE))
35 : {
36 12 : size_t const totalBytesWritten = serializer.getCurrentPosition() - writingStartPos;
37 : ::etl::unaligned_type_ext<LENGTH_TYPE, ::etl::endian::big>{lengthBuffer.data()}
38 12 : = static_cast<LENGTH_TYPE>(totalBytesWritten);
39 : }
40 12 : }
41 :
42 : private:
43 : SomeIpSerializer& serializer;
44 : ::etl::span<uint8_t> lengthBuffer;
45 : size_t writingStartPos;
46 : };
47 :
48 : template<class LENGTH_TYPE>
49 : class LengthParserHelper
50 : {
51 : public:
52 : static uint32_t parseLength(SomeIpParser& parser);
53 : };
54 :
55 : template<class LENGTH_TYPE>
56 20 : uint32_t LengthParserHelper<LENGTH_TYPE>::parseLength(SomeIpParser& parser)
57 : {
58 20 : if (!parser.isGood())
59 : {
60 2 : return 0U;
61 : }
62 :
63 18 : LENGTH_TYPE numBytes = 0U;
64 :
65 : // for now length's are always written in BigEndian
66 18 : parser.bigEndian();
67 18 : parser >> numBytes;
68 :
69 18 : if (parser.bytesAvailable() < numBytes)
70 : {
71 2 : parser.setFailure();
72 2 : return 0U;
73 : }
74 :
75 16 : return static_cast<uint32_t>(numBytes);
76 : }
77 :
78 : } // namespace someip
|