koicore_ffi 0.2.3

FFI bindings for koicore
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use koicore::{
    Value,
    command::{Command, CompositeValue, Parameter},
};
use std::{
    ffi::{CStr, c_char},
    ptr, slice,
};

use crate::command::param::KoiParamType;

use super::command::KoiCommand;

/// Opaque handle for composite dict parameter
///
/// This struct represents a dictionary-style composite parameter that stores key-value pairs.
/// The keys are strings, and the values can be integers, floats, or strings.
/// This is an opaque type intended for use through the C FFI API.
#[repr(C)]
pub struct KoiCompositeDict {
    _data: (),
    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}

/// Create a new composite dict parameter
///
/// Creates an empty dictionary with no key-value pairs. The returned pointer
/// must be freed using KoiCompositeDict_Del when no longer needed to avoid memory leaks,
/// unless it is passed to KoiCommand_AddCompositeDict.
///
/// # Arguments
///
/// * `name` - The name of the composite parameter (null-terminated C string)
///
/// # Returns
/// Pointer to the new composite dict parameter, or null on error
///
/// # Safety
/// The returned pointer must not be used after calling KoiCompositeDict_Del on it.
/// The caller is responsible for memory management of the returned object.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_New(name: *const c_char) -> *mut KoiCompositeDict {
    if name.is_null() {
        return ptr::null_mut();
    }

    let name_str = match unsafe { CStr::from_ptr(name) }.to_str() {
        Ok(s) => s.to_string(),
        Err(_) => return ptr::null_mut(),
    };

    let param = Parameter::Composite(name_str, CompositeValue::Dict(Vec::new()));
    Box::into_raw(Box::new(param)) as *mut KoiCompositeDict
}

/// Add composite dict to command
///
/// Adds the specified composite dict to the command's parameters.
/// This function TAKES OWNERSHIP of the dict pointer. The caller must NOT
/// free the dict using KoiCompositeDict_Del after a successful call.
///
/// # Arguments
///
/// * `command` - Pointer to the command object
/// * `dict` - Pointer to the composite dict parameter to add
///
/// # Returns
///
/// 0 on success, or a non-zero error code on failure:
/// - -1: command or dict pointer is NULL
/// - -3: command pointer is invalid
///
/// # Safety
///
/// The `command` pointer must be a valid KoiCommand.
/// The `dict` pointer must be a valid KoiCompositeDict created with KoiCompositeDict_New.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCommand_AddCompositeDict(
    command: *mut KoiCommand,
    dict: *mut KoiCompositeDict,
) -> i32 {
    if command.is_null() || dict.is_null() {
        return -1;
    }

    let command = unsafe { &mut *(command as *mut Command) };
    let dict_param = unsafe { Box::from_raw(dict as *mut Parameter) };

    command.params.push(*dict_param);
    0
}

/// Get composite dict parameter from command
///
/// Retrieves a dictionary parameter from a command at the specified index.
/// The parameter must be of dictionary type, otherwise null is returned.
///
/// # Ownership and Lifetime
///
/// The returned pointer is a borrowed reference to data owned by the command.
/// It must NOT be freed with KoiCompositeDict_Del. The pointer is only valid
/// as long as the command object exists and is not modified or destroyed.
///
/// # Arguments
/// * `command` - Command object pointer
/// * `index` - Parameter index (0-based)
///
/// # Returns
/// Pointer to composite dict parameter, or null on error:
/// - null if command is null
/// - null if index is out of bounds
/// - null if parameter at index is not a dictionary
///
/// # Safety
/// The command pointer must be either null or point to a valid KoiCommand object.
/// The returned pointer must NOT be freed with KoiCompositeDict_Del as it is owned by the command.
/// The returned pointer becomes invalid if the command is destroyed or modified.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCommand_GetCompositeDict(
    command: *mut KoiCommand,
    index: usize,
) -> *mut KoiCompositeDict {
    if command.is_null() {
        return ptr::null_mut();
    }

    let command = unsafe { &*(command as *mut Command) };
    let params = command.params();

    if index >= params.len() {
        return ptr::null_mut();
    }

    match &params[index] {
        p @ &Parameter::Composite(_, CompositeValue::Dict(_)) => {
            // Cast the parameter reference to the opaque dict type
            p as *const Parameter as *mut KoiCompositeDict
        }
        _ => ptr::null_mut(),
    }
}

