/*
具体实现理论参见 mongodb官方  objectid生成策略
http://docs.mongodb.org/manual/reference/object-id/
ObjectId 是一个由12字节组成的bson数据,按照字节顺序,一次代表:
ObjectId is a 12-byte BSON type, constructed using:
4个字节代表1970年元月一日到现在毫秒数  UNIX时间戳
a 4-byte value representing the seconds since the Unix epoch,
3个字节代表机器的唯一标识符    表示运行的机器
a 3-byte machine identifier,
2个字节代表进程的id 表示生成此_id的进程
a 2-byte process id, and
3个字节代表计数器,开始带着一个随机数   由一个随机数开始的计数器生成的值
a 3-byte counter, starting with a random value.

*/

package objectid

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "math/rand"
    "os"
    "sync/atomic"
    "time"
)

var staticMachine = getMachineHash()  //获取机器的id
var staticIncrement = getRandomNumber()//获取随机数
var staticPid = int32(os.Getpid())//获取进程id
//
type ObjectId struct {
    timestamp int64
    machine   int32
    pid       int32
    increment int32
}
//
func New() *ObjectId {
    timestamp := time.Now().Unix()
    return &ObjectId{timestamp, staticMachine, staticPid, atomic.AddInt32(&staticIncrement, 1) & 0xffffff}
}
//
func Parse(input string) *ObjectId {
    if len(input) == 0 {
        panic("The input is empty.")
    }
    if value, ok := tryParse(input); ok {
        return value
    }
    panic(fmt.Sprintf("%s is not a valid 24 digit hex string.", input))
}
//
func (this *ObjectId) Timestamp() int64 {
    return this.timestamp
}
//
func (this *ObjectId) Machine() int32 {
    return this.machine
}
//
func (this *ObjectId) Pid() int32 {
    return this.pid
}
//
func (this *ObjectId) Increment() int32 {
    return this.increment & 0xffffff
}
//
func (this *ObjectId) CreationTime() time.Time {
    return time.Unix(this.timestamp, 0)
}
//
func (this *ObjectId) Equal(other *ObjectId) bool {
    return this.timestamp == other.timestamp &&
        this.machine == other.machine &&
        this.pid == other.pid &&
        this.increment == other.increment
}
//
func (this *ObjectId) String() string {
    array := []byte{
        byte(this.timestamp >> 0x18),
        byte(this.timestamp >> 0x10),
        byte(this.timestamp >> 8),
        byte(this.timestamp),
        byte(this.machine >> 0x10),
        byte(this.machine >> 8),
        byte(this.machine),
        byte(this.pid >> 8),
        byte(this.pid),
        byte(this.increment >> 0x10),
        byte(this.increment >> 8),
        byte(this.increment),
    }
    return hex.EncodeToString(array)
}
//获取机器唯一标识符
func getMachineHash() int32 {
    machineName, err := os.Hostname()
    if err != nil {
        panic(err)
    }
    buf := md5.Sum([]byte(machineName))
    return (int32(buf[0])<<0x10 + int32(buf[1])<<8) + int32(buf[2])
}
//获取随机数开始的计数器生成的值
func getRandomNumber() int32 {
    rand.Seed(time.Now().UnixNano())
    return rand.Int31()
}
//从字符串objectid  解析成为ObjectId
func tryParse(input string) (*ObjectId, bool) {
    if len(input) != 0x18 {
        return nil, false
    }
    array, err := hex.DecodeString(input) //十六进制的字符串 转化为字节切片 
    if err != nil {
        return nil, false
    }
    return &ObjectId{
        timestamp: int64(array[0])<<0x18 + int64(array[1])<<0x10 + int64(array[2])<<8 + int64(array[3]),
               //转化为十进制的int64  新纪元时间  毫秒
        machine:   int32(array[4])<<0x10 + int32(array[5])<<8 + int32(array[6]),
               //转化为十进制的int32数据   机器唯一标识符
        pid:       int32(array[7])<<8 + int32(array[8]),
              // 当前进程id
        increment: int32(array[9])<<0x10 + (int32(array[10]) << 8) + int32(array[11]),
              // 随机数开始的计数器生成的值
    }, true
}

