lib.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. //! fcntl implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/fcntl.h.html
  2. #![no_std]
  3. #![allow(non_camel_case_types)]
  4. //TODO #![feature(thread_local)]
  5. #[cfg(all(not(feature = "no_std"), target_os = "linux"))]
  6. #[macro_use]
  7. extern crate sc;
  8. #[cfg(all(not(feature = "no_std"), target_os = "redox"))]
  9. #[macro_use]
  10. extern crate syscall;
  11. pub use sys::*;
  12. #[cfg(all(not(feature = "no_std"), target_os = "linux"))]
  13. #[path = "linux/mod.rs"]
  14. mod sys;
  15. #[cfg(all(not(feature = "no_std"), target_os = "redox"))]
  16. #[path = "redox/mod.rs"]
  17. mod sys;
  18. pub mod types;
  19. use core::fmt;
  20. use types::*;
  21. //TODO #[thread_local]
  22. #[allow(non_upper_case_globals)]
  23. #[no_mangle]
  24. pub static mut errno: c_int = 0;
  25. pub unsafe fn c_str(s: *const c_char) -> &'static [u8] {
  26. use core::usize;
  27. c_str_n(s, usize::MAX)
  28. }
  29. pub unsafe fn c_str_n(s: *const c_char, n: usize) -> &'static [u8] {
  30. use core::slice;
  31. let mut size = 0;
  32. for _ in 0..n {
  33. if *s.offset(size) == 0 {
  34. break;
  35. }
  36. size += 1;
  37. }
  38. slice::from_raw_parts(s as *const u8, size as usize)
  39. }
  40. pub struct FileWriter(pub c_int);
  41. impl FileWriter {
  42. pub fn write(&mut self, buf: &[u8]) {
  43. write(self.0, buf);
  44. }
  45. }
  46. impl fmt::Write for FileWriter {
  47. fn write_str(&mut self, s: &str) -> fmt::Result {
  48. self.write(s.as_bytes());
  49. Ok(())
  50. }
  51. }
  52. pub struct StringWriter(pub *mut u8, pub usize);
  53. impl StringWriter {
  54. pub unsafe fn write(&mut self, buf: &[u8]) {
  55. for &b in buf.iter() {
  56. if self.1 == 0 {
  57. break;
  58. } else if self.1 == 1 {
  59. *self.0 = b'\0';
  60. } else {
  61. *self.0 = b;
  62. }
  63. self.0 = self.0.offset(1);
  64. self.1 -= 1;
  65. if self.1 > 0 {
  66. *self.0 = b'\0';
  67. }
  68. }
  69. }
  70. }
  71. impl fmt::Write for StringWriter {
  72. fn write_str(&mut self, s: &str) -> fmt::Result {
  73. unsafe { self.write(s.as_bytes()) };
  74. Ok(())
  75. }
  76. }
  77. pub struct UnsafeStringWriter(pub *mut u8);
  78. impl UnsafeStringWriter {
  79. pub unsafe fn write(&mut self, buf: &[u8]) {
  80. for &b in buf.iter() {
  81. *self.0 = b;
  82. self.0 = self.0.offset(1);
  83. *self.0 = b'\0';
  84. }
  85. }
  86. }
  87. impl fmt::Write for UnsafeStringWriter {
  88. fn write_str(&mut self, s: &str) -> fmt::Result {
  89. unsafe { self.write(s.as_bytes()) };
  90. Ok(())
  91. }
  92. }