/// Get number of entries in dict
///
/// Returns the count of key-value pairs currently stored in the dictionary.
/// This is useful for iteration or checking if the dictionary is empty.
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
///
/// # Returns
/// Number of entries in the dict, 0 on error:
/// - 0 if dict is null
/// - 0 if dict is not a valid dictionary
///
/// # Safety
/// The dict pointer must be a valid KoiCompositeDict pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetLength(dict: *mut KoiCompositeDict) -> usize {
    if dict.is_null() {
        return 0;
    }

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => entries.len(),
        _ => 0,
    }
}

/// Remove entry from composite dict by key
///
/// Removes a key-value pair from the dictionary based on the provided key.
/// If the key does not exist in the dictionary, the function returns an error.
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name (null-terminated UTF-8 string)
///
/// # Returns
/// 0 on success, non-zero on error:
/// - -1 if dict or key is null
/// - -2 if key contains invalid UTF-8
/// - -3 if key not found in dictionary
/// - -4 if dict is not a valid dictionary
///
/// # Safety
/// The dict pointer must be a valid KoiCompositeDict pointer.
/// The key pointer must be a valid null-terminated C string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_Remove(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
) -> i32 {
    if dict.is_null() || key.is_null() {
        return -1;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let param = unsafe { &mut *(dict as *mut Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            let original_len = entries.len();
            entries.retain(|(k, _)| k != key_str);

            if entries.len() == original_len {
                // Key not found
                return -3;
            }
            0
        }
        _ => -4,
    }
}

/// Clear all entries from composite dict
///
/// Removes all key-value pairs from the dictionary, making it empty.
/// This operation is irreversible but does not deallocate the dictionary itself.
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
///
/// # Returns
/// 0 on success, non-zero on error:
/// - -1 if dict is null
/// - -3 if dict is not a valid dictionary
///
/// # Safety
/// The dict pointer must be a valid KoiCompositeDict pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_Clear(dict: *mut KoiCompositeDict) -> i32 {
    if dict.is_null() {
        return -1;
    }

    let param = unsafe { &mut *(dict as *mut Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            entries.clear();
            0
        }
        _ => -3,
    }
}

/// Free composite dict parameter
///
/// Deallocates the memory used by the dictionary and all its key-value pairs.
/// After calling this function, the pointer becomes invalid and must not be used.
/// This function should only be called on dictionaries created with KoiCompositeDict_New,
/// not on dictionaries obtained from KoiCommand_GetCompositeDict.
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
///
/// # Safety
/// The dict pointer must be a valid KoiCompositeDict pointer created with KoiCompositeDict_New.
/// Do not call this function on pointers obtained from KoiCommand_GetCompositeDict.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_Del(dict: *mut KoiCompositeDict) {
    if dict.is_null() {
        return;
    }

    unsafe { drop(Box::from_raw(dict as *mut Parameter)) };
}

/// Set integer value in composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
/// * `value` - Integer value to set
///
/// # Returns
/// 0 on success, non-zero on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_SetIntValue(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
    value: i64,
) -> i32 {
    if dict.is_null() || key.is_null() {
        return -1;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let param = unsafe { &mut *(dict as *mut Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, v)) = entries.iter_mut().find(|(k, _)| k == key_str) {
                *v = Value::Int(value);
                0
            } else {
                entries.push((key_str.to_string(), Value::Int(value)));
                0
            }
        }
        _ => -3,
    }
}

/// Set float value in composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
/// * `value` - Float value to set
///
/// # Returns
/// 0 on success, non-zero on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_SetFloatValue(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
    value: f64,
) -> i32 {
    if dict.is_null() || key.is_null() {
        return -1;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let param = unsafe { &mut *(dict as *mut Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, v)) = entries.iter_mut().find(|(k, _)| k == key_str) {
                *v = Value::Float(value);
                0
            } else {
                entries.push((key_str.to_string(), Value::Float(value)));
                0
            }
        }
        _ => -3,
    }
}

