Encode payload (mask PII). When context is Llm, tokens get a 3-digit signature and instruction text is prepended.
(&self, payload: serde_json::Value, context: EncodeContext)
| 225 | impl Enforcer { |
| 226 | /// Encode payload (mask PII). When context is Llm, tokens get a 3-digit signature and instruction text is prepended. |
| 227 | pub fn encode(&self, payload: serde_json::Value, context: EncodeContext) -> EncodeResult { |
| 228 | let default_result = EncodeResult { |
| 229 | payload: payload.clone(), |
| 230 | signature_injection_text: String::new(), |
| 231 | rules_applied_count: 0, |
| 232 | rule_names: Vec::new(), |
| 233 | policy_name: String::new(), |
| 234 | }; |
| 235 | if self.handle.is_null() { |
| 236 | return default_result; |
| 237 | } |
| 238 | let json = match serde_json::to_string(&payload) { |
| 239 | Ok(s) => s, |
| 240 | Err(_) => return default_result, |
| 241 | }; |
| 242 | let c_str = match CString::new(json.as_bytes()) { |
| 243 | Ok(c) => c, |
| 244 | Err(_) => return default_result, |
| 245 | }; |
| 246 | let enc_ctx = match context { |
| 247 | EncodeContext::Llm => ENCODE_CONTEXT_LLM, |
| 248 | EncodeContext::Manual => ENCODE_CONTEXT_MANUAL, |
| 249 | }; |
| 250 | let out = unsafe { |
| 251 | guardrail_encode( |
| 252 | self.handle, |
| 253 | c_str.as_ptr(), |
| 254 | c_str.as_bytes().len(), |
| 255 | enc_ctx, |
| 256 | ) |
| 257 | }; |
| 258 | if out.is_null() { |
| 259 | return default_result; |
| 260 | } |
| 261 | let out_slice = unsafe { CStr::from_ptr(out).to_bytes() }; |
| 262 | let out_str = String::from_utf8_lossy(out_slice).into_owned(); |
| 263 | unsafe { guardrail_free(out) }; |
| 264 | parse_encode_result(&out_str) |
| 265 | .or_else(|| parse_encode_result_legacy(&out_str)) |
| 266 | .unwrap_or(default_result) |
| 267 | } |
| 268 | |
| 269 | /// Decode payload (rehydrate PII). |
| 270 | pub fn decode(&self, payload: serde_json::Value, context: DecodeContext) -> DecodeResult { |
no test coverage detected