bneradt commented on code in PR #12265: URL: https://github.com/apache/trafficserver/pull/12265#discussion_r2175849398
########## src/tscore/SnowflakeID.cc: ########## @@ -0,0 +1,138 @@ +/** + @file Implement Snowflake ID. + + @section license License + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#include "tscore/SnowflakeID.h" +#include "tscore/Diags.h" +#include "tscore/ink_base64.h" +#include "tscore/ink_hrtime.h" +#include "tsutil/DbgCtl.h" + +#include <cstdint> +#include <cinttypes> +#include <memory> +#include <mutex> +#include <string_view> + +std::atomic<uint64_t> SnowflakeIDUtils::global_machine_id{0}; + +uint64_t SnowflakeID::m_last_timestamp{0}; +uint64_t SnowflakeID::m_last_sequence{0}; +std::mutex SnowflakeID::m_mutex; + +DbgCtl dbg_ctl_snowflake{"snowflake"}; + +SnowflakeIDUtils::SnowflakeIDUtils(uint64_t id) : m_snowflake_value{id} {} + +void +SnowflakeIDUtils::set_machine_id(uint64_t machine_id) +{ + Dbg(dbg_ctl_snowflake, "Setting machine ID to: %" PRIx64, machine_id); + global_machine_id = machine_id; +} + +std::string_view +SnowflakeIDUtils::get_string() const +{ + if (m_id_string.empty()) { + // Base64 encode the snowflake ID as m_id_string. + size_t const max_encoded_size = ats_base64_encode_dstlen(sizeof(m_snowflake_value)); + auto encoded_buffer = std::make_unique<char[]>(max_encoded_size); + size_t encoded_length = 0; + auto *snowflake_char_p = reinterpret_cast<char const *>(&m_snowflake_value); + if (ats_base64_encode(snowflake_char_p, sizeof(m_snowflake_value), encoded_buffer.get(), max_encoded_size, &encoded_length)) { + m_id_string = std::string(encoded_buffer.get(), encoded_length); Review Comment: I see. Yes, it is good to make those const as well. Thanks for catching this. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: github-unsubscr...@trafficserver.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org