96{
97 static_assert(std::is_integral_v<WordType> && std::is_unsigned_v<WordType>,
98 "WordType must be an unsigned integral type");
99
100 constexpr int bits_per_word = std::numeric_limits<WordType>::digits;
101
102 static_assert(BitsPerADC > 0 && BitsPerADC <= bits_per_word);
103 static_assert(ADCSPerChannel * NChannels * BitsPerADC == NWords * bits_per_word);
104
105 if (i_channel < 0 || i_channel >= NChannels) {
106 throw std::out_of_range(
107 std::format("Requested channel of {} is out of channel range 0-{}", i_channel, NChannels - 1));
108 }
109
110 if (i_adc < 0 || i_adc >= ADCSPerChannel) {
111 throw std::out_of_range(std::format("Requested ADC index of {} is out of range 0-{}", i_adc, ADCSPerChannel - 1));
112 }
113
114 if constexpr (BitsPerADC < bits_per_word) {
115 if (adc_val >= (static_cast<WordType>(1) << BitsPerADC)) {
116 throw std::out_of_range(std::format(
117 "Requested ADC value of {} exceeds max value of {}", adc_val, (static_cast<WordType>(1) << BitsPerADC) - 1));
118 }
119 }
120
121
122 int i_abs = i_adc * NChannels + i_channel;
123
124 if constexpr (BitsPerADC == bits_per_word) {
125 adc_matrix[i_abs] = adc_val;
126 } else {
127
128
129 int i_word = BitsPerADC * i_abs / bits_per_word;
130 assert(i_word < NWords);
131
132
133 int first_bit_position = (BitsPerADC * i_abs) % bits_per_word;
134
135
136 int bits_in_first_word = std::min(BitsPerADC, bits_per_word - first_bit_position);
137
138 WordType
mask = ((
static_cast<WordType
>(1) << bits_in_first_word) - 1) << first_bit_position;
139
140 adc_matrix[i_word] = (adc_matrix[i_word] & ~mask) | ((static_cast<WordType>(adc_val) << first_bit_position) & mask);
141
142
143 if (bits_in_first_word < BitsPerADC) {
144 assert(i_word < NWords - 1);
145 int bits_in_second_word = BitsPerADC - bits_in_first_word;
146 WordType mask2 = (static_cast<WordType>(1) << bits_in_second_word) - 1;
147 adc_matrix[i_word + 1] = (adc_matrix[i_word + 1] & ~mask2) | ((adc_val >> bits_in_first_word) & mask2);
148 }
149 }
150}