1use reddb_types::Value;
16
17pub const MSG_QUERY: u8 = 0x01;
19pub const MSG_RESULT: u8 = 0x02;
20pub const MSG_ERROR: u8 = 0x03;
21pub const MSG_BULK_INSERT: u8 = 0x04;
22pub const MSG_BULK_OK: u8 = 0x05;
23pub const MSG_BULK_INSERT_BINARY: u8 = 0x06;
24pub const MSG_QUERY_BINARY: u8 = 0x07;
25pub const MSG_BULK_INSERT_PREVALIDATED: u8 = 0x08;
26pub const MSG_BULK_STREAM_START: u8 = 0x09;
27pub const MSG_BULK_STREAM_ROWS: u8 = 0x0A;
28pub const MSG_BULK_STREAM_COMMIT: u8 = 0x0B;
29pub const MSG_BULK_STREAM_ACK: u8 = 0x0C;
30pub const MSG_PREPARE: u8 = 0x0D;
31pub const MSG_PREPARED_OK: u8 = 0x0E;
32pub const MSG_EXECUTE_PREPARED: u8 = 0x0F;
33pub const MSG_DEALLOCATE: u8 = 0x10;
34pub const MSG_DECLARE_CURSOR: u8 = 0x11;
35pub const MSG_CURSOR_OK: u8 = 0x12;
36pub const MSG_FETCH: u8 = 0x13;
37pub const MSG_CURSOR_BATCH: u8 = 0x14;
38pub const MSG_CLOSE_CURSOR: u8 = 0x15;
39
40pub const VAL_NULL: u8 = 0;
42pub const VAL_I64: u8 = 1;
43pub const VAL_F64: u8 = 2;
44pub const VAL_TEXT: u8 = 3;
45pub const VAL_BOOL: u8 = 4;
46pub const VAL_U64: u8 = 5;
47
48#[derive(Debug, Clone, PartialEq)]
49pub enum WireValue {
50 Null,
51 I64(i64),
52 U64(u64),
53 F64(f64),
54 Text(String),
55 Bool(bool),
56 Bytes(Vec<u8>),
57 Timestamp(u64),
58}
59
60impl From<&Value> for WireValue {
67 fn from(value: &Value) -> Self {
68 match value {
69 Value::Null => WireValue::Null,
70 Value::Integer(n) => WireValue::I64(*n),
71 Value::UnsignedInteger(n) => WireValue::U64(*n),
72 Value::Float(f) => WireValue::F64(*f),
73 Value::Text(s) => WireValue::Text(s.to_string()),
74 Value::Cron(value) => WireValue::Text(value.to_string()),
75 Value::Temperature(temperature) => WireValue::Text(temperature.to_string()),
76 Value::Blob(bytes) => WireValue::Bytes(bytes.clone()),
77 Value::Boolean(b) => WireValue::Bool(*b),
78 Value::Timestamp(t) => WireValue::Timestamp(*t as u64),
79 _ => WireValue::Null,
80 }
81 }
82}
83
84impl From<Value> for WireValue {
85 fn from(value: Value) -> Self {
86 match value {
87 Value::Null => WireValue::Null,
88 Value::Integer(n) => WireValue::I64(n),
89 Value::UnsignedInteger(n) => WireValue::U64(n),
90 Value::Float(f) => WireValue::F64(f),
91 Value::Text(s) => WireValue::Text(s.to_string()),
92 Value::Cron(value) => WireValue::Text(value.to_string()),
93 Value::Temperature(temperature) => WireValue::Text(temperature.to_string()),
94 Value::Blob(bytes) => WireValue::Bytes(bytes),
95 Value::Boolean(b) => WireValue::Bool(b),
96 Value::Timestamp(t) => WireValue::Timestamp(t as u64),
97 _ => WireValue::Null,
98 }
99 }
100}
101
102impl TryFrom<WireValue> for Value {
103 type Error = &'static str;
104
105 fn try_from(value: WireValue) -> Result<Self, Self::Error> {
106 match value {
107 WireValue::Null => Ok(Value::Null),
108 WireValue::I64(n) => Ok(Value::Integer(n)),
109 WireValue::U64(n) => Ok(Value::UnsignedInteger(n)),
110 WireValue::F64(f) => Ok(Value::Float(f)),
111 WireValue::Text(s) => Ok(Value::text(s)),
112 WireValue::Bool(b) => Ok(Value::Boolean(b)),
113 WireValue::Bytes(bytes) => Ok(Value::Blob(bytes)),
114 WireValue::Timestamp(t) => {
115 let timestamp = i64::try_from(t).map_err(|_| "timestamp exceeds i64 range")?;
116 Ok(Value::Timestamp(timestamp))
117 }
118 }
119 }
120}
121
122#[inline]
124pub fn write_frame_header(buf: &mut Vec<u8>, msg_type: u8, payload_len: u32) {
125 let total = payload_len + 1; buf.extend_from_slice(&total.to_le_bytes());
127 buf.push(msg_type);
128}
129
130pub fn build_legacy_frame(msg_type: u8, payload: &[u8]) -> Vec<u8> {
131 let mut out = Vec::with_capacity(5 + payload.len());
132 write_frame_header(&mut out, msg_type, payload.len() as u32);
133 out.extend_from_slice(payload);
134 out
135}
136
137pub fn build_legacy_result_frame(payload: &[u8]) -> Vec<u8> {
138 build_legacy_frame(MSG_RESULT, payload)
139}
140
141pub fn build_legacy_result_frame_with(
145 payload_capacity: usize,
146 encode: impl FnOnce(&mut Vec<u8>),
147) -> Vec<u8> {
148 let mut out = Vec::with_capacity(payload_capacity.saturating_add(5));
149 write_frame_header(&mut out, MSG_RESULT, 0);
150 encode(&mut out);
151 assert!(
152 out.len() >= 5,
153 "encoder must preserve the legacy frame header"
154 );
155 let total = u32::try_from(out.len() - 4).expect("legacy frame length fits u32");
156 out[..4].copy_from_slice(&total.to_le_bytes());
157 out
158}
159
160pub fn build_legacy_result_frame_in_place(out: &mut [u8]) -> Result<(), &'static str> {
163 if out.len() < 5 {
164 return Err("truncated legacy result buffer");
165 }
166 let total = u32::try_from(out.len() - 4).map_err(|_| "legacy result exceeds frame length")?;
167 out[..4].copy_from_slice(&total.to_le_bytes());
168 out[4] = MSG_RESULT;
169 Ok(())
170}
171
172pub fn build_legacy_error_frame(message: &[u8]) -> Vec<u8> {
173 build_legacy_frame(MSG_ERROR, message)
174}
175
176pub fn build_legacy_bulk_ok_frame(payload: &[u8]) -> Vec<u8> {
177 build_legacy_frame(MSG_BULK_OK, payload)
178}
179
180pub fn build_legacy_bulk_stream_ack_frame() -> Vec<u8> {
181 build_legacy_frame(MSG_BULK_STREAM_ACK, &[])
182}
183
184pub fn build_legacy_prepared_ok_frame(payload: &[u8]) -> Vec<u8> {
185 build_legacy_frame(MSG_PREPARED_OK, payload)
186}
187
188pub fn build_legacy_cursor_ok_frame(payload: &[u8]) -> Vec<u8> {
189 build_legacy_frame(MSG_CURSOR_OK, payload)
190}
191
192pub fn build_legacy_cursor_batch_frame(payload: &[u8]) -> Vec<u8> {
193 build_legacy_frame(MSG_CURSOR_BATCH, payload)
194}
195
196#[inline]
197pub fn encode_value(buf: &mut Vec<u8>, value: &WireValue) {
198 match value {
199 WireValue::Null | WireValue::Bytes(_) => buf.push(VAL_NULL),
200 WireValue::I64(n) => {
201 buf.push(VAL_I64);
202 buf.extend_from_slice(&n.to_le_bytes());
203 }
204 WireValue::U64(n) | WireValue::Timestamp(n) => {
205 buf.push(VAL_U64);
206 buf.extend_from_slice(&n.to_le_bytes());
207 }
208 WireValue::F64(f) => {
209 buf.push(VAL_F64);
210 buf.extend_from_slice(&f.to_le_bytes());
211 }
212 WireValue::Text(s) => {
213 buf.push(VAL_TEXT);
214 let bytes = s.as_bytes();
215 buf.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
216 buf.extend_from_slice(bytes);
217 }
218 WireValue::Bool(b) => {
219 buf.push(VAL_BOOL);
220 buf.push(*b as u8);
221 }
222 }
223}
224
225#[inline]
228pub fn encode_native_value(buf: &mut Vec<u8>, value: &Value) {
229 match value {
230 Value::Text(text) => {
231 buf.push(VAL_TEXT);
232 buf.extend_from_slice(&(text.len() as u32).to_le_bytes());
233 buf.extend_from_slice(text.as_bytes());
234 }
235 Value::Cron(value) => encode_value(buf, &WireValue::Text(value.to_string())),
236 Value::Temperature(temperature) => {
237 encode_value(buf, &WireValue::Text(temperature.to_string()))
238 }
239 Value::Integer(value) => encode_value(buf, &WireValue::I64(*value)),
240 Value::UnsignedInteger(value) => encode_value(buf, &WireValue::U64(*value)),
241 Value::Float(value) => encode_value(buf, &WireValue::F64(*value)),
242 Value::Boolean(value) => encode_value(buf, &WireValue::Bool(*value)),
243 Value::Timestamp(value) => encode_value(buf, &WireValue::Timestamp(*value as u64)),
244 _ => buf.push(VAL_NULL),
245 }
246}
247
248#[inline]
250pub fn native_value_encoded_len(value: &Value) -> usize {
251 match value {
252 Value::Text(text) => 5 + text.len(),
253 Value::Cron(value) => 5 + value.as_str().len(),
254 Value::Temperature(temperature) => 5 + temperature.to_string().len(),
255 Value::Integer(_) | Value::UnsignedInteger(_) | Value::Float(_) | Value::Timestamp(_) => 9,
256 Value::Boolean(_) => 2,
257 _ => 1,
258 }
259}
260
261#[inline]
262pub fn decode_value(data: &[u8], pos: &mut usize) -> WireValue {
263 try_decode_value(data, pos).unwrap_or(WireValue::Null)
264}
265
266#[inline]
267pub fn try_decode_value(data: &[u8], pos: &mut usize) -> Result<WireValue, &'static str> {
268 if *pos >= data.len() {
269 return Err("missing value tag");
270 }
271
272 let tag = data[*pos];
273 *pos += 1;
274
275 match tag {
276 VAL_NULL => Ok(WireValue::Null),
277 VAL_I64 => Ok(WireValue::I64(i64::from_le_bytes(read_array::<8>(
278 data,
279 pos,
280 "truncated i64 value",
281 )?))),
282 VAL_U64 => Ok(WireValue::U64(u64::from_le_bytes(read_array::<8>(
283 data,
284 pos,
285 "truncated u64 value",
286 )?))),
287 VAL_F64 => Ok(WireValue::F64(f64::from_le_bytes(read_array::<8>(
288 data,
289 pos,
290 "truncated f64 value",
291 )?))),
292 VAL_TEXT => {
293 let len =
294 u32::from_le_bytes(read_array::<4>(data, pos, "truncated text length")?) as usize;
295 let bytes = read_bytes(data, pos, len, "truncated text value")?;
296 let cow = std::string::String::from_utf8_lossy(bytes);
297 Ok(WireValue::Text(cow.into_owned()))
298 }
299 VAL_BOOL => {
300 let bytes = read_bytes(data, pos, 1, "truncated bool value")?;
301 Ok(WireValue::Bool(bytes[0] != 0))
302 }
303 _ => Err("unknown value tag"),
304 }
305}
306
307#[inline]
308fn read_bytes<'a>(
309 data: &'a [u8],
310 pos: &mut usize,
311 len: usize,
312 err: &'static str,
313) -> Result<&'a [u8], &'static str> {
314 let end = pos.saturating_add(len);
315 if end > data.len() {
316 return Err(err);
317 }
318 let bytes = &data[*pos..end];
319 *pos = end;
320 Ok(bytes)
321}
322
323#[inline]
324fn read_array<const N: usize>(
325 data: &[u8],
326 pos: &mut usize,
327 err: &'static str,
328) -> Result<[u8; N], &'static str> {
329 let bytes = read_bytes(data, pos, N, err)?;
330 let mut array = [0u8; N];
331 array.copy_from_slice(bytes);
332 Ok(array)
333}
334
335#[inline]
336pub fn encode_column_name(buf: &mut Vec<u8>, name: &str) {
337 let bytes = name.as_bytes();
338 buf.extend_from_slice(&(bytes.len() as u16).to_le_bytes());
339 buf.extend_from_slice(bytes);
340}
341
342pub fn encode_result_payload_header<'a, I>(buf: &mut Vec<u8>, columns: I, row_count: u32) -> usize
343where
344 I: IntoIterator<Item = &'a str>,
345 I::IntoIter: ExactSizeIterator,
346{
347 let columns = columns.into_iter();
348 buf.extend_from_slice(&(columns.len() as u16).to_le_bytes());
349 for column in columns {
350 encode_column_name(buf, column);
351 }
352 let row_count_offset = buf.len();
353 buf.extend_from_slice(&row_count.to_le_bytes());
354 row_count_offset
355}
356
357pub fn set_result_payload_row_count(
358 buf: &mut [u8],
359 row_count_offset: usize,
360 row_count: u32,
361) -> Result<(), &'static str> {
362 let end = row_count_offset.saturating_add(4);
363 if end > buf.len() {
364 return Err("result payload row-count offset out of bounds");
365 }
366 buf[row_count_offset..end].copy_from_slice(&row_count.to_le_bytes());
367 Ok(())
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 #[test]
375 fn admitted_in_place_result_matches_canonical_envelope() {
376 for payload in [b"".as_slice(), b"hello", &[0, 255, 1, 2]] {
377 let expected = build_legacy_result_frame(payload);
378 let mut actual = vec![0; 5 + payload.len()];
379 actual[5..].copy_from_slice(payload);
380 build_legacy_result_frame_in_place(&mut actual).unwrap();
381 assert_eq!(actual, expected);
382 }
383 for length in 0..5 {
384 let mut truncated = vec![0; length];
385 assert!(build_legacy_result_frame_in_place(&mut truncated).is_err());
386 }
387 }
388
389 #[test]
390 fn borrowed_native_encoding_matches_owned_conversion_and_exact_length() {
391 let values = [
392 Value::Null,
393 Value::Integer(i64::MIN),
394 Value::UnsignedInteger(u64::MAX),
395 Value::Float(-1.25),
396 Value::Boolean(true),
397 Value::Boolean(false),
398 Value::Timestamp(-1),
399 Value::text(""),
400 Value::text("quotes\"雪\n"),
401 Value::text("x".repeat(192 * 1024)),
402 Value::Blob(vec![1; 192 * 1024]),
403 ];
404 for value in values {
405 let mut expected = Vec::new();
406 encode_value(&mut expected, &WireValue::from(&value));
407 let mut actual = Vec::with_capacity(native_value_encoded_len(&value));
408 encode_native_value(&mut actual, &value);
409 assert_eq!(actual, expected);
410 assert_eq!(actual.len(), native_value_encoded_len(&value));
411 assert_eq!(actual.len(), actual.capacity());
412 }
413 }
414
415 #[test]
420 fn value_wirevalue_field_mapping_round_trips() {
421 let cases = [
422 (Value::Null, WireValue::Null),
423 (Value::Integer(-7), WireValue::I64(-7)),
424 (Value::UnsignedInteger(9), WireValue::U64(9)),
425 (Value::Float(1.5), WireValue::F64(1.5)),
426 (Value::text("hi"), WireValue::Text("hi".to_string())),
427 (Value::Blob(vec![1, 2, 3]), WireValue::Bytes(vec![1, 2, 3])),
428 (Value::Boolean(true), WireValue::Bool(true)),
429 (Value::Timestamp(42), WireValue::Timestamp(42)),
430 ];
431 for (value, wire) in cases {
432 assert_eq!(WireValue::from(value.clone()), wire);
434 assert_eq!(WireValue::from(&value), wire);
435 assert_eq!(Value::try_from(wire.clone()), Ok(value));
437 }
438 }
439
440 #[test]
441 fn wirevalue_timestamp_rejects_i64_overflow() {
442 let overflow = WireValue::Timestamp(u64::MAX);
443 assert_eq!(
444 Value::try_from(overflow),
445 Err("timestamp exceeds i64 range")
446 );
447 }
448
449 #[test]
450 fn frame_header_keeps_legacy_length_shape() {
451 let mut out = Vec::new();
452 write_frame_header(&mut out, MSG_RESULT, 10);
453 assert_eq!(out, [11, 0, 0, 0, MSG_RESULT]);
454 }
455
456 #[test]
457 fn legacy_frame_builders_wrap_payloads() {
458 assert_eq!(
459 build_legacy_result_frame(b"ok"),
460 [3, 0, 0, 0, MSG_RESULT, b'o', b'k']
461 );
462 assert_eq!(
463 build_legacy_error_frame(b"no"),
464 [3, 0, 0, 0, MSG_ERROR, b'n', b'o']
465 );
466 assert_eq!(
467 build_legacy_bulk_ok_frame(b"\x02\0\0\0\0\0\0\0"),
468 [9, 0, 0, 0, MSG_BULK_OK, 2, 0, 0, 0, 0, 0, 0, 0]
469 );
470 assert_eq!(
471 build_legacy_bulk_stream_ack_frame(),
472 [1, 0, 0, 0, MSG_BULK_STREAM_ACK]
473 );
474 assert_eq!(
475 build_legacy_prepared_ok_frame(b"p"),
476 [2, 0, 0, 0, MSG_PREPARED_OK, b'p']
477 );
478 assert_eq!(
479 build_legacy_cursor_ok_frame(b"c"),
480 [2, 0, 0, 0, MSG_CURSOR_OK, b'c']
481 );
482 assert_eq!(
483 build_legacy_cursor_batch_frame(b"b"),
484 [2, 0, 0, 0, MSG_CURSOR_BATCH, b'b']
485 );
486 }
487
488 #[test]
489 fn direct_result_frame_encoder_matches_legacy_bytes_across_growth() {
490 for size in [0, 1, 255, 1024, 192 * 1024] {
491 let payload = vec![0x71; size];
492 let frame = build_legacy_result_frame_with(8, |out| {
493 out.extend_from_slice(&payload[..size / 2]);
494 out.extend_from_slice(&payload[size / 2..]);
495 });
496 assert_eq!(frame, build_legacy_result_frame(&payload));
497 }
498 }
499
500 #[test]
501 fn wire_values_round_trip_legacy_tags() {
502 let values = [
503 WireValue::Null,
504 WireValue::I64(-7),
505 WireValue::U64(42),
506 WireValue::F64(3.5),
507 WireValue::Text("hello".to_string()),
508 WireValue::Bool(true),
509 WireValue::Timestamp(1234),
510 ];
511
512 let mut bytes = Vec::new();
513 for value in &values {
514 encode_value(&mut bytes, value);
515 }
516
517 let mut pos = 0;
518 assert_eq!(try_decode_value(&bytes, &mut pos), Ok(WireValue::Null));
519 assert_eq!(try_decode_value(&bytes, &mut pos), Ok(WireValue::I64(-7)));
520 assert_eq!(try_decode_value(&bytes, &mut pos), Ok(WireValue::U64(42)));
521 assert_eq!(try_decode_value(&bytes, &mut pos), Ok(WireValue::F64(3.5)));
522 assert_eq!(
523 try_decode_value(&bytes, &mut pos),
524 Ok(WireValue::Text("hello".to_string()))
525 );
526 assert_eq!(
527 try_decode_value(&bytes, &mut pos),
528 Ok(WireValue::Bool(true))
529 );
530 assert_eq!(try_decode_value(&bytes, &mut pos), Ok(WireValue::U64(1234)));
531 assert_eq!(pos, bytes.len());
532 }
533
534 #[test]
535 fn result_payload_header_encodes_columns_and_row_count() {
536 let mut bytes = Vec::new();
537 let row_count_offset = encode_result_payload_header(&mut bytes, ["id", "name"], 3);
538
539 assert_eq!(
540 bytes,
541 [
542 2, 0, 2, 0, b'i', b'd', 4, 0, b'n', b'a', b'm', b'e', 3, 0, 0, 0, ]
547 );
548 assert_eq!(row_count_offset, bytes.len() - 4);
549 set_result_payload_row_count(&mut bytes, row_count_offset, 5).unwrap();
550 assert_eq!(
551 &bytes[row_count_offset..row_count_offset + 4],
552 &[5, 0, 0, 0]
553 );
554 }
555}
556
557#[cfg(test)]
558mod temperature_wire_tests {
559 use super::*;
560
561 #[test]
562 fn temperature_uses_existing_text_tag_in_legacy_wire() {
563 let value = Value::Temperature(
564 reddb_types::Temperature::new(29_315, 2, reddb_types::TemperatureUnit::Kelvin)
565 .expect("temperature"),
566 );
567 let expected = WireValue::Text("293.15 K".into());
568 assert_eq!(WireValue::from(&value), expected);
569 assert_eq!(WireValue::from(value.clone()), expected);
570
571 let mut bytes = Vec::new();
572 encode_native_value(&mut bytes, &value);
573 assert_eq!(bytes.len(), native_value_encoded_len(&value));
574 assert_eq!(try_decode_value(&bytes, &mut 0).expect("decode"), expected);
575 }
576}