2

It's a bit Rust question, but the type I used was anchor's Vec<Pubkey> type, so came here to ask. Here is the code.

pub fn set_tokens(&mut self, tokens: Vec<Pubkey>) -> Result<()> {
    msg!("unsorted tokens: {:?}", tokens);
    let mut sorted_tokens: Vec<_> = tokens.iter().collect();
    sorted_tokens.sort();
    msg!("sorted tokens: {:?}", sorted_tokens);

    Ok(())
}

And the result is like this.

unsorted tokens: [1111111QLbz7JHiBTspS962RLKV8GndWFwiEaqKM, 1111111ogCyDbaRMvkdsHB3qfdyFYaG1WtRUAfdh, 11111112D1oxKts8YPdTJRG5FzxTNpMtWmq8hkVx3, 11111112cMQwSC9qirWGjZM6gLGwW69X22mqwLLGP, 111111131h1vYVSYuKP6AhS86fbRdMw9XHiZAvAaj]
sorted tokens: [1111111QLbz7JHiBTspS962RLKV8GndWFwiEaqKM, 1111111ogCyDbaRMvkdsHB3qfdyFYaG1WtRUAfdh, 11111112D1oxKts8YPdTJRG5FzxTNpMtWmq8hkVx3, 11111112cMQwSC9qirWGjZM6gLGwW69X22mqwLLGP, 111111131h1vYVSYuKP6AhS86fbRdMw9XHiZAvAaj]

It's totally same. Sort didn't happen. Why is it like this? And how could I fix it?

3
  • I think they're already sorted!
    – Jon C
    Commented Jul 22 at 18:20
  • @JonC Oh, why do you think so? Those five addresses have seven 1s in front of them, and first one's 'Q' is later than second one's 'o', isn't it? And third's '2D' is later than fourth's '2c'. Hmm, if you see these sequence is already sorted, then is capital letter's sequence smaller than small letter?
    – Jung Chun
    Commented Jul 23 at 2:11
  • Pubkey uses the default derivation for Ord, which compares the array piece by piece: doc.rust-lang.org/std/cmp/… -- this is looking at the raw pubkey values, and not its base58 representation. If you want to sort the pubkeys by their base58 representation, you'll need to do something like sorted_tokens.sort_by(|a, b| a.to_string().cmp(b.to_string()));
    – Jon C
    Commented Jul 23 at 9:45

1 Answer 1

0

Seems like the written function is absolutely fine to sort Vec<String> but for Vec<Pubkey>, You have to make them as sortable type that implements Ord, then you can sort based on that.

For example,

Pubkey::from_str("11111112D1oxKts8YPdTJRG5FzxTNpMtWmq8hkVx3").unwrap(),

at your initialisation of the vector, then make few necessary changes in set_tokens function.

let mut sorted_tokens = tokens.clone();
sorted_tokens.sort_by(|a, b| a.to_bytes().cmp(&b.to_bytes()));

Explanation :

  1. The sort_by method is used with a custom comparison function that converts Pubkey to its byte representation using to_bytes(). This byte array is then compared to ensure proper ordering.
  2. Clone Tokens: To preserve the original order for the unsorted print, the tokens are cloned before sorting.

Cheers, Happy Coding!🤠

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.