| ... | @@ -489,3 +489,37 @@ test "fmt.format" { | ... | @@ -489,3 +489,37 @@ test "fmt.format" { |
| 489 | assert(mem.eql(u8, result, "error union: error.InvalidChar\n")); | 489 | assert(mem.eql(u8, result, "error union: error.InvalidChar\n")); |
| 490 | } | 490 | } |
| 491 | } | 491 | } |
| | 492 | |
| | 493 | pub fn trim(buf: []const u8) -> []const u8 { |
| | 494 | var start: usize = 0; |
| | 495 | while (start < buf.len and isWhiteSpace(buf[start])) : (start += 1) { } |
| | 496 | |
| | 497 | var end: usize = buf.len; |
| | 498 | while (true) { |
| | 499 | if (end > start) { |
| | 500 | const new_end = end - 1; |
| | 501 | if (isWhiteSpace(buf[new_end])) { |
| | 502 | end = new_end; |
| | 503 | continue; |
| | 504 | } |
| | 505 | } |
| | 506 | break; |
| | 507 | |
| | 508 | } |
| | 509 | return buf[start..end]; |
| | 510 | } |
| | 511 | |
| | 512 | test "fmt.trim" { |
| | 513 | assert(mem.eql(u8, "abc", trim("\n abc \t"))); |
| | 514 | assert(mem.eql(u8, "", trim(" "))); |
| | 515 | assert(mem.eql(u8, "", trim(""))); |
| | 516 | assert(mem.eql(u8, "abc", trim(" abc"))); |
| | 517 | assert(mem.eql(u8, "abc", trim("abc "))); |
| | 518 | } |
| | 519 | |
| | 520 | pub fn isWhiteSpace(byte: u8) -> bool { |
| | 521 | return switch (byte) { |
| | 522 | ' ', '\t', '\n', '\r' => true, |
| | 523 | else => false, |
| | 524 | }; |
| | 525 | } |