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
//! Minimal wrapper over Android logging facilities.
//!
//! ## Features:
//!
//! - `std` - Enables `std::io::Write` implementation.
//!
//! ## Usage
//!
//! ```rust,no_run
//! use androidy_log::{LogPriority, Writer};
//!
//! use core::fmt::Write;
//!
//! let mut writer = Writer::new("MyTag", LogPriority::INFO);
//! let _ = write!(writer, "Hellow World!");
//! drop(writer); //or writer.flush();
//!
//! androidy_log::println!("Hello via macro!");
//! androidy_log::eprintln!("Error via macro!");
//! ```
//!

#![cfg_attr(not(test), no_std)]
#![warn(missing_docs)]

#[cfg(feature = "std")]
extern crate std;

use core::{cmp, mem, ptr, fmt};

///Priority of the log message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum LogPriority {
    ///For internal use only.
    UNKNOWN = 0,
    ///The default priority, for internal use only.
    DEFAULT = 1,
    ///Verbose logging.
    VERBOSE = 2,
    ///Debug logging.
    DEBUG = 3,
    ///Informational logging.
    INFO = 4,
    ///Warning logging.
    ///
    ///For use with recoverable failures.
    WARN = 5,
    ///Error logging.
    ///
    ///For use with unrecoverable failures.
    ERROR = 6,
    ///Fatal logging.
    ///
    ///For use when aborting.
    FATAL = 7,
    ///For internal use only.
    SILENT = 8,
}

const TAG_MAX_LEN: usize = 23;
//Re-check NDK sources, I think internally kernel limits to 4076, but
//it includes some overhead of logcat machinery, hence 4000
//Don't remember details
const BUFFER_CAPACITY: usize = 4000;
const DEFAULT_TAG: &str = "Rust";

#[cfg(not(test))]
#[link(name = "log")]
extern "C" {
    fn __android_log_write(prio: i32, tag: *const i8, text: *const i8) -> i32;
}

#[cfg(test)]
fn __android_log_write(_: i32, _: *const i8, _: *const i8) -> i32 {
    0
}

///Android log writer.
///
///By default every write is buffer unless buffer overflow happens.
///Buffered input is flushed on `Drop` or via manual call.
pub struct Writer {
    //Null character is not within limit
    tag: mem::MaybeUninit<[u8; TAG_MAX_LEN + 1]>,
    prio: LogPriority,
    //Null character is not within limit
    buffer: mem::MaybeUninit<[u8; BUFFER_CAPACITY + 1]>,
    len: usize,
}

impl Writer {
    #[inline(always)]
    ///Creates new instance using default tag `Rust`
    ///
    ///- `prio` - Logging priority.
    pub const fn new_default(prio: LogPriority) -> Self {
        let mut tag = [0u8; TAG_MAX_LEN + 1];

        tag[0] = DEFAULT_TAG.as_bytes()[0];
        tag[1] = DEFAULT_TAG.as_bytes()[1];
        tag[2] = DEFAULT_TAG.as_bytes()[2];
        tag[3] = DEFAULT_TAG.as_bytes()[3];
        unsafe {
            Self::from_raw_parts(mem::MaybeUninit::new(tag), prio)
        }
    }

    #[inline]
    ///Creates new instance using:
    ///
    ///- `tag` - Log message tag, truncated to first 23 characters.
    ///- `prio` - Logging priority
    pub fn new(tag: &str, prio: LogPriority) -> Self {
        let mut tag_buffer = mem::MaybeUninit::<[u8; TAG_MAX_LEN + 1]>::zeroed();
        unsafe {
            ptr::copy_nonoverlapping(tag.as_ptr(), tag_buffer.as_mut_ptr() as *mut u8, cmp::min(tag.len(), TAG_MAX_LEN));
            Self::from_raw_parts(tag_buffer, prio)
        }
    }

    #[inline]
    ///Creates new instance with:
    ///
    ///- `tag` - Log message's tag as raw C string, that must be ending with 0. It is UB to pass anything else.
    ///- `prio` - Logging priority
    pub const unsafe fn from_raw_parts(tag: mem::MaybeUninit<[u8; TAG_MAX_LEN + 1]>, prio: LogPriority) -> Self {
        Self {
            tag,
            prio,
            buffer: mem::MaybeUninit::uninit(),
            len: 0,
        }
    }

    #[inline(always)]
    ///Returns content of written buffer.
    pub fn buffer(&self) -> &[u8] {
        unsafe {
            core::slice::from_raw_parts(self.buffer.as_ptr() as *const u8, self.len)
        }
    }

    #[inline(always)]
    fn as_mut_ptr(&mut self) -> *mut u8 {
        self.buffer.as_mut_ptr() as _
    }

    #[inline(always)]
    ///Flushes internal buffer, if any data is available.
    ///
    ///Namely it dumps stored data in buffer via `__android_log_write`.
    ///And resets buffered length to 0.
    pub fn flush(&mut self) {
        if self.len > 0 {
            self.inner_flush();
        }
    }

    fn inner_flush(&mut self) {
        unsafe {
            (self.buffer.as_mut_ptr() as *mut u8).add(self.len).write(0);
            __android_log_write(self.prio as _, self.tag.as_ptr() as _, self.buffer.as_ptr() as *const _);
        }
        self.len = 0;
    }

