summaryrefslogtreecommitdiffhomepage
path: root/include/ocl/fix/checksum.hpp
blob: 31aee75c3ca1cc53cd9acac8fbf636df90e22a40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
 * File: fix/checksum.hpp
 * Purpose: Financial Information Exchange checksum in C++
 * Author: Amlal El Mahrouss (amlal@nekernel.org)
 * Copyright 2025, Amlal El Mahrouss, licensed under the Boost Software License.
 */

#ifndef __OCL_FIX_CHECKSUM
#define __OCL_FIX_CHECKSUM

#include <ocl/fix/detail/config.hpp>
#include <ocl/fix/parser.hpp>
#include <boost/core/detail/string_view.hpp>

namespace ocl::fix
{

	/// \brief Returns the checksum index of a FIX message.
	/// \param range the range_buffer containing the message.
	/// \throws runtime_error if the FIX message is invalid (missing tag "8").
	inline std::string try_index_checksum(range_buffer& fix)
	{
		if (fix.is_valid())
			return fix["10"];
		else
			detail::throw_runtime_error();
	}

	/// \brief FIX message operators namespace.
	namespace operators::fix
	{
		using checksum_type = long long;

		/// \brief Calculates the FIX protocol checksum for a message.
		/// \param in_ Pointer to the message buffer.
		/// \param len Length of the message in bytes.
		/// \return The checksum value (sum of all bytes modulo 256).
		inline checksum_type
			checksum(const char* in_,
				 const long  len)
		{
			if (len < 1)
				return 0L;

			long long cks{};

			for (long idx{}; idx < len; ++idx)
			{
				cks += static_cast<unsigned char>(in_[idx]);
			}

			return cks % 256;
		}
	} // namespace operators::fix

} // namespace ocl::fix

#endif