objectid.go源码阅读的更多相关文章

  1. 【原】FMDB源码阅读(三)

    [原]FMDB源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 FMDB比较优秀的地方就在于对多线程的处理.所以这一篇主要是研究FMDB的多线程处理的实现.而 ...

  2. 【原】FMDB源码阅读(二)

    [原]FMDB源码阅读(二) 本文转载请注明出处 -- polobymulberry-博客园 1. 前言 上一篇只是简单地过了一下FMDB一个简单例子的基本流程,并没有涉及到FMDB的所有方方面面,比 ...

  3. 【原】FMDB源码阅读(一)

    [原]FMDB源码阅读(一) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 说实话,之前的SDWebImage和AFNetworking这两个组件我还是使用过的,但是对于 ...

  4. 【原】AFNetworking源码阅读(六)

    [原]AFNetworking源码阅读(六) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 这一篇的想讲的,一个就是分析一下AFSecurityPolicy文件,看看AF ...

  5. 【原】AFNetworking源码阅读(五)

    [原]AFNetworking源码阅读(五) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇中提及到了Multipart Request的构建方法- [AFHTTP ...

  6. 【原】AFNetworking源码阅读(四)

    [原]AFNetworking源码阅读(四) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇还遗留了很多问题,包括AFURLSessionManagerTaskDe ...

  7. 【原】AFNetworking源码阅读(三)

    [原]AFNetworking源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇的话,主要是讲了如何通过构建一个request来生成一个data tas ...

  8. 【原】AFNetworking源码阅读(二)

    [原]AFNetworking源码阅读(二) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇中我们在iOS Example代码中提到了AFHTTPSessionMa ...

  9. 【原】AFNetworking源码阅读(一)

    [原]AFNetworking源码阅读(一) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 AFNetworking版本:3.0.4 由于我平常并没有经常使用AFNetw ...

随机推荐

  1. LeetCode(53)-Binary Tree Paths

    题目: Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree ...

  2. LeetCode(29)-Plus One

    题目: Given a non-negative number represented as an array of digits, plus one to the number. The digit ...

  3. 64位ubuntu安装N64模拟器mupen64

    我们知道在windows平台下模拟器多如牛毛,N64的模拟器也不例外.而linux下对于想玩N64的童鞋们有啥好办法呢?我通过度娘找到一款开源的N64模拟器mupen64,其官方网址为:http:// ...

  4. 将文件内容转化为byte数组返回

    如何将文件内容转化为byte数组并返回呢?对于这个问题,我献上我第一次成功的代码~ package com.succez.task1; import java.io.ByteArrayOutputSt ...

  5. 面向对象(this的问题二)

    <!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content=&q ...

  6. postgresql 异步流复制hot standby搭建

    先说说环境,主从库版本都是9.5,主库在CentOS物理机上,从库在Ubuntu虚拟机上 一.主库上的操作: 1.添加同步访问规则: host   replication     dbuser     ...

  7. SQLServer Merger Using语法使用和注意点

    SQL多表关联数据更新,如果数据量比较少的情况下,用Update也是可以的:脚本如下: UPDATE NA_AgentGrpOrder SET AttrServSIItem=b.AttrValue F ...

  8. RocketMQ源码 — 八、 RocketMQ消息重试

    RocketMQ的消息重试包含了producer发送消息的重试和consumer消息消费的重试. producer发送消息重试 producer在发送消息的时候如果发送失败了,RocketMQ会自动重 ...

  9. java.util.logging的使用

    秉承着某种执念我今天决定不用Logback而是和Java的logging肛到底,现在总结一下研究成果: 日志等级 日志等级有七种,severe,warning,info,fine,finer,fine ...

  10. Java基础:Java的四种引用

    在Java基础:java虚拟机(JVM)中,我们提到了Java的四种引用.包括:强引用,软引用,弱引用,虚引用.这篇博客将详细的讲解一下这四种引用. 1. 强引用 2. 软引用 3. 弱引用 4. 虚 ...