    #[inline]
    fn copy_data<'a>(&mut self, text: &'a [u8]) -> &'a [u8] {
        let mut write_len = cmp::min(BUFFER_CAPACITY.saturating_sub(self.len), text.len());

        #[inline(always)]
        fn is_char_boundary(text: &[u8], idx: usize) -> bool {
            if idx == 0 {
                return true;
            }

            match text.get(idx) {
                None => idx == text.len(),
                Some(&byte) => (byte as i8) >= -0x40
            }
        }

        #[inline(never)]
        #[cold]
        fn shift_by_char_boundary(text: &[u8], mut size: usize) -> usize {
            while !is_char_boundary(text, size) {
                size -= 1;
            }
            size
        }

        if !is_char_boundary(text, write_len) {
            //0 is always char boundary so 0 - 1 is impossible
            write_len = shift_by_char_boundary(text, write_len - 1);
        }

        unsafe {
            ptr::copy_nonoverlapping(text.as_ptr(), self.as_mut_ptr().add(self.len), write_len);
        }
        self.len += write_len;
        &text[write_len..]
    }

    ///Writes supplied text to the buffer.
    ///
    ///On buffer overflow, data is logged via `__android_log_write`
    ///and buffer is filled with the rest of `data`
    pub fn write_data(&mut self, mut data: &[u8]) {
        loop {
            data = self.copy_data(data);

            if data.is_empty() {
                break;
            } else {
                self.flush();
            }
        }
    }
}

impl fmt::Write for Writer {
    #[inline]
    fn write_str(&mut self, text: &str) -> fmt::Result {
        self.write_data(text.as_bytes());

        Ok(())
    }
}

#[cfg(feature = "std")]
impl std::io::Write for Writer {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.write_data(buf);
        Ok(buf.len())
    }

    #[inline(always)]
    fn flush(&mut self) -> std::io::Result<()> {
        self.flush();
        Ok(())
    }
}

impl Drop for Writer {
    #[inline]
    fn drop(&mut self) {
        self.flush();
    }
}

#[macro_export]
///`println` alternative to write message with INFO priority.
macro_rules! println {
    () => {{
        $crate::println!(" ");
    }};
    ($($arg:tt)*) => {{
        use core::fmt::Write;
        let mut writer = $crate::Writer::new_default($crate::LogPriority::INFO);
        let _ = write!(writer, $($arg)*);
        drop(writer);
    }}
}

#[macro_export]
///`eprintln` alternative to write message with ERROR priority.
macro_rules! eprintln {
    () => {{
        $crate::println!(" ");
    }};
    ($($arg:tt)*) => {{
        use core::fmt::Write;
        let mut writer = $crate::Writer::new_default($crate::LogPriority::ERROR);
        let _ = write!(writer, $($arg)*);
        drop(writer);
    }}
}

#[cfg(test)]
mod tests {
    use super::{LogPriority, Writer, TAG_MAX_LEN, DEFAULT_TAG};
    const TAG: &str = "Test";
    const TAG_OVERFLOW: &str = "123456789123456789123456789";

    #[test]
    fn should_truncate_tag() {
        let writer = Writer::new(TAG_OVERFLOW, LogPriority::WARN);
        assert!(TAG_OVERFLOW.len() > TAG_MAX_LEN);
        let tag = unsafe { core::slice::from_raw_parts(writer.tag.as_ptr() as *const u8, TAG_MAX_LEN) };
        assert_eq!(tag, TAG_OVERFLOW[..TAG_MAX_LEN].as_bytes());
    }

    #[test]
    fn should_normal_write() {
        let mut writer = Writer::new_default(LogPriority::WARN);

        let tag = unsafe { core::slice::from_raw_parts(writer.tag.as_ptr() as *const u8, DEFAULT_TAG.len()) };
        assert_eq!(tag, DEFAULT_TAG.as_bytes());
        assert_eq!(writer.prio, LogPriority::WARN);

        let data = TAG_OVERFLOW.as_bytes();

        writer.write_data(data);
        assert_eq!(writer.len, data.len());
        assert_eq!(writer.buffer(), data);

        writer.write_data(b" ");
        writer.write_data(data);
        let expected = format!("{} {}", TAG_OVERFLOW, TAG_OVERFLOW);
        assert_eq!(writer.len, expected.len());
        assert_eq!(writer.buffer(), expected.as_bytes());
    }

    #[test]
    fn should_handle_write_overflow() {
        let mut writer = Writer::new(TAG, LogPriority::WARN);
        let data = TAG_OVERFLOW.as_bytes();
        assert_eq!(unsafe { core::slice::from_raw_parts(writer.tag.as_ptr() as *const u8, TAG.len() + 1) }, &b"Test\0"[..]);

        //BUFFER_CAPACITY / TAG_OVERFLOW.len() = 148.xxx
        for idx in 1..=148 {
            writer.write_data(data);
            assert_eq!(writer.len, data.len() * idx);
        }

        writer.write_data(data);
        assert_eq!(writer.len, 23);
    }

    #[test]
    fn should_handle_write_overflow_outside_of_char_boundary() {
        let mut writer = Writer::new(TAG, LogPriority::WARN);
        let data = b"1234567891";

        for idx in 1..400 {
            writer.write_data(data);
            assert_eq!(writer.len, data.len() * idx);
        }

        assert_eq!(3990, writer.len);

        writer.write_data(b"12345678");
        assert_eq!(3998, writer.len);

        let unicode = "ロリ";
        writer.write_data(unicode.as_bytes());
        assert_eq!(writer.len, unicode.len());
        assert_eq!(writer.buffer(), unicode.as_bytes());
    }

}