/*
具体实现理论参见 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(49)-Valid Parentheses

    题目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...

  2. obj-c编程10:Foundation库中类的使用(5)[时间对象]

    隔了好久才有了这新的一篇,还是无奈的时间啊!so这次我们就着重谈谈它喽. F库中有很多时间相关的类,比如NSDate,NSTimeInterval,NSTimeZone,NSDateComponent ...

  3. RHEL6 不重启扫描新添加硬盘

    First find your host bus number grep mpt /sys/class/scsi_host/host?/proc_name Which should return a ...

  4. java线程的同步控制--重入锁ReentrantLock

    我们常用的synchronized关键字是一种最简单的线程同步控制方法,它决定了一个线程是否可以访问临界区资源.同时Object.wait() 和Object.notify()方法起到了线程等待和通知 ...

  5. Go中string转[]byte的陷阱

    Go中string转[]byte的陷阱html {overflow-x: initial !important;}#write, body { height: auto; }#write, #writ ...

  6. Collections模块下的Counter

    class Counter(dict) 这个类是dict的子类,对哈希类型的项进行计数,元素被存储为字典的键,他们的计数将作为字典的键值. 主要介绍两个方法: 1.初始化方法:__init__(*ar ...

  7. Ubuntu系统下配置IP地址方法介绍

    配置IP方式有两种: 1.通过命令直接配置 sudo ifconfig eth0 IP地址 netmask 子网掩码------配置IP地 sudo route add default gw 网关-- ...

  8. 推荐个Mac OSX下的Code Editor:Atom

    首先只是当Editor用,不是整成IDE级. 先说几个大家耳熟能详的: 1.Sublime,Sublime在Mac下的安装并不完全,CLI启动需要自己ln个链接.还有一些其他原因,比如Packages ...

  9. 与班尼特·胡迪一起拿奖学金(HZNU-2273)

    与班尼特·胡迪一起拿奖学金 AC Time Limit:  2 s      Memory Limit:   256 MB Description 班尼特·胡迪这学期的体测终于上80分了,当期末考试的 ...

  10. JAVAEE——BOS物流项目13:Quartz概述、创建定时任务、使用JavaMail发送邮件、HighCharts概述、实现区域分区分布图

    1 学习计划 1.Quartz概述 n Quartz介绍和下载 n 入门案例 n Quartz执行流程 n cron表达式 2.在BOS项目中使用Quartz创建定时任务 3.在BOS项目中使用Jav ...