encodeStringValue encodes the value format: [type][expire][value] type: 1 byte expire: 8 bytes value: n bytes
(value []byte, ttl time.Duration)
| 531 | // expire: 8 bytes |
| 532 | // value: n bytes |
| 533 | func encodeStringValue(value []byte, ttl time.Duration) ([]byte, error) { |
| 534 | // Create a byte slice buf with a length of binary.MaxVarintLen64 |
| 535 | // to hold the encoded value and additional data. |
| 536 | buf := make([]byte, binary.MaxVarintLen64) |
| 537 | |
| 538 | // Set the first element of buf to represent the data structure type as String. |
| 539 | buf[0] = String |
| 540 | |
| 541 | // Use the variable bufIndex to keep track of the current index position in buf, |
| 542 | // starting from 1 to indicate the number of bytes written so far. |
| 543 | var bufIndex = 1 |
| 544 | |
| 545 | // The variable expire is used to store the expiration time, initially set to 0. |
| 546 | var expire int64 = 0 |
| 547 | |
| 548 | // Calculate the expiration time by adding ttl to the current time, |
| 549 | // convert it to nanoseconds, and store it in the expire variable. |
| 550 | if ttl != 0 { |
| 551 | expire = time.Now().Add(ttl).UnixNano() |
| 552 | } |
| 553 | |
| 554 | // Encode the expiration time expire as a variable-length integer |
| 555 | // and write it to the sub-slice of byte slice buf starting |
| 556 | // from the current index position bufIndex. |
| 557 | bufIndex += binary.PutVarint(buf[bufIndex:], expire) |
| 558 | |
| 559 | // Create a byte slice encValue with a length of bufIndex + len(value) |
| 560 | // to hold the encoded value and additional data. |
| 561 | encValue := make([]byte, bufIndex+len(value)) |
| 562 | |
| 563 | // Copy the encoded value from the beginning of buf |
| 564 | // to the corresponding position in encValue. |
| 565 | copy(encValue[:bufIndex], buf[:bufIndex]) |
| 566 | |
| 567 | // Copy the original value value to the remaining positions in encValue, |
| 568 | // starting from the index bufIndex. |
| 569 | copy(encValue[bufIndex:], value) |
| 570 | |
| 571 | return encValue, nil |
| 572 | } |
| 573 | |
| 574 | var ( |
| 575 | // ErrInvalidValue is returned if the value is invalid. |