1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT 2 // file at the top-level directory of this distribution and at 3 // http://rust-lang.org/COPYRIGHT. 4 // 5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or 6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license 7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your 8 // option. This file may not be copied, modified, or distributed 9 // except according to those terms. 10 // 11 // Original authors: alexchrichton, bluss 12 13 // UTF-8 ranges and tags for encoding characters 14 const TAG_CONT: u8 = 0b1000_0000; 15 const TAG_TWO_B: u8 = 0b1100_0000; 16 const TAG_THREE_B: u8 = 0b1110_0000; 17 const TAG_FOUR_B: u8 = 0b1111_0000; 18 const MAX_ONE_B: u32 = 0x80; 19 const MAX_TWO_B: u32 = 0x800; 20 const MAX_THREE_B: u32 = 0x10000; 21 22 /// Placeholder 23 pub struct EncodeUtf8Error; 24 25 /// Encode a char into buf using UTF-8. 26 /// 27 /// On success, return the byte length of the encoding (1, 2, 3 or 4).<br> 28 /// On error, return `EncodeUtf8Error` if the buffer was too short for the char. 29 #[inline] 30 pub fn encode_utf8(ch: char, buf: &mut [u8]) -> Result<usize, EncodeUtf8Error> 31 { 32 let code = ch as u32; 33 if code < MAX_ONE_B && buf.len() >= 1 { 34 buf[0] = code as u8; 35 return Ok(1); 36 } else if code < MAX_TWO_B && buf.len() >= 2 { 37 buf[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; 38 buf[1] = (code & 0x3F) as u8 | TAG_CONT; 39 return Ok(2); 40 } else if code < MAX_THREE_B && buf.len() >= 3 { 41 buf[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; 42 buf[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; 43 buf[2] = (code & 0x3F) as u8 | TAG_CONT; 44 return Ok(3); 45 } else if buf.len() >= 4 { 46 buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; 47 buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; 48 buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; 49 buf[3] = (code & 0x3F) as u8 | TAG_CONT; 50 return Ok(4); 51 }; 52 Err(EncodeUtf8Error) 53 } 54 55