summaryrefslogtreecommitdiffstats
path: root/netwerk/base/rust-url-capi/src/string_utils.rs
blob: ae68a60dc3d2cc92c67002240afbb0b32d0df68d (plain)
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
extern crate libc;
use libc::size_t;

extern crate std;
use std::ptr;

use error_mapping::*;

extern "C" {
  fn c_fn_set_size(user: *mut libc::c_void, size: size_t) -> i32;
  fn c_fn_get_buffer(user: *mut libc::c_void) -> *mut libc::c_char;
}

pub trait StringContainer {
  fn set_size(&self, size_t) -> i32;
  fn get_buffer(&self) -> *mut libc::c_char;
  fn assign(&self, content: &str) -> i32;
}

impl StringContainer for *mut libc::c_void {
  fn set_size(&self, size: size_t) -> i32 {
    if (*self).is_null() {
      return NSError::InvalidArg.error_code();
    }
    unsafe {
      c_fn_set_size(*self, size);
    }

    return NSError::OK.error_code();
  }
  fn get_buffer(&self) -> *mut libc::c_char {
    if (*self).is_null() {
      return 0 as *mut libc::c_char;
    }
    unsafe {
      c_fn_get_buffer(*self)
    }
  }
  fn assign(&self, content: &str) -> i32 {
    if (*self).is_null() {
      return NSError::InvalidArg.error_code();
    }

    unsafe {
      let slice = content.as_bytes();
      c_fn_set_size(*self, slice.len());
      let buf = c_fn_get_buffer(*self);
      if buf.is_null() {
        return NSError::Failure.error_code();
      }

      ptr::copy(slice.as_ptr(), buf as *mut u8, slice.len());
    }

    NSError::OK.error_code()
  }
}