Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add more api definitions in the kclvm api crate #1373

Merged
merged 1 commit into from
May 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 66 additions & 2 deletions kclvm/api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,72 @@
pub mod service;

//! # KCL Rust SDK
//!
//! ## How to Use
//!
//! ```no_check,no_run
//! cargo add --git https://github.com/kcl-lang/kcl kclvm_api
//! ```
//!
//! Write the Code
//!
//! ```no_run
//! use kclvm_api::*;
//! use std::path::Path;
//! use anyhow::Result;
//!
//! fn main() -> Result<()> {
//! let api = API::default();
//! let args = &ExecProgramArgs {
//! work_dir: Path::new(".").join("testdata").canonicalize().unwrap().display().to_string(),
//! k_filename_list: vec!["test.k".to_string()],
//! ..Default::default()
//! };
//! let exec_result = api.exec_program(args)?;
//! assert_eq!(exec_result.yaml_result, "alice:\n age: 18");
//! Ok(())
//! }
//! ```
#[cfg(test)]
pub mod capi_test;
pub mod service;

pub mod gpyrpc {
include!(concat!(env!("OUT_DIR"), "/gpyrpc.rs"));
}

pub use crate::gpyrpc::*;
use crate::service::capi::{kclvm_service_call_with_length, kclvm_service_new};
use crate::service::service_impl::KclvmServiceImpl;
use anyhow::Result;
use std::ffi::CString;

pub type API = KclvmServiceImpl;

/// Call KCL API with the API name and argument protobuf bytes.
#[inline]
pub fn call<'a>(name: &'a [u8], args: &'a [u8]) -> Result<Vec<u8>> {
call_with_plugin_agent(name, args, 0)
}

/// Call KCL API with the API name, argument protobuf bytes and the plugin agent pointer address.
pub fn call_with_plugin_agent<'a>(
name: &'a [u8],
args: &'a [u8],
plugin_agent: u64,
) -> Result<Vec<u8>> {
let mut result_len: usize = 0;
let result_ptr = {
let args = CString::new(args)?;
let call = CString::new(name)?;
let serv = kclvm_service_new(plugin_agent);
kclvm_service_call_with_length(serv, call.as_ptr(), args.as_ptr(), &mut result_len)
};
let result = unsafe {
let mut dest_data: Vec<u8> = Vec::with_capacity(result_len);
let dest_ptr: *mut u8 = dest_data.as_mut_ptr();
std::ptr::copy_nonoverlapping(result_ptr as *const u8, dest_ptr, result_len);
dest_data.set_len(result_len);
dest_data
};

Ok(result)
}
Loading