/// Set string value in composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
/// * `value` - String value to set
///
/// # Returns
/// 0 on success, non-zero on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_SetStringValue(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
    value: *const c_char,
) -> i32 {
    if dict.is_null() || key.is_null() || value.is_null() {
        return -1;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let value_str = unsafe { CStr::from_ptr(value) };
    let value_str = match value_str.to_str() {
        Ok(s) => s,
        Err(_) => return -3,
    };

    let param = unsafe { &mut *(dict as *mut Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, v)) = entries.iter_mut().find(|(k, _)| k == key_str) {
                *v = Value::String(value_str.to_string());
                0
            } else {
                entries.push((key_str.to_string(), Value::String(value_str.to_string())));
                0
            }
        }
        _ => -4,
    }
}

/// Get dict key by index into provided buffer
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `index` - Entry index
/// * `buffer` - Buffer for key output
/// * `buffer_size` - Buffer size
///
/// # Returns
/// Actual key length (excluding null terminator), or required buffer size if insufficient
/// Returns 0 on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetKeybyIndex(
    dict: *mut KoiCompositeDict,
    index: usize,
    buffer: *mut c_char,
    buffer_size: usize,
) -> usize {
    if dict.is_null() {
        return 0;
    }

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if index >= entries.len() {
                return 0;
            }

            let key = &entries[index].0;
            let key_bytes = key.as_bytes();
            let key_len = key_bytes.len();
            let required_size = key_len + 1;

            if buffer.is_null() || buffer_size < required_size {
                return required_size;
            }

            let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer as *mut u8, buffer_size) };
            buffer_slice[..key_len].copy_from_slice(key_bytes);
            buffer_slice[key_len] = 0;

            required_size
        }
        _ => 0,
    }
}

/// Get dict key length by index
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `index` - Entry index
///
/// # Returns
/// Required buffer size (including null terminator)
/// Returns 0 on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetKeyLenByIndex(
    dict: *mut KoiCompositeDict,
    index: usize,
) -> usize {
    if dict.is_null() {
        return 0;
    }

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if index >= entries.len() {
                return 0;
            }

            let key = &entries[index].0;
            key.len() + 1
        }
        _ => 0,
    }
}

/// Get dict value type by index
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `index` - Entry index
///
/// # Returns
/// Value type as KoiParamType enum value
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetValueTypeByIndex(
    dict: *mut KoiCompositeDict,
    index: usize,
) -> i32 {
    if dict.is_null() {
        return KoiParamType::Invalid as i32;
    }

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if index >= entries.len() {
                KoiParamType::Invalid as i32
            } else {
                match &entries[index].1 {
                    Value::Int(_) => KoiParamType::BasicInt as i32,
                    Value::Float(_) => KoiParamType::BasicFloat as i32,
                    Value::String(_) => KoiParamType::BasicString as i32,
                    Value::Bool(_) => KoiParamType::BasicBool as i32,
                }
            }
        }
        _ => KoiParamType::Invalid as i32,
    }
}

/// Get value type from composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
///
/// # Returns
/// Value type as KoiParamType enum value
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetValueType(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
) -> i32 {
    if dict.is_null() || key.is_null() {
        return KoiParamType::Invalid as i32;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return KoiParamType::Invalid as i32,
    };

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, value)) = entries.iter().find(|(k, _)| k == key_str) {
                match value {
                    Value::Int(_) => KoiParamType::BasicInt as i32,
                    Value::Float(_) => KoiParamType::BasicFloat as i32,
                    Value::String(_) => KoiParamType::BasicString as i32,
                    Value::Bool(_) => KoiParamType::BasicBool as i32,
                }
            } else {
                KoiParamType::Invalid as i32
            }
        }
        _ => KoiParamType::Invalid as i32,
    }
}

/// Get integer value from composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
/// * `out_value` - Pointer to store integer value
///
/// # Returns
/// 0 on success, non-zero on error or type mismatch
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetIntValue(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
    out_value: *mut i64,
) -> i32 {
    if dict.is_null() || key.is_null() || out_value.is_null() {
        return -1;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, value)) = entries.iter().find(|(k, _)| k == key_str) {
                match value {
                    Value::Int(v) => {
                        unsafe { *out_value = *v };
                        0
                    }
                    _ => -3,
                }
            } else {
                -2 // Key not found
            }
        }
        _ => -4,
    }
}

/// Get float value from composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
/// * `out_value` - Pointer to store float value
///
/// # Returns
/// 0 on success, non-zero on error or type mismatch
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetFloatValue(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
    out_value: *mut f64,
) -> i32 {
    if dict.is_null() || key.is_null() || out_value.is_null() {
        return -1;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, value)) = entries.iter().find(|(k, _)| k == key_str) {
                match value {
                    Value::Float(v) => {
                        unsafe { *out_value = *v };
                        0
                    }
                    _ => -3,
                }
            } else {
                -2 // Key not found
            }
        }
        _ => -4,
    }
}

/// Get string value from composite dict by key into provided buffer
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
/// * `buffer` - Buffer for string output
/// * `buffer_size` - Buffer size
///
/// # Returns
/// Actual string length (excluding null terminator), or required buffer size if insufficient
/// Returns 0 on error or type mismatch
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetStringValue(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
    buffer: *mut c_char,
    buffer_size: usize,
) -> usize {
    if dict.is_null() || key.is_null() {
        return 0;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, Value::String(v))) = entries.iter().find(|(k, _)| k == key_str) {
                let v_bytes = v.as_bytes();
                let v_len = v_bytes.len();
                let required_size = v_len + 1;

                if buffer.is_null() || buffer_size < required_size {
                    return required_size;
                }

                let buffer_slice =
                    unsafe { slice::from_raw_parts_mut(buffer as *mut u8, buffer_size) };
                buffer_slice[..v_len].copy_from_slice(v_bytes);
                buffer_slice[v_len] = 0;

                required_size
            } else {
                0 // Key not found, return 0 to indicate error
            }
        }
        _ => 0,
    }
}

/// Get string value length from composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
///
/// # Returns
/// Required buffer size (including null terminator), or 0 on error or type mismatch
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetStringValueLen(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
) -> usize {
    if dict.is_null() || key.is_null() {
        return 0;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, Value::String(v))) = entries.iter().find(|(k, _)| k == key_str) {
                v.len() + 1
            } else {
                0 // Key not found, return 0 to indicate error
            }
        }
        _ => 0,
    }
}

/// Get boolean value from composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
/// * `out_value` - Pointer to store boolean value (1 for true, 0 for false)
///
/// # Returns
/// 0 on success, non-zero on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_GetBoolValue(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
    out_value: *mut i32,
) -> i32 {
    if dict.is_null() || key.is_null() || out_value.is_null() {
        return -1;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let param = unsafe { &*(dict as *const Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, value)) = entries.iter().find(|(k, _)| k == key_str) {
                match value {
                    Value::Bool(v) => {
                        unsafe { *out_value = if *v { 1 } else { 0 } };
                        0
                    }
                    _ => -3,
                }
            } else {
                -2 // Key not found
            }
        }
        _ => -4,
    }
}

/// Set boolean value in composite dict by key
///
/// # Arguments
/// * `dict` - Composite dict parameter pointer
/// * `key` - Key name
/// * `value` - Boolean value to set (non-zero for true, 0 for false)
///
/// # Returns
/// 0 on success, non-zero on error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn KoiCompositeDict_SetBoolValue(
    dict: *mut KoiCompositeDict,
    key: *const c_char,
    value: i32,
) -> i32 {
    if dict.is_null() || key.is_null() {
        return -1;
    }

    let key_str = unsafe { CStr::from_ptr(key) };
    let key_str = match key_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let param = unsafe { &mut *(dict as *mut Parameter) };
    match param {
        Parameter::Composite(_, CompositeValue::Dict(entries)) => {
            if let Some((_, v)) = entries.iter_mut().find(|(k, _)| k == key_str) {
                *v = Value::Bool(value != 0);
                0
            } else {
                entries.push((key_str.to_string(), Value::Bool(value != 0)));
                0
            }
        }
        _ => -3,
    }
}