strings.rs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // Copyright (c) 2016-2018, The Tor Project, Inc. */
  2. // See LICENSE for licensing information */
  3. //! Utilities for working with static strings.
  4. /// Create a `CStr` from a literal byte slice, appending a NUL byte to it first.
  5. ///
  6. /// # Warning
  7. ///
  8. /// The literal byte slice which is taken as an argument *MUST NOT* have any NUL
  9. /// bytes (`b"\0"`) in it, anywhere, or else an empty string will be returned
  10. /// (`CStr::from_bytes_with_nul_unchecked(b"\0")`) so as to avoid `panic!()`ing.
  11. ///
  12. /// # Examples
  13. ///
  14. /// ```
  15. /// #[macro_use]
  16. /// extern crate tor_util;
  17. ///
  18. /// use std::ffi::CStr;
  19. ///
  20. /// # fn do_test() -> Result<&'static CStr, &'static str> {
  21. /// let message: &'static str = "This is a test of the tsunami warning system.";
  22. /// let tuesday: &'static CStr;
  23. /// let original: &str;
  24. ///
  25. /// tuesday = cstr!("This is a test of the tsunami warning system.");
  26. /// original = tuesday.to_str().or(Err("Couldn't unwrap CStr!"))?;
  27. ///
  28. /// assert!(original == message);
  29. /// #
  30. /// # Ok(tuesday)
  31. /// # }
  32. /// # fn main() {
  33. /// # do_test(); // so that we can use the ? operator in the test
  34. /// # }
  35. /// ```
  36. /// It is also possible to pass several string literals to this macro. They
  37. /// will be concatenated together in the order of the arguments, unmodified,
  38. /// before finally being suffixed with a NUL byte:
  39. ///
  40. /// ```
  41. /// #[macro_use]
  42. /// extern crate tor_util;
  43. /// #
  44. /// # use std::ffi::CStr;
  45. /// #
  46. /// # fn do_test() -> Result<&'static CStr, &'static str> {
  47. ///
  48. /// let quux: &'static CStr = cstr!("foo", "bar", "baz");
  49. /// let orig: &'static str = quux.to_str().or(Err("Couldn't unwrap CStr!"))?;
  50. ///
  51. /// assert!(orig == "foobarbaz");
  52. /// # Ok(quux)
  53. /// # }
  54. /// # fn main() {
  55. /// # do_test(); // so that we can use the ? operator in the test
  56. /// # }
  57. /// ```
  58. /// This is useful for passing static strings to C from Rust FFI code. To do so
  59. /// so, use the `.as_ptr()` method on the resulting `&'static CStr` to convert
  60. /// it to the Rust equivalent of a C `const char*`:
  61. ///
  62. /// ```
  63. /// #[macro_use]
  64. /// extern crate tor_util;
  65. ///
  66. /// use std::ffi::CStr;
  67. /// use std::os::raw::c_char;
  68. ///
  69. /// pub extern "C" fn give_static_borrowed_string_to_c() -> *const c_char {
  70. /// let hello: &'static CStr = cstr!("Hello, language my parents wrote.");
  71. ///
  72. /// hello.as_ptr()
  73. /// }
  74. /// # fn main() {
  75. /// # let greetings = give_static_borrowed_string_to_c();
  76. /// # }
  77. /// ```
  78. /// Note that the C code this static borrowed string is passed to *MUST NOT*
  79. /// attempt to free the memory for the string.
  80. ///
  81. /// # Note
  82. ///
  83. /// An unfortunate limitation of the rustc compiler (as of 1.25.0-nightly), is
  84. /// that the first example above compiles, but if we were to change the
  85. /// assignment of `tuesday` as follows, it will fail to compile, because Rust
  86. /// macros are expanded at parse time, and at parse time there is no symbol
  87. /// table available.
  88. ///
  89. /// ```ignore
  90. /// tuesday = cstr!(message);
  91. /// ```
  92. /// with the error message `error: expected a literal`.
  93. ///
  94. /// # Returns
  95. ///
  96. /// If the string literals passed as arguments contain no NUL bytes anywhere,
  97. /// then an `&'static CStr` containing the (concatenated) bytes of the string
  98. /// literal(s) passed as arguments, with a NUL byte appended, is returned.
  99. /// Otherwise, an `&'static CStr` containing a single NUL byte is returned (an
  100. /// "empty" string in C).
  101. #[macro_export]
  102. macro_rules! cstr {
  103. ($($bytes:expr),*) => (
  104. ::std::ffi::CStr::from_bytes_with_nul(
  105. concat!($($bytes),*, "\0").as_bytes()
  106. ).unwrap_or(
  107. unsafe{
  108. ::std::ffi::CStr::from_bytes_with_nul_unchecked(b"\0")
  109. }
  110. )
  111. )
  112. }
  113. #[cfg(test)]
  114. mod test {
  115. use std::ffi::CStr;
  116. #[test]
  117. fn cstr_macro() {
  118. let _: &'static CStr = cstr!("boo");
  119. }
  120. #[test]
  121. fn cstr_macro_multi_input() {
  122. let quux: &'static CStr = cstr!("foo", "bar", "baz");
  123. assert!(quux.to_str().unwrap() == "foobarbaz");
  124. }
  125. #[test]
  126. fn cstr_macro_bad_input() {
  127. let waving: &'static CStr = cstr!("waving not drowning o/");
  128. let drowning: &'static CStr = cstr!("\0 drowning not waving");
  129. assert!(waving.to_str().unwrap() == "waving not drowning o/");
  130. assert!(drowning.to_str().unwrap() == "")
  131. }
  132. }