nushell/crates/nu-plugin-protocol/src/test_util.rs
Devyn Cairns f4940e115f
Remove bincode and use MessagePack instead for plugin custom values (#13745)
# Description

This changes the serialization of custom values within the plugin
protocol to use MessagePack instead of bincode, removing the dependency
on bincode entirely.

Bincode does not seem to be very maintained anymore, and the externally
tagged enum representation doesn't seem to always work now even though
it should. Since we use MessagePack already anyway for the plugin
protocol, this seems like an obvious choice. This uses the unnamed
variant of the serialization rather than the named variant, which is
what the plugin protocol in general uses. The unnamed variant does not
include field names, which aren't really required here, so this should
give us something that's more or less as efficient as bincode is.

Should fix #13743.

# User-Facing Changes

- Will need to recompile plugins (but always do anyway)
- Doesn't technically break the plugin protocol (custom value data is a
black box / plugin implementation specific), but breaks compatibility
between `nu-plugin-engine` and `nu-plugin` so they do need to both be
updated to match.

# Tests + Formatting

All tests pass.

# After Submitting

- [ ] release notes
2024-09-01 17:33:10 +02:00

44 lines
1.4 KiB
Rust

use crate::PluginCustomValue;
use nu_protocol::{CustomValue, ShellError, Span, Value};
use serde::{Deserialize, Serialize};
/// A custom value that can be used for testing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestCustomValue(pub i32);
#[typetag::serde(name = "nu_plugin_protocol::test_util::TestCustomValue")]
impl CustomValue for TestCustomValue {
fn clone_value(&self, span: Span) -> Value {
Value::custom(Box::new(self.clone()), span)
}
fn type_name(&self) -> String {
"TestCustomValue".into()
}
fn to_base_value(&self, span: Span) -> Result<Value, ShellError> {
Ok(Value::int(self.0 as i64, span))
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}
/// A [`TestCustomValue`] serialized as a [`PluginCustomValue`].
pub fn test_plugin_custom_value() -> PluginCustomValue {
let data = rmp_serde::to_vec(&expected_test_custom_value() as &dyn CustomValue)
.expect("MessagePack serialization of the expected_test_custom_value() failed");
PluginCustomValue::new("TestCustomValue".into(), data, false)
}
/// The expected [`TestCustomValue`] that [`test_plugin_custom_value()`] should deserialize into.
pub fn expected_test_custom_value() -> TestCustomValue {
TestCustomValue(-1)
}