feat: add abi stable crates
This commit is contained in:
154
__ffi/abi_stable_crates/interface/src/commands.rs
Normal file
154
__ffi/abi_stable_crates/interface/src/commands.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
use crate::{PluginId,WhichPlugin};
|
||||
|
||||
use std::fmt;
|
||||
use serde::{
|
||||
Serialize,Deserialize,
|
||||
de::{self,Deserializer, DeserializeOwned, IgnoredAny, Visitor, MapAccess, Error as _},
|
||||
};
|
||||
use abi_stable::{StableAbi, std_types::*};
|
||||
|
||||
/// The commands that map to methods in the Plugin trait.
|
||||
// This is intentionally not `#[derive(StableAbi)]`,
|
||||
// since it can be extended in minor versions of the interface.
|
||||
// I has to be serialized to pass it through ffi.
|
||||
#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize)]
|
||||
pub enum BasicCommand{
|
||||
GetCommands,
|
||||
}
|
||||
|
||||
|
||||
/// These is the (serialized) return value of calling `PluginExt::send_basic_command`.
|
||||
// This is intentionally not `#[derive(StableAbi)]`,
|
||||
// since it can be extended in minor versions of the interface.
|
||||
// I has to be serialized to pass it through ffi.
|
||||
#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize)]
|
||||
pub enum BasicRetVal{
|
||||
GetCommands(RVec<CommandDescription>),
|
||||
}
|
||||
|
||||
|
||||
// This is intentionally not `#[derive(StableAbi)]`,
|
||||
// since it can be extended in minor versions of the interface.
|
||||
// I has to be serialized to pass it through ffi.
|
||||
#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum CommandUnion<T>{
|
||||
ForPlugin(T),
|
||||
Basic(BasicCommand),
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum ReturnValUnion<T>{
|
||||
ForPlugin(T),
|
||||
Basic(BasicRetVal),
|
||||
}
|
||||
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/// A partially deserialize command,that only deserialized its variant.
|
||||
#[derive(Debug,Clone)]
|
||||
pub struct WhichVariant{
|
||||
pub variant:RString,
|
||||
}
|
||||
|
||||
|
||||
struct WhichVariantVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for WhichVariantVisitor{
|
||||
type Value = WhichVariant;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a map with a single entry,or a string")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<WhichVariant, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
Ok(WhichVariant{variant:value.to_string().into()})
|
||||
}
|
||||
|
||||
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
|
||||
where
|
||||
M: MapAccess<'de>,
|
||||
{
|
||||
let (variant,_)=access.next_entry::<RString,IgnoredAny>()?
|
||||
.ok_or_else(||M::Error::custom("Expected a map with a single entry"))?;
|
||||
if let Some((second,_))=access.next_entry::<RString,IgnoredAny>()? {
|
||||
let s=format!(
|
||||
"Expected a map with a single field,\n\
|
||||
instead found both {{ \"{}\":... , \"{}\": ... }}",
|
||||
variant,
|
||||
second,
|
||||
);
|
||||
return Err(M::Error::custom(s));
|
||||
}
|
||||
Ok(WhichVariant{variant})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for WhichVariant{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_map(WhichVariantVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/// Denotes this as a command type.
|
||||
pub trait CommandTrait:Serialize{
|
||||
type Returns:DeserializeOwned;
|
||||
}
|
||||
|
||||
impl CommandTrait for BasicCommand{
|
||||
type Returns=BasicRetVal;
|
||||
}
|
||||
|
||||
|
||||
/// Describes a command.
|
||||
#[repr(C)]
|
||||
#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize,StableAbi)]
|
||||
pub struct CommandDescription{
|
||||
/// A description of what this command does.
|
||||
pub name:RCow<'static,str>,
|
||||
/// A description of what this command does,
|
||||
/// optionally with a description of the command format.
|
||||
pub description:RCow<'static,str>,
|
||||
}
|
||||
|
||||
|
||||
impl CommandDescription{
|
||||
pub fn from_literals(
|
||||
name:&'static str,
|
||||
description:&'static str,
|
||||
)->Self{
|
||||
CommandDescription{
|
||||
name:name.into(),
|
||||
description:description.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug,Clone,PartialEq,Eq,StableAbi)]
|
||||
pub struct AsyncCommand{
|
||||
pub from:PluginId,
|
||||
pub which_plugin:WhichPlugin,
|
||||
pub command:RString,
|
||||
}
|
||||
127
__ffi/abi_stable_crates/interface/src/error.rs
Normal file
127
__ffi/abi_stable_crates/interface/src/error.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use crate::{commands::CommandDescription,WhichPlugin,WhichCommandRet};
|
||||
|
||||
use abi_stable::{StableAbi, std_types::{RBoxError,RBox,RString,RVec}};
|
||||
use std::{error::Error as ErrorTrait, fmt::{self,Display}};
|
||||
use core_extensions::strings::StringExt;
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug,StableAbi)]
|
||||
pub enum Error{
|
||||
/// An error produced by `serde_json::to_string`.
|
||||
Serialize(RBoxError,WhichCommandRet),
|
||||
/// An error produced by `serde_json::from_string`.
|
||||
Deserialize(RBoxError,WhichCommandRet),
|
||||
/// A deserialization error produced when trying to deserialize json
|
||||
/// as a particular command type.
|
||||
UnsupportedCommand(RBox<Unsupported>),
|
||||
/// A deserialization error produced when trying to deserialize json
|
||||
/// as a particular return value type.
|
||||
UnsupportedReturnValue(RBox<Unsupported>),
|
||||
/// An invalid plugin.
|
||||
InvalidPlugin(WhichPlugin),
|
||||
/// A custom error.
|
||||
Custom(RBoxError),
|
||||
/// A list of errors.
|
||||
Many(RVec<Error>),
|
||||
}
|
||||
|
||||
/// Represents a command or return value that wasn't supported.
|
||||
#[repr(C)]
|
||||
#[derive(Debug,StableAbi)]
|
||||
pub struct Unsupported{
|
||||
/// The name of the plugin for which the command/return value wasn't supported.
|
||||
pub plugin_name:RString,
|
||||
/// The command/return value that wasn't supported.
|
||||
pub command_name:RString,
|
||||
/// A custom error.
|
||||
pub error:RBoxError,
|
||||
/// A list of the commands that the plugin supports
|
||||
pub supported_commands:RVec<CommandDescription>,
|
||||
}
|
||||
|
||||
|
||||
impl Error{
|
||||
pub fn unsupported_command(what:Unsupported)->Self{
|
||||
Error::UnsupportedCommand(RBox::new(what))
|
||||
}
|
||||
pub fn unsupported_return_value(what:Unsupported)->Self{
|
||||
Error::UnsupportedReturnValue(RBox::new(what))
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Error{
|
||||
fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result {
|
||||
match self {
|
||||
Error::Serialize(e,which)=>{
|
||||
let which=match which {
|
||||
WhichCommandRet::Command=>"command",
|
||||
WhichCommandRet::Return=>"return value",
|
||||
};
|
||||
writeln!(f,"Error happened while serializing the {}:\n{}\n",which,e)
|
||||
}
|
||||
Error::Deserialize(e,which)=>{
|
||||
let which=match which {
|
||||
WhichCommandRet::Command=>"command",
|
||||
WhichCommandRet::Return=>"return value",
|
||||
};
|
||||
writeln!(f,"Error happened while deserializing {}:\n{}\n",which,e)
|
||||
}
|
||||
Error::UnsupportedCommand(v)=>{
|
||||
writeln!(
|
||||
f,
|
||||
"Plugin '{}' ooes not support this command:\n\
|
||||
\t'{}'\n\
|
||||
Because of this error:\n{}\n\
|
||||
Supported commands:\
|
||||
",
|
||||
v.plugin_name,
|
||||
v.command_name,
|
||||
v.error,
|
||||
|
||||
)?;
|
||||
|
||||
for supported in &v.supported_commands {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
format!(
|
||||
"\nName:\n{}\nDescription:\n{}\n\n",
|
||||
supported.name.left_padder(4),
|
||||
supported.description.left_padder(4),
|
||||
).left_padder(4)
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Error::UnsupportedReturnValue(v)=>
|
||||
writeln!(
|
||||
f,
|
||||
"Unrecognized return value from '{}',named:\n\
|
||||
\t'{}'\n\
|
||||
Because of this error:\n{}\n\
|
||||
",
|
||||
v.plugin_name,
|
||||
v.command_name,
|
||||
v.error,
|
||||
),
|
||||
Error::InvalidPlugin(wc)=>
|
||||
writeln!(
|
||||
f,
|
||||
"Attempted to access a nonexistent plugin with the WhichPlugin:\n\t{:?}\n",
|
||||
wc
|
||||
),
|
||||
Error::Custom(e)=>Display::fmt(e,f),
|
||||
Error::Many(list)=>{
|
||||
for e in list {
|
||||
writeln!(f,"{}",e)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl ErrorTrait for Error{}
|
||||
|
||||
234
__ffi/abi_stable_crates/interface/src/lib.rs
Normal file
234
__ffi/abi_stable_crates/interface/src/lib.rs
Normal file
@@ -0,0 +1,234 @@
|
||||
/*!
|
||||
This is an example `interface crate`,
|
||||
where all publically available modules(structs of function pointers) and types are declared,
|
||||
|
||||
To load the library and the modules together,
|
||||
call `<PluginMod_Ref as RootModule>::load_from_directory`,
|
||||
which will load the dynamic library from a directory(folder),
|
||||
and all the modules inside of the library.
|
||||
|
||||
*/
|
||||
|
||||
use abi_stable::{
|
||||
StableAbi,
|
||||
sabi_trait,
|
||||
package_version_strings,
|
||||
declare_root_module_statics,
|
||||
library::RootModule,
|
||||
sabi_types::VersionStrings,
|
||||
external_types::{
|
||||
crossbeam_channel::RSender,
|
||||
},
|
||||
std_types::{RBox, RCow, RVec, RStr, RString,RResult, ROption, ROk,RSome},
|
||||
};
|
||||
|
||||
use serde::{Serialize,Deserialize};
|
||||
|
||||
mod commands;
|
||||
mod error;
|
||||
mod which_plugin;
|
||||
mod vec_from_map;
|
||||
pub mod utils;
|
||||
|
||||
|
||||
pub use self::{
|
||||
commands::{
|
||||
BasicCommand,BasicRetVal,CommandDescription,CommandTrait,WhichVariant,AsyncCommand,
|
||||
},
|
||||
error::{Error,Unsupported},
|
||||
which_plugin::WhichPlugin,
|
||||
vec_from_map::VecFromMap,
|
||||
};
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/**
|
||||
The identifier for a plugin.
|
||||
*/
|
||||
#[repr(C)]
|
||||
#[derive(Debug,Clone,PartialEq,Eq,StableAbi,Serialize,Deserialize)]
|
||||
pub struct PluginId{
|
||||
pub named:RCow<'static,str>,
|
||||
/// The number of the instance of this Plugin.
|
||||
pub instance:u64,
|
||||
}
|
||||
|
||||
|
||||
/// Describes whether a boxed error is a command or a return value.
|
||||
#[repr(u8)]
|
||||
#[derive(Debug,Clone,PartialEq,Eq,StableAbi,Serialize,Deserialize)]
|
||||
pub enum WhichCommandRet{
|
||||
Command,
|
||||
Return,
|
||||
}
|
||||
|
||||
|
||||
/// The response from having called `ApplicationMut::send_command_to_plugin` ealier.
|
||||
#[repr(C)]
|
||||
#[derive(Debug,Clone,PartialEq,Eq,StableAbi)]
|
||||
pub struct PluginResponse<'a>{
|
||||
/// The id of the plugin that is responding.
|
||||
pub plugin_id:PluginId,
|
||||
/// The response from the plugin
|
||||
pub response:RCow<'a,str>,
|
||||
}
|
||||
|
||||
|
||||
impl<'a> PluginResponse<'a>{
|
||||
pub fn owned_response(plugin_id:PluginId,response:RString)->Self{
|
||||
Self{plugin_id,response:response.into()}
|
||||
}
|
||||
pub fn borrowed_response(plugin_id:PluginId,response:RStr<'a>)->Self{
|
||||
Self{plugin_id,response:response.into()}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
pub type PluginType=Plugin_TO<'static,RBox<()>>;
|
||||
|
||||
|
||||
/**
|
||||
A plugin which is loaded by the application,and provides some functionality.
|
||||
|
||||
|
||||
*/
|
||||
#[sabi_trait]
|
||||
//#[sabi(debug_print)]
|
||||
pub trait Plugin {
|
||||
|
||||
/// Handles a JSON encoded command.
|
||||
fn json_command(
|
||||
&mut self,
|
||||
command: RStr<'_>,
|
||||
app:ApplicationMut<'_>,
|
||||
)->RResult<RString,Error>;
|
||||
|
||||
/// Handles a response from another Plugin,
|
||||
/// from having called `ApplicationMut::send_command_to_plugin` ealier.
|
||||
fn handle_response<'a>(
|
||||
&mut self,
|
||||
response:PluginResponse<'a>,
|
||||
_app:ApplicationMut<'_>,
|
||||
)->RResult<ROption<PluginResponse<'a>>,Error>{
|
||||
ROk(RSome(response))
|
||||
}
|
||||
|
||||
/// Gets the PluginId that was passed to this plugin in its constructor.
|
||||
fn plugin_id(&self)->&PluginId;
|
||||
|
||||
/// Gets a description of all commands from this Plugin.
|
||||
fn list_commands(&self)->RVec<CommandDescription>;
|
||||
|
||||
/*
|
||||
Closes the plugin,
|
||||
|
||||
This does not unload the dynamic library of this plugin,
|
||||
you can instantiate another instance of this plugin with
|
||||
`PluginMod_Ref::get_module().new()(application_handle)`.
|
||||
|
||||
|
||||
|
||||
The `#[sabi(last_prefix_field)]` attribute here means that this is the last method
|
||||
that was defined in the first compatible version of the library
|
||||
(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc),
|
||||
requiring new methods to always be added below preexisting ones.
|
||||
|
||||
The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library
|
||||
bumps its "major" version,
|
||||
at which point it would be moved to the last method at the time.
|
||||
*/
|
||||
#[sabi(last_prefix_field)]
|
||||
fn close(self,app:ApplicationMut<'_>);
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// The root module of a`plugin` dynamic library.
|
||||
///
|
||||
/// To load this module,
|
||||
/// call <PluginMod as RootModule>::load_from_directory(some_directory_path)
|
||||
#[repr(C)]
|
||||
#[derive(StableAbi)]
|
||||
#[sabi(kind(Prefix(prefix_ref="PluginMod_Ref")))]
|
||||
#[sabi(missing_field(panic))]
|
||||
pub struct PluginMod {
|
||||
/**
|
||||
Constructs the plugin.
|
||||
|
||||
|
||||
The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct
|
||||
that was defined in the first compatible version of the library
|
||||
(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc),
|
||||
requiring new fields to always be added below preexisting ones.
|
||||
|
||||
The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library
|
||||
bumps its "major" version,
|
||||
at which point it would be moved to the last field at the time.
|
||||
|
||||
*/
|
||||
#[sabi(last_prefix_field)]
|
||||
pub new: extern "C" fn(RSender<AsyncCommand>,PluginId) -> RResult<PluginType,Error>,
|
||||
}
|
||||
|
||||
|
||||
impl RootModule for PluginMod_Ref {
|
||||
declare_root_module_statics!{PluginMod_Ref}
|
||||
const BASE_NAME: &'static str = "plugin";
|
||||
const NAME: &'static str = "plugin";
|
||||
const VERSION_STRINGS: VersionStrings = package_version_strings!();
|
||||
}
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/// A mutable reference to the application implementation.
|
||||
pub type ApplicationMut<'a>=Application_TO<'a,&'a mut ()>;
|
||||
|
||||
|
||||
#[sabi_trait]
|
||||
pub trait Application{
|
||||
|
||||
/// Asynchronously Sends a command to the plugin(s) specified by `which_plugin`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an `Error::InvalidPlugin` if `which_plugin` is invalid.
|
||||
fn send_command_to_plugin(
|
||||
&mut self,
|
||||
from:&PluginId,
|
||||
which_plugin:WhichPlugin,
|
||||
command:RString,
|
||||
)->RResult<(),Error>;
|
||||
|
||||
/**
|
||||
Gets the `PluginId`s of the plugins specified by `which_plugin`.
|
||||
|
||||
|
||||
The `#[sabi(last_prefix_field)]` attribute here means that this is the last method
|
||||
that was defined in the first compatible version of the library
|
||||
(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc),
|
||||
requiring new methods to always be added below preexisting ones.
|
||||
|
||||
The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library
|
||||
bumps its "major" version,
|
||||
at which point it would be moved to the last method at the time.
|
||||
|
||||
*/
|
||||
#[sabi(last_prefix_field)]
|
||||
fn get_plugin_id(&self,which_plugin:WhichPlugin)->RResult<RVec<PluginId>,Error>;
|
||||
|
||||
/// Gets the sender end of a channel to send commands to the application/other plugins.
|
||||
fn sender(&self)->RSender<AsyncCommand>;
|
||||
|
||||
/// Gets the PluginId of all loaded plugins
|
||||
fn loaded_plugins(&self)->RVec<PluginId>;
|
||||
}
|
||||
129
__ffi/abi_stable_crates/interface/src/utils.rs
Normal file
129
__ffi/abi_stable_crates/interface/src/utils.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use crate::{
|
||||
commands::{
|
||||
BasicCommand,
|
||||
CommandUnion,
|
||||
CommandUnion as CU,
|
||||
CommandTrait,
|
||||
ReturnValUnion,
|
||||
ReturnValUnion as RVU,
|
||||
WhichVariant,
|
||||
BasicRetVal,
|
||||
},
|
||||
error::Unsupported,
|
||||
ApplicationMut,WhichCommandRet,Error,Plugin,PluginType,
|
||||
};
|
||||
use abi_stable::{std_types::{RStr, RString, RBoxError, RResult}};
|
||||
use serde::{Serialize,Deserialize};
|
||||
|
||||
|
||||
/**
|
||||
Sends a json encoded command to a plugin,and returns the response by encoding it to json.
|
||||
|
||||
# Errors
|
||||
|
||||
These are all error that this function returns
|
||||
(this does not include error returned as part of the command):
|
||||
|
||||
- Error::Serialize:
|
||||
If the command/return value could not be serialized to JSON.
|
||||
|
||||
- Error::Deserialize
|
||||
If the command/return value could not be deserialized from JSON(this comes from the plugin).
|
||||
|
||||
- Error::UnsupportedCommand
|
||||
If the command is not supported by the plugin.
|
||||
|
||||
*/
|
||||
pub fn process_command<'de,P,C,R,F>(this:&mut P,command:RStr<'de>,f:F)->RResult<RString,Error>
|
||||
where
|
||||
P:Plugin,
|
||||
F:FnOnce(&mut P,C)->Result<R,Error>,
|
||||
C:Deserialize<'de>,
|
||||
R:Serialize,
|
||||
{
|
||||
(||->Result<RString,Error>{
|
||||
let command=command.as_str();
|
||||
|
||||
let which_variant=serde_json::from_str::<WhichVariant>(&command)
|
||||
.map_err(|e| Error::Deserialize(RBoxError::new(e),WhichCommandRet::Command) )?;
|
||||
|
||||
let command=serde_json::from_str::<CommandUnion<C>>(command)
|
||||
.map_err(|e|{
|
||||
Error::unsupported_command(Unsupported{
|
||||
plugin_name:this.plugin_id().named.clone().into_owned(),
|
||||
command_name:which_variant.variant,
|
||||
error:RBoxError::new(e),
|
||||
supported_commands:this.list_commands(),
|
||||
})
|
||||
})?;
|
||||
|
||||
let ret:ReturnValUnion<R>=match command {
|
||||
CU::Basic(BasicCommand::GetCommands)=>{
|
||||
let commands=this.list_commands();
|
||||
RVU::Basic(BasicRetVal::GetCommands(commands))
|
||||
}
|
||||
CU::ForPlugin(cmd)=>{
|
||||
RVU::ForPlugin(f(this,cmd)?)
|
||||
}
|
||||
};
|
||||
|
||||
match serde_json::to_string(&ret) {
|
||||
Ok(v)=>Ok(v.into()),
|
||||
Err(e)=>Err(Error::Serialize(RBoxError::new(e),WhichCommandRet::Return)),
|
||||
}
|
||||
})().into()
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Sends a typed command to a plugin.
|
||||
|
||||
# Errors
|
||||
|
||||
These are all error that this function returns
|
||||
(this does not include error returned as part of the command):
|
||||
|
||||
- Error::Serialize:
|
||||
If the command/return value could not be serialized to JSON.
|
||||
|
||||
- Error::Deserialize
|
||||
If the command/return value could not be deserialized from JSON(this comes from the plugin).
|
||||
|
||||
- Error::UnsupportedReturnValue:
|
||||
If the return value could not be deserialized from JSON
|
||||
(after checking that it has the `{"name":"...",description: ... }` format),
|
||||
containing the name of the command this is a return value for .
|
||||
|
||||
- Error::UnsupportedCommand
|
||||
If the command is not supported by the plugin.
|
||||
|
||||
*/
|
||||
pub fn send_command<C>(
|
||||
this:&mut PluginType,
|
||||
command:&C,
|
||||
app:ApplicationMut<'_>
|
||||
)->Result<C::Returns,Error>
|
||||
where
|
||||
C:CommandTrait,
|
||||
{
|
||||
let cmd=serde_json::to_string(&command)
|
||||
.map_err(|e| Error::Serialize(RBoxError::new(e),WhichCommandRet::Command) )?;
|
||||
|
||||
let ret=this.json_command(RStr::from(&*cmd),app).into_result()?;
|
||||
|
||||
let which_variant=serde_json::from_str::<WhichVariant>(&*ret)
|
||||
.map_err(|e| Error::Deserialize(RBoxError::new(e),WhichCommandRet::Return) )?;
|
||||
|
||||
serde_json::from_str::<C::Returns>(&ret)
|
||||
.map_err(|e|{
|
||||
Error::unsupported_return_value(Unsupported{
|
||||
plugin_name:this.plugin_id().named.clone().into_owned(),
|
||||
command_name:which_variant.variant,
|
||||
error:RBoxError::new(e),
|
||||
supported_commands:this.list_commands(),
|
||||
})
|
||||
})
|
||||
|
||||
}
|
||||
57
__ffi/abi_stable_crates/interface/src/vec_from_map.rs
Normal file
57
__ffi/abi_stable_crates/interface/src/vec_from_map.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use std::{fmt, marker::PhantomData};
|
||||
use serde::de::{Deserialize, Deserializer, Visitor, MapAccess};
|
||||
|
||||
|
||||
/// Used to deserialize a list of key-value pairs from a json object.
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct VecFromMap<K,V>{
|
||||
pub vec:Vec<(K,V)>,
|
||||
}
|
||||
|
||||
|
||||
struct VecFromMapVisitor<K, V> {
|
||||
marker: PhantomData<(K, V)>
|
||||
}
|
||||
|
||||
impl<K, V> VecFromMapVisitor<K, V> {
|
||||
const NEW:Self=Self{marker:PhantomData};
|
||||
}
|
||||
|
||||
impl<'de, K, V> Visitor<'de> for VecFromMapVisitor<K, V>
|
||||
where
|
||||
K: Deserialize<'de>,
|
||||
V: Deserialize<'de>,
|
||||
{
|
||||
type Value = VecFromMap<K, V>;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a map")
|
||||
}
|
||||
|
||||
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
|
||||
where
|
||||
M: MapAccess<'de>,
|
||||
{
|
||||
let cap=access.size_hint().unwrap_or(0);
|
||||
let mut vec = Vec::<(K,V)>::with_capacity(cap);
|
||||
|
||||
while let Some(pair) = access.next_entry()? {
|
||||
vec.push(pair);
|
||||
}
|
||||
|
||||
Ok(VecFromMap{vec})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, K, V> Deserialize<'de> for VecFromMap<K, V>
|
||||
where
|
||||
K: Deserialize<'de>,
|
||||
V: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_map(VecFromMapVisitor::NEW)
|
||||
}
|
||||
}
|
||||
262
__ffi/abi_stable_crates/interface/src/which_plugin.rs
Normal file
262
__ffi/abi_stable_crates/interface/src/which_plugin.rs
Normal file
@@ -0,0 +1,262 @@
|
||||
use crate::PluginId;
|
||||
|
||||
use std::{fmt::{self,Display}, str::FromStr};
|
||||
use arrayvec::ArrayVec;
|
||||
use abi_stable::{StableAbi, std_types::{RCow,RVec,RString,cow::BorrowingRCowStr}};
|
||||
use core_extensions::{StringExt,SelfOps};
|
||||
use serde::{Serialize,Deserialize,Deserializer,Serializer};
|
||||
|
||||
|
||||
/// A way to choose to which plugins one refers to when sending commands,and other operations.
|
||||
#[repr(u8)]
|
||||
#[derive(Debug,Clone,PartialEq,Eq,StableAbi)]
|
||||
pub enum WhichPlugin{
|
||||
Id(PluginId),
|
||||
First{
|
||||
named:RCow<'static,str>,
|
||||
},
|
||||
Last{
|
||||
named:RCow<'static,str>,
|
||||
},
|
||||
Every{
|
||||
named:RCow<'static,str>,
|
||||
},
|
||||
Many(RVec<WhichPlugin>),
|
||||
}
|
||||
|
||||
|
||||
impl WhichPlugin{
|
||||
/// Converts this `WhichPlugin` to its json representation,
|
||||
/// generally used as a key in a json object.
|
||||
pub fn to_key(&self)->RString{
|
||||
let mut buffer=RString::new();
|
||||
self.write_key(&mut buffer);
|
||||
buffer
|
||||
}
|
||||
|
||||
/// Writes the value of this as a key usable in the application config.
|
||||
pub fn write_key(&self,buf:&mut RString){
|
||||
use std::fmt::Write;
|
||||
match self {
|
||||
WhichPlugin::Id(id)=>write!(buf,"{}:{}",id.named,id.instance).drop_(),
|
||||
WhichPlugin::First{named}=>write!(buf,"{}:first",named).drop_(),
|
||||
WhichPlugin::Last{named}=>write!(buf,"{}:last",named).drop_(),
|
||||
WhichPlugin::Every{named}=>write!(buf,"{}:every",named).drop_(),
|
||||
WhichPlugin::Many(list)=>{
|
||||
for elem in list {
|
||||
elem.write_key(buf);
|
||||
buf.push(',');
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl FromStr for WhichPlugin{
|
||||
type Err=WhichPluginError;
|
||||
|
||||
fn from_str(full_str:&str)->Result<Self,WhichPluginError>{
|
||||
let mut comma_sep=full_str.split(',').peekable();
|
||||
let first=comma_sep.next().unwrap_or("").piped(|s|Self::parse_single(s,full_str))?;
|
||||
|
||||
if comma_sep.peek().is_some() {
|
||||
let mut list:RVec<WhichPlugin>=vec![first].into();
|
||||
for s in comma_sep.filter(|s| !s.is_empty() ) {
|
||||
list.push( Self::parse_single(s,full_str)? );
|
||||
}
|
||||
WhichPlugin::Many(list)
|
||||
}else{
|
||||
first
|
||||
}.piped(Ok)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl WhichPlugin{
|
||||
|
||||
fn parse_single(s:&str,full_str:&str)->Result<Self,WhichPluginError>{
|
||||
let splitted=s.splitn(2,':').map(|s|s.trim()).collect::<ArrayVec<[&str;2]>>();
|
||||
let named=splitted.get(0)
|
||||
.filter(|s| !s.is_empty() )
|
||||
.ok_or_else(|| WhichPluginError(full_str.into()) )?
|
||||
.to_string()
|
||||
.into_(RCow::<'static,str>::T);
|
||||
let selector=splitted.get(1).map_or("",|x|*x);
|
||||
|
||||
match selector {
|
||||
"first"=>return Ok(WhichPlugin::First{named}),
|
||||
""|"last"=>return Ok(WhichPlugin::Last{named}),
|
||||
"all"|"every"=>return Ok(WhichPlugin::Every{named}),
|
||||
_=>(),
|
||||
}
|
||||
|
||||
let instance=selector.parse::<u64>().map_err(|_| WhichPluginError(full_str.into()) )?;
|
||||
Ok(WhichPlugin::Id(PluginId{named,instance}))
|
||||
}
|
||||
|
||||
pub const FMT_MSG:&'static str=r##"
|
||||
|
||||
"plugin name":
|
||||
refers to the last plugin named "plugin name".
|
||||
|
||||
"plugin name:10":
|
||||
refers to the 10th instance of the plugin named "plugin name".
|
||||
|
||||
"plugin name:first":
|
||||
refers to the first instance of the plugin named "plugin name".
|
||||
|
||||
"plugin name:last":
|
||||
refers to the last instance of the plugin named "plugin name".
|
||||
|
||||
"plugin name:every":
|
||||
refers to all the instances of the plugin named "plugin name".
|
||||
|
||||
"plugin name 1,plugin name 2:first,plugin name 3:every":
|
||||
refers to the last instance of the plugin named "plugin name 1".
|
||||
refers to the first instance of the plugin named "plugin name 2".
|
||||
refers to the all the instances of the plugin named "plugin name 3".
|
||||
|
||||
Plugin names:
|
||||
|
||||
- Are trimmed,so you can add spaces at the start and the end.
|
||||
|
||||
- Cannot contain commas,since they will be interpreted as a list of plugins.
|
||||
|
||||
|
||||
"##;
|
||||
|
||||
}
|
||||
|
||||
|
||||
impl<'de> Deserialize<'de> for WhichPlugin{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
use serde::de;
|
||||
BorrowingRCowStr::deserialize(deserializer)?
|
||||
.cow
|
||||
.parse::<Self>()
|
||||
.map_err(de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl Serialize for WhichPlugin{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.to_key().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Debug,Clone,StableAbi)]
|
||||
pub struct WhichPluginError(RString);
|
||||
|
||||
|
||||
impl Display for WhichPluginError{
|
||||
fn fmt(&self,f:&mut fmt::Formatter)->fmt::Result{
|
||||
writeln!(
|
||||
f,
|
||||
"Could not parse this as a `WhichPlugin`:\n\t'{}'\nExpected format:\n{}\n",
|
||||
self.0,
|
||||
WhichPlugin::FMT_MSG.left_padder(4),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests{
|
||||
use super::*;
|
||||
|
||||
fn new_str_expected()->Vec<(&'static str,WhichPlugin)>{
|
||||
vec![
|
||||
(
|
||||
"plugin name",
|
||||
WhichPlugin::Last{named:"plugin name".into()}
|
||||
),
|
||||
(
|
||||
"plugin name:10",
|
||||
WhichPlugin::Id(PluginId{
|
||||
named:"plugin name".into(),
|
||||
instance:10,
|
||||
})
|
||||
),
|
||||
(
|
||||
"plugin name:first",
|
||||
WhichPlugin::First{named:"plugin name".into()}
|
||||
),
|
||||
(
|
||||
"plugin name:last",
|
||||
WhichPlugin::Last{named:"plugin name".into()}
|
||||
),
|
||||
(
|
||||
"plugin name:every",
|
||||
WhichPlugin::Every{named:"plugin name".into()}
|
||||
),
|
||||
(
|
||||
"plugin name 1,plugin name 2:first,plugin name 3:every",
|
||||
WhichPlugin::Many(vec![
|
||||
WhichPlugin::Last{named:"plugin name 1".into()},
|
||||
WhichPlugin::First{named:"plugin name 2".into()},
|
||||
WhichPlugin::Every{named:"plugin name 3".into()},
|
||||
].into())
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_correctly(){
|
||||
let str_expected=new_str_expected();
|
||||
|
||||
for (str_,expected) in str_expected {
|
||||
let parsed=str_.parse::<WhichPlugin>().unwrap();
|
||||
assert_eq!(parsed,expected);
|
||||
|
||||
assert_eq!(
|
||||
parsed.to_key().parse::<WhichPlugin>().unwrap(),
|
||||
expected,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn serde_(){
|
||||
let str_expected=new_str_expected();
|
||||
|
||||
for (_,elem) in str_expected {
|
||||
let str_=serde_json::to_string(&elem).unwrap();
|
||||
let other:WhichPlugin=serde_json::from_str(&str_)
|
||||
.unwrap_or_else(|e| panic!("{}",e) );
|
||||
assert_eq!(other,elem);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn parses_incorrectly(){
|
||||
let list=vec![
|
||||
// An empty plugin name is invalid
|
||||
"",
|
||||
":",
|
||||
":first",
|
||||
":last",
|
||||
",",
|
||||
",,,:first,:last",
|
||||
];
|
||||
|
||||
for str_ in list {
|
||||
str_.parse::<WhichPlugin>().unwrap_err();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user