Guest User

Untitled

a guest
Sep 25th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. #![feature(nll)]
  2.  
  3. fn strlen(buf: &[u8]) -> Option<usize> {
  4. buf.iter().position(|&c| c == b'\0')
  5. }
  6.  
  7. fn strcat(buf: &mut Option<&mut [u8]>, s: &[u8]) {
  8. if let Some(ref mut b) = buf {
  9. let l1 = strlen(b).expect("no terminator on buf");
  10. let l2 = strlen(s).expect("no terminator on s");
  11.  
  12. if l1 + l2 + 1 > b.len() {
  13. *buf = None;
  14. } else {
  15. for i in 0..l2 {
  16. b[l1 + i] = s[i];
  17. }
  18. b[l1 + l2] = b'\0';
  19. }
  20. }
  21. }
  22.  
  23. fn main() {
  24. let mut buf = [0u8; 10];
  25.  
  26. let mut string = Some(&mut buf[..]);
  27.  
  28. strcat(&mut string, b"ciao\0"); //non c'e' il \0 di default, quindi ho scritto anche \0
  29. strcat(&mut string, b"vb\0");
  30.  
  31. //NON posso accedere a buf perche' e' borrowed da string
  32. //questo non compilerebbe
  33. //println!("{}",buf[0]);
  34.  
  35. //NON posso accedere a string perche' potrebbe essere None
  36. //questo non compilerebbe
  37. //println!("{}",string[0]);
  38.  
  39. match string {
  40. Some(ref s) => println!("{:?}", s),
  41. None => println!("you did something bad"),
  42. }
  43.  
  44. strcat(&mut string, b"vbbbbbbbbb\0");
  45.  
  46. match string {
  47. Some(ref s) => println!("{:?}", s),
  48. None => println!("you did something bad"),
  49. }
  50. }
Add Comment
Please, Sign In